@octocodeai/octocode-tools-core 16.6.3 → 17.0.2

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 (252) hide show
  1. package/README.md +22 -50
  2. package/dist/direct.js +33 -38
  3. package/dist/github/botFilter.d.ts +1 -0
  4. package/dist/github/client.d.ts +6 -0
  5. package/dist/github/directoryFetch/fetchDirectoryContents.d.ts +3 -0
  6. package/dist/github/directoryFetch/fetchFileContentToDisk.d.ts +3 -0
  7. package/dist/github/directoryFetch/helpers.d.ts +35 -0
  8. package/dist/github/directoryFetch.d.ts +3 -6
  9. package/dist/github/fileContentPagination.d.ts +9 -0
  10. package/dist/github/fileContentProcess.d.ts +1 -8
  11. package/dist/github/fileContentRaw/fetch.d.ts +20 -0
  12. package/dist/github/fileContentRaw/pathSuggestions.d.ts +3 -0
  13. package/dist/github/fileContentRaw.d.ts +2 -12
  14. package/dist/github/githubAPI.d.ts +4 -1
  15. package/dist/github/history.d.ts +6 -2
  16. package/dist/github/issues/fetchers.d.ts +7 -0
  17. package/dist/github/issues/helpers.d.ts +32 -0
  18. package/dist/github/issues/orchestrator.d.ts +4 -0
  19. package/dist/github/issues/types.d.ts +72 -0
  20. package/dist/github/issues.d.ts +3 -0
  21. package/dist/github/prContentFetcher/comments.d.ts +11 -0
  22. package/dist/github/prContentFetcher/commits.d.ts +27 -0
  23. package/dist/github/prContentFetcher/flags.d.ts +21 -0
  24. package/dist/github/prContentFetcher/transform.d.ts +5 -0
  25. package/dist/github/prContentFetcher.d.ts +2 -5
  26. package/dist/github/pullRequestSearch/restSearch.d.ts +6 -0
  27. package/dist/github/pullRequestSearch.d.ts +1 -1
  28. package/dist/github/queryBuilders/base.d.ts +25 -0
  29. package/dist/github/queryBuilders/codeAndRepo.d.ts +20 -0
  30. package/dist/github/queryBuilders/issues.d.ts +42 -0
  31. package/dist/github/queryBuilders/pullRequests.d.ts +13 -0
  32. package/dist/github/queryBuilders.d.ts +4 -12
  33. package/dist/github/releases.d.ts +37 -0
  34. package/dist/github/repoStructure/contentResolution.d.ts +12 -0
  35. package/dist/github/repoStructure/fetchOrchestration.d.ts +7 -0
  36. package/dist/github/repoStructure/resultBuilder.d.ts +22 -0
  37. package/dist/github/repoStructure.d.ts +1 -7
  38. package/dist/github/repoStructureTree.d.ts +38 -0
  39. package/dist/github/responseHeaders.d.ts +2 -0
  40. package/dist/github/searchKeyword.d.ts +2 -0
  41. package/dist/index.d.ts +1 -4
  42. package/dist/index.js +35 -40
  43. package/dist/oql/adapters/github/execute.d.ts +16 -0
  44. package/dist/oql/adapters/github/provider-diagnostics.d.ts +14 -0
  45. package/dist/oql/adapters/github/shared.d.ts +75 -0
  46. package/dist/oql/adapters/github.d.ts +11 -0
  47. package/dist/oql/adapters/graphView/filters.d.ts +25 -0
  48. package/dist/oql/adapters/graphView/nativeEdges.d.ts +5 -0
  49. package/dist/oql/adapters/graphView.d.ts +17 -16
  50. package/dist/oql/adapters/local/code.d.ts +3 -0
  51. package/dist/oql/adapters/local/codeBoolean.d.ts +3 -0
  52. package/dist/oql/adapters/local/fileRowOps.d.ts +11 -0
  53. package/dist/oql/adapters/local/files.d.ts +3 -0
  54. package/dist/oql/adapters/local/filesBoolean.d.ts +10 -0
  55. package/dist/oql/adapters/local/filesContentLeaf.d.ts +12 -0
  56. package/dist/oql/adapters/local/filesUniverse.d.ts +6 -0
  57. package/dist/oql/adapters/local/findToolType.d.ts +10 -0
  58. package/dist/oql/adapters/local/predicates.d.ts +18 -0
  59. package/dist/oql/adapters/local/scope.d.ts +14 -0
  60. package/dist/oql/adapters/local/searchToolType.d.ts +7 -0
  61. package/dist/oql/adapters/local/structureContent.d.ts +6 -0
  62. package/dist/oql/adapters/local/types.d.ts +34 -0
  63. package/dist/oql/adapters/local.d.ts +3 -7
  64. package/dist/oql/adapters/researchTargets/diff.d.ts +16 -0
  65. package/dist/oql/adapters/researchTargets/graph.d.ts +3 -0
  66. package/dist/oql/adapters/researchTargets/history.d.ts +20 -0
  67. package/dist/oql/adapters/researchTargets/pagination.d.ts +54 -0
  68. package/dist/oql/adapters/researchTargets/repositories.d.ts +4 -0
  69. package/dist/oql/adapters/researchTargets/research.d.ts +3 -0
  70. package/dist/oql/adapters/researchTargets/rows.d.ts +16 -0
  71. package/dist/oql/adapters/researchTargets/semantics.d.ts +3 -0
  72. package/dist/oql/adapters/researchTargets/shared.d.ts +11 -0
  73. package/dist/oql/adapters/researchTargets.d.ts +4 -46
  74. package/dist/oql/defaults.d.ts +1 -1
  75. package/dist/oql/index.js +34 -39
  76. package/dist/oql/normalize/batch.d.ts +2 -0
  77. package/dist/oql/normalize/materialize.d.ts +2 -0
  78. package/dist/oql/normalize/params.d.ts +2 -0
  79. package/dist/oql/normalize/query.d.ts +2 -0
  80. package/dist/oql/normalize/scope.d.ts +2 -0
  81. package/dist/oql/normalize/shared.d.ts +7 -0
  82. package/dist/oql/normalize/source.d.ts +2 -0
  83. package/dist/oql/normalize/where.d.ts +2 -0
  84. package/dist/oql/normalize.d.ts +19 -4
  85. package/dist/oql/planner/planDiagnostics.d.ts +13 -0
  86. package/dist/oql/planner/predicateRouting.d.ts +35 -0
  87. package/dist/oql/predicateUtils.d.ts +3 -0
  88. package/dist/oql/research/analyze/manifest-scan.d.ts +4 -0
  89. package/dist/oql/research/analyze/source-graph.d.ts +7 -0
  90. package/dist/oql/research/analyze/symbol-scoring.d.ts +4 -0
  91. package/dist/oql/research/analyze/types.d.ts +163 -0
  92. package/dist/oql/research/analyze/utils.d.ts +16 -0
  93. package/dist/oql/research/analyze.d.ts +2 -133
  94. package/dist/oql/research/packets/builders.d.ts +4 -0
  95. package/dist/oql/research/packets/types.d.ts +91 -0
  96. package/dist/oql/research/packets.d.ts +21 -80
  97. package/dist/oql/run/batch.d.ts +3 -0
  98. package/dist/oql/run/continuations/records.d.ts +19 -0
  99. package/dist/oql/run/continuations/registry.d.ts +22 -0
  100. package/dist/oql/run/continuations/semantics.d.ts +3 -0
  101. package/dist/oql/run/continuations/types.d.ts +12 -0
  102. package/dist/oql/run/dryRun.d.ts +11 -0
  103. package/dist/oql/run/paths.d.ts +15 -0
  104. package/dist/oql/run/proofGrades.d.ts +8 -0
  105. package/dist/oql/run/select.d.ts +10 -0
  106. package/dist/oql/run/single.d.ts +22 -0
  107. package/dist/oql/run.d.ts +4 -31
  108. package/dist/oql/schema/predicates.d.ts +12 -0
  109. package/dist/oql/schema.d.ts +50 -35
  110. package/dist/oql/schemeText.d.ts +10 -13
  111. package/dist/oql/shorthand/predicates.d.ts +15 -0
  112. package/dist/oql/shorthand/query-controls.d.ts +18 -0
  113. package/dist/oql/shorthand/target-params.d.ts +9 -0
  114. package/dist/oql/shorthand/types.d.ts +159 -0
  115. package/dist/oql/shorthand/utils.d.ts +7 -0
  116. package/dist/oql/shorthand.d.ts +2 -171
  117. package/dist/oql/targetParams.d.ts +0 -13
  118. package/dist/oql/transformers/github/code.d.ts +1 -9
  119. package/dist/oql/types/diagnostics.d.ts +22 -0
  120. package/dist/oql/types/envelope.d.ts +78 -0
  121. package/dist/oql/types/guards.d.ts +9 -0
  122. package/dist/oql/types/planner.d.ts +46 -0
  123. package/dist/oql/types/predicates.d.ts +93 -0
  124. package/dist/oql/types/query.d.ts +143 -0
  125. package/dist/oql/types/recordData.d.ts +127 -0
  126. package/dist/oql/types/recordRows.d.ts +48 -0
  127. package/dist/oql/types/results.d.ts +118 -0
  128. package/dist/oql/types/targets.d.ts +22 -0
  129. package/dist/oql/types.d.ts +17 -640
  130. package/dist/providers/github/paginationMetadata.d.ts +12 -0
  131. package/dist/providers/providerResults.d.ts +0 -1
  132. package/dist/schema.js +2 -2
  133. package/dist/scheme/pagination.d.ts +65 -0
  134. package/dist/shared/config/index.js +1 -1
  135. package/dist/shared/credentials/index.js +2 -2
  136. package/dist/shared/credentials/testing.js +1 -1
  137. package/dist/shared/languageSelectors/classify.d.ts +15 -0
  138. package/dist/shared/languageSelectors/data.d.ts +12 -0
  139. package/dist/shared/languageSelectors.d.ts +3 -23
  140. package/dist/shared/paths.d.ts +0 -4
  141. package/dist/shared/paths.js +1 -1
  142. package/dist/shared/session/index.js +1 -1
  143. package/dist/shared/session/statsDefaults.d.ts +1 -2
  144. package/dist/tools/directToolCatalog/toolCatalogDefinitions.d.ts +68 -0
  145. package/dist/tools/directToolCatalog/toolCommandPatternQueries.d.ts +4 -0
  146. package/dist/tools/directToolCatalog/toolCommandPatterns.d.ts +4 -0
  147. package/dist/tools/directToolCatalog/toolInputPreparation.d.ts +12 -0
  148. package/dist/tools/directToolCatalog/toolSchemaIntrospection.d.ts +19 -0
  149. package/dist/tools/directToolCatalog.meta.d.ts +10 -67
  150. package/dist/tools/github_clone_repo/cache.d.ts +1 -5
  151. package/dist/tools/github_clone_repo/cachePaths.d.ts +5 -0
  152. package/dist/tools/github_fetch_content/finalizer/entryParsers.d.ts +9 -0
  153. package/dist/tools/github_fetch_content/finalizer/types.d.ts +101 -0
  154. package/dist/tools/github_fetch_content/finalizer.d.ts +1 -7
  155. package/dist/tools/github_fetch_content/scheme.d.ts +42 -9
  156. package/dist/tools/github_fetch_content/types.d.ts +1 -2
  157. package/dist/tools/github_search_code/execution.d.ts +9 -0
  158. package/dist/tools/github_search_code/finalizer/build.d.ts +4 -0
  159. package/dist/tools/github_search_code/finalizer/groups.d.ts +23 -0
  160. package/dist/tools/github_search_code/finalizer/ranking.d.ts +12 -0
  161. package/dist/tools/github_search_code/finalizer.d.ts +2 -6
  162. package/dist/tools/github_search_code/scheme.d.ts +29 -2
  163. package/dist/tools/github_search_pull_requests/contentResponse/commentsShaping.d.ts +68 -0
  164. package/dist/tools/github_search_pull_requests/contentResponse/fileSurfaces.d.ts +52 -0
  165. package/dist/tools/github_search_pull_requests/contentResponse/nextCalls.d.ts +17 -0
  166. package/dist/tools/github_search_pull_requests/contentResponse/pagination.d.ts +63 -0
  167. package/dist/tools/github_search_pull_requests/contentResponse.d.ts +1 -15
  168. package/dist/tools/github_search_pull_requests/execution/commitsMode.d.ts +4 -0
  169. package/dist/tools/github_search_pull_requests/execution/issuesMode.d.ts +4 -0
  170. package/dist/tools/github_search_pull_requests/execution/pullRequestsMode.d.ts +4 -0
  171. package/dist/tools/github_search_pull_requests/execution/releasesMode.d.ts +4 -0
  172. package/dist/tools/github_search_pull_requests/execution/types.d.ts +6 -0
  173. package/dist/tools/github_search_pull_requests/execution.d.ts +1 -4
  174. package/dist/tools/github_search_pull_requests/scheme.d.ts +11 -1
  175. package/dist/tools/github_search_repos/execution/pagination.d.ts +39 -0
  176. package/dist/tools/github_search_repos/execution/queryVariants.d.ts +38 -0
  177. package/dist/tools/github_search_repos/execution/ranking.d.ts +4 -0
  178. package/dist/tools/github_search_repos/execution.d.ts +3 -71
  179. package/dist/tools/github_search_repos/scheme.d.ts +8 -0
  180. package/dist/tools/github_view_repo_structure/types.d.ts +2 -0
  181. package/dist/tools/local_fetch_content/fetchContent/extraction.d.ts +15 -0
  182. package/dist/tools/local_fetch_content/fetchContent/pagination.d.ts +38 -0
  183. package/dist/tools/local_fetch_content/fetchContent/validation.d.ts +26 -0
  184. package/dist/tools/local_fetch_content/fetchContent.d.ts +2 -0
  185. package/dist/tools/local_fetch_content/scheme.d.ts +25 -1
  186. package/dist/tools/local_find_files/scheme.d.ts +32 -0
  187. package/dist/tools/local_ripgrep/rankingProfile/rankingProfiles.d.ts +70 -0
  188. package/dist/tools/local_ripgrep/rankingProfile/rankingResults.d.ts +47 -0
  189. package/dist/tools/local_ripgrep/rankingProfile/rankingScoring.d.ts +41 -0
  190. package/dist/tools/local_ripgrep/rankingProfile.d.ts +16 -95
  191. package/dist/tools/local_ripgrep/ripgrepResultBuilder/buildResult.d.ts +10 -0
  192. package/dist/tools/local_ripgrep/ripgrepResultBuilder/searchNext.d.ts +46 -0
  193. package/dist/tools/local_ripgrep/ripgrepResultBuilder.d.ts +2 -18
  194. package/dist/tools/local_ripgrep/scheme.d.ts +95 -0
  195. package/dist/tools/local_view_structure/scheme.d.ts +31 -0
  196. package/dist/tools/lsp/semantic_content/scheme.d.ts +61 -0
  197. package/dist/tools/lsp/semantic_content/semanticAnchored.d.ts +7 -0
  198. package/dist/tools/lsp/semantic_content/semanticEnvelopes/callEnvelopes.d.ts +5 -0
  199. package/dist/tools/lsp/semantic_content/semanticEnvelopes/envelopeHelpers.d.ts +20 -0
  200. package/dist/tools/lsp/semantic_content/semanticEnvelopes/locationEnvelopes.d.ts +13 -0
  201. package/dist/tools/lsp/semantic_content/semanticEnvelopes.d.ts +3 -0
  202. package/dist/tools/lsp/semantic_content/semanticFileOps/anchor.d.ts +24 -0
  203. package/dist/tools/lsp/semantic_content/semanticFileOps/documentSymbols.d.ts +27 -0
  204. package/dist/tools/lsp/semantic_content/semanticFileOps/workspaceSymbolsAndDiagnostics.d.ts +20 -0
  205. package/dist/tools/lsp/semantic_content/semanticFileOps.d.ts +8 -0
  206. package/dist/tools/lsp/semantic_content/semanticPresentation.d.ts +53 -0
  207. package/dist/tools/lsp/shared/semanticTypes.d.ts +6 -0
  208. package/dist/tools/package_search/execution.d.ts +8 -0
  209. package/dist/tools/package_search/scheme.d.ts +43 -2
  210. package/dist/tools/providerMappers/codeSearch.d.ts +66 -0
  211. package/dist/tools/providerMappers/fileContent.d.ts +28 -0
  212. package/dist/tools/providerMappers/pullRequests.d.ts +158 -0
  213. package/dist/tools/providerMappers/repoSearch.d.ts +30 -0
  214. package/dist/tools/providerMappers/repoStructure.d.ts +20 -0
  215. package/dist/tools/providerMappers/shared.d.ts +23 -0
  216. package/dist/tools/providerMappers.d.ts +9 -294
  217. package/dist/tools/toolConfig.d.ts +0 -2
  218. package/dist/tools/toolMetadata/descriptionOverrides.d.ts +4 -0
  219. package/dist/tools/toolSchemaImports.d.ts +13 -0
  220. package/dist/utils/contextUtils.d.ts +5 -16
  221. package/dist/utils/core/types.d.ts +2 -24
  222. package/dist/utils/exec/spawn/env.d.ts +5 -0
  223. package/dist/utils/exec/spawn/wrappers.d.ts +29 -0
  224. package/dist/utils/exec/spawn.d.ts +2 -34
  225. package/dist/utils/file/toolHelpers.d.ts +12 -0
  226. package/dist/utils/http/cache/conditional.d.ts +21 -0
  227. package/dist/utils/http/cache/dataCache.d.ts +6 -0
  228. package/dist/utils/http/cache/key.d.ts +1 -0
  229. package/dist/utils/http/cache/management.d.ts +9 -0
  230. package/dist/utils/http/cache/store.d.ts +28 -0
  231. package/dist/utils/http/cache.d.ts +4 -16
  232. package/dist/utils/markdownOutline.d.ts +0 -2
  233. package/dist/utils/package/npm/npmDeprecation.d.ts +5 -0
  234. package/dist/utils/package/npm/npmDetailsFetchers.d.ts +15 -0
  235. package/dist/utils/package/npm/npmMappers.d.ts +12 -0
  236. package/dist/utils/package/npm/npmRegistry.d.ts +79 -0
  237. package/dist/utils/package/npm/npmSearchStrategies.d.ts +6 -0
  238. package/dist/utils/package/npm.d.ts +2 -8
  239. package/dist/utils/pagination/boundary.d.ts +5 -5
  240. package/dist/utils/response/bulk/pagination.d.ts +6 -0
  241. package/dist/utils/response/bulk/queries.d.ts +19 -0
  242. package/dist/utils/response/bulk/response.d.ts +4 -0
  243. package/dist/utils/response/bulk.d.ts +2 -6
  244. package/package.json +42 -35
  245. package/dist/tools/local_binary_inspect/archiveOps.d.ts +0 -24
  246. package/dist/tools/local_binary_inspect/binaryInspector.d.ts +0 -86
  247. package/dist/tools/local_binary_inspect/binaryOps.d.ts +0 -27
  248. package/dist/tools/local_binary_inspect/decompressOps.d.ts +0 -16
  249. package/dist/tools/local_binary_inspect/execution.d.ts +0 -4
  250. package/dist/tools/local_binary_inspect/scheme.d.ts +0 -144
  251. package/dist/tools/local_ripgrep/lspBoost.d.ts +0 -54
  252. package/dist/utils/parsers/ripgrep.d.ts +0 -11
package/dist/oql/index.js CHANGED
@@ -5,48 +5,43 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- var qS=Object.defineProperty;var y=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var WS=(e,t)=>{for(var n in t)qS(e,n,{get:t[n],enumerable:!0})};function Yu(e){return Array.isArray(e.queries)}function Xu(e){return Array.isArray(e.queries)}function Ju(e){return Array.isArray(e.children)}var Je,_n,Mo,Ku,At=y(()=>{"use strict";Je=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],_n=["fixes","dataflow"],Mo=["packages","repositories"],Ku={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});import{z as g}from"zod";var Do,ya,VS,Zu,ed,KS,YS,ln,td,XS,JS,Wt,nd,rd,od,id,Pr,sd,ZS,ad,cd,ld,ud,No,ba,Ra,un,In=y(()=>{"use strict";At();Do=g.lazy(()=>g.union([g.strictObject({kind:g.literal("local"),path:g.string().min(1)}),g.strictObject({kind:g.literal("github"),repo:g.string().min(1).optional(),owner:g.string().min(1).optional(),ref:g.string().min(1).optional()}),g.strictObject({kind:g.literal("materialized"),localPath:g.string().min(1),source:Do.optional()}),g.strictObject({kind:g.literal("npm")})])),ya=g.union([g.string(),g.array(g.string()).max(100)]),VS=g.strictObject({path:ya.optional(),language:ya.optional(),include:g.array(g.string()).max(100).optional(),exclude:g.array(g.string()).max(100).optional(),excludeDir:g.array(g.string()).max(100).optional(),hidden:g.boolean().optional(),noIgnore:g.boolean().optional(),minDepth:g.number().int().min(0).max(64).optional(),maxDepth:g.number().int().min(0).max(64).optional()}).optional(),Zu=g.enum(["smart","sensitive","insensitive"]),ed=g.string().max(1e4),KS=g.strictObject({id:g.string().optional(),kind:g.literal("text"),value:ed,case:Zu.optional(),wholeWord:g.boolean().optional()}),YS=g.strictObject({id:g.string().optional(),kind:g.literal("regex"),value:ed,dialect:g.enum(["rust","pcre2","provider"]).optional(),case:Zu.optional(),wholeWord:g.boolean().optional(),multiline:g.boolean().optional(),dotAll:g.boolean().optional()}),ln=g.lazy(()=>g.strictObject({pattern:g.string().optional(),kind:g.string().optional(),inside:ln.optional(),has:ln.optional(),not:ln.optional(),all:g.array(ln).optional(),any:g.array(ln).optional(),stopBy:g.literal("end").optional()})),td=g.union([ln,g.string().min(1)]),XS=g.strictObject({id:g.string().optional(),kind:g.literal("structural"),lang:g.string().min(1),pattern:g.string().optional(),rule:td.optional()}),JS=g.strictObject({id:g.string().optional(),kind:g.literal("field"),field:g.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:g.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:g.unknown().optional()}),Wt=g.lazy(()=>g.discriminatedUnion("kind",[g.strictObject({kind:g.literal("all"),id:g.string().optional(),of:g.array(Wt).min(1)}),g.strictObject({kind:g.literal("any"),id:g.string().optional(),of:g.array(Wt).min(1)}),g.strictObject({kind:g.literal("not"),id:g.string().optional(),predicate:Wt}),KS,YS,XS,JS])),nd=g.strictObject({mode:g.enum(["never","auto","required"]),strategy:g.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:g.boolean().optional(),forceRefresh:g.boolean().optional()}),rd=g.strictObject({content:g.strictObject({range:g.strictObject({startLine:g.number().int().min(1).optional(),endLine:g.number().int().min(1).optional(),contextLines:g.number().int().min(0).max(100).optional()}).optional(),match:g.strictObject({text:g.string(),regex:g.boolean().optional(),caseSensitive:g.boolean().optional()}).optional(),contentView:g.enum(["exact","compact","symbols"]).optional(),charOffset:g.number().int().min(0).max(1e8).optional(),charLength:g.number().int().min(1).max(5e4).optional(),fullContent:g.boolean().optional()}).optional(),tree:g.strictObject({maxDepth:g.number().int().min(0).max(64).optional(),pattern:g.string().optional(),includeSizes:g.boolean().optional(),extensions:g.array(g.string()).optional(),filesOnly:g.boolean().optional(),directoriesOnly:g.boolean().optional(),sortBy:g.enum(["name","size","time","extension"]).optional(),reverse:g.boolean().optional()}).optional()}),od=g.strictObject({search:g.strictObject({countLinesPerFile:g.boolean().optional(),countMatchesPerFile:g.boolean().optional(),onlyMatching:g.boolean().optional(),unique:g.boolean().optional(),countUnique:g.boolean().optional(),contextLines:g.number().int().min(0).max(100).optional(),invertMatch:g.boolean().optional(),matchWindow:g.number().int().min(0).optional(),matchContentLength:g.number().int().min(1).optional(),maxMatchesPerFile:g.number().int().min(1).optional(),matchPage:g.number().int().min(1).optional(),sort:g.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:g.boolean().optional(),rankingProfile:g.string().optional(),debugRanking:g.boolean().optional()}).optional(),budget:g.strictObject({maxFiles:g.number().int().min(1).optional(),maxCandidates:g.number().int().min(1).optional(),maxBytes:g.number().int().min(1).optional(),maxMaterializedBytes:g.number().int().min(1).optional(),maxPlanNodes:g.number().int().min(1).optional(),maxBooleanExpansion:g.number().int().min(1).optional(),timeoutMs:g.number().int().min(1).optional()}).optional()}),id=g.enum(["discovery","paginated","detailed"]),Pr=g.strictObject({schema:g.literal("oql"),id:g.string().optional(),target:g.enum(Je),from:Do.optional(),scope:VS,where:Wt.optional(),materialize:nd.optional(),fetch:rd.optional(),select:g.array(g.string()).optional(),view:id.optional(),controls:od.optional(),limit:g.number().int().min(1).optional(),page:g.number().int().min(1).optional(),itemsPerPage:g.number().int().min(1).optional(),params:g.record(g.string(),g.unknown()).optional(),explain:g.boolean().optional()}),sd=g.strictObject({schema:g.literal("oql"),id:g.string().optional(),queries:g.array(Pr).min(1).max(5),combine:g.enum(["independent","merge"]).optional(),limit:g.number().int().min(1).optional(),page:g.number().int().min(1).optional(),itemsPerPage:g.number().int().min(1).optional(),explain:g.boolean().optional()}),ZS=g.union([Pr,sd]),ad=[...Je,..._n],cd={schema:g.literal("oql").optional(),id:g.string().optional(),mainResearchGoal:g.string().optional(),researchGoal:g.string().optional(),reasoning:g.string().optional()},ld={...cd,target:g.enum(ad).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Do.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:Wt.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:g.union([nd,g.enum(["never","auto","required"])]).optional(),fetch:rd.optional(),select:g.array(g.string()).optional(),view:id.optional(),controls:od.optional(),limit:g.number().int().min(1).optional(),page:g.number().int().min(1).optional(),itemsPerPage:g.number().int().min(1).optional(),params:g.record(g.string(),g.unknown()).optional(),explain:g.boolean().optional(),repo:g.string().optional(),owner:g.string().optional(),ref:g.string().optional(),path:ya.optional(),text:g.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:g.string().optional(),pattern:g.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:td.optional(),lang:g.string().optional(),and:g.array(g.unknown()).optional(),or:g.array(g.unknown()).optional(),xor:g.array(g.unknown()).optional(),noneOf:g.array(g.unknown()).optional(),oneOf:g.array(g.unknown()).optional(),invert:g.unknown().optional(),filesOnly:g.boolean().optional(),filesWithoutMatch:g.boolean().optional(),verbose:g.boolean().optional()},ud={...ld,target:g.enum(ad).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},No=g.object(ud).catchall(g.unknown()),ba=g.object(ld).catchall(g.unknown()),Ra=g.object({...cd,queries:g.array(g.unknown()).min(1)}).catchall(g.unknown()),un=g.object({...ud,queries:g.array(g.unknown()).min(1).max(5).optional(),combine:g.enum(["independent","merge"]).optional()}).catchall(g.unknown())});function P(e,t,n={}){let r=n.severity??(tP.has(e)?"error":"warning"),o=n.blocksAnswer??(eP.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function Sa(e){return e.some(t=>t.blocksAnswer)}function nP(e){return e.some(t=>t.severity==="error")}var eP,tP,_t,Ze=y(()=>{"use strict";eP=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),tP=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);_t=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});import{z as C}from"zod";function pd(e,t){let n=fP[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var fe,Pa,dd,rP,oP,iP,sP,aP,cP,lP,uP,dP,pP,fP,fd=y(()=>{"use strict";fe=C.number().int().min(1),Pa=C.number().int().min(0),dd=C.enum(["symbols","files","dependencies","relations"]),rP=C.object({match:C.enum(["file","path"]).optional(),concise:C.boolean().optional(),extension:C.string().optional(),filename:C.string().optional(),page:fe.optional(),limit:fe.optional()}).passthrough(),oP=C.object({type:C.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:C.string().optional(),symbolName:C.string().optional(),symbolKind:C.string().optional(),lineHint:fe.optional(),orderHint:C.number().int().optional(),includeDeclaration:C.boolean().optional(),depth:C.number().int().min(0).max(20).optional(),groupByFile:C.boolean().optional(),workspaceRoot:C.string().optional(),format:C.enum(["structured","compact"]).optional(),page:fe.optional(),itemsPerPage:fe.optional()}).passthrough(),iP=C.object({keywords:C.array(C.string()).optional(),topicsToSearch:C.union([C.string(),C.array(C.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:C.string().optional(),owner:C.string().optional(),stars:C.union([C.string(),C.number()]).optional(),forks:C.string().optional(),goodFirstIssues:C.string().optional(),size:C.string().optional(),created:C.string().optional(),updated:C.string().optional(),license:C.string().optional(),match:C.array(C.enum(["name","description","readme"])).optional(),visibility:C.enum(["public","private"]).optional(),archived:C.boolean().optional(),sort:C.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:C.boolean().optional(),page:fe.optional()}).passthrough(),sP=C.object({packageName:C.string().optional(),keywords:C.array(C.string()).optional(),mode:C.enum(["lean","full"]).optional(),page:fe.optional()}).passthrough(),aP=C.object({prNumber:fe.optional(),concise:C.boolean().optional(),state:C.enum(["open","closed","merged"]).optional(),author:C.string().optional(),label:C.union([C.string(),C.array(C.string())]).optional(),keywordsToSearch:C.union([C.string(),C.array(C.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:C.string().optional(),base:C.string().optional(),created:C.string().optional(),updated:C.string().optional(),closed:C.string().optional(),"merged-at":C.string().optional(),draft:C.boolean().optional(),archived:C.boolean().optional(),sort:C.enum(["created","updated","best-match","comments","reactions"]).optional(),order:C.enum(["asc","desc"]).optional(),reviewMode:C.string().optional(),filePage:fe.optional(),commentPage:fe.optional(),commitPage:fe.optional(),charOffset:Pa.optional(),charLength:fe.optional(),minify:C.enum(["none","standard"]).optional(),limit:fe.optional(),page:fe.optional(),matchString:C.string().optional(),matchScope:C.enum(["body","title","comments","reviews","all"]).optional(),content:C.record(C.string(),C.unknown()).optional()}).passthrough(),cP=C.object({path:C.string().optional(),branch:C.string().optional(),since:C.string().optional(),until:C.string().optional(),author:C.string().optional(),includeDiff:C.boolean().optional(),limit:fe.optional(),page:fe.optional()}).passthrough(),lP=C.object({mode:C.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:C.string().optional(),entryPageNumber:fe.optional(),maxEntries:fe.optional(),entriesPerPage:fe.optional(),minLength:C.number().int().min(1).max(128).optional(),scanOffset:Pa.optional(),charOffset:Pa.optional(),charLength:fe.optional(),matchString:C.string().optional(),detailed:C.boolean().optional(),format:C.string().optional(),verbose:C.boolean().optional(),includeOffsets:C.boolean().optional()}).passthrough(),uP=C.object({prNumber:fe.optional(),files:C.array(C.string()).optional(),baseRef:C.string().optional(),headRef:C.string().optional(),path:C.string().optional()}).passthrough(),dP=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array(dd).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:fe.optional()}).passthrough(),pP=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array(dd).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:fe.optional(),subject:C.string().optional(),subjectKind:C.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:C.union([C.string(),C.array(C.string())]).optional(),verdict:C.union([C.string(),C.array(C.string())]).optional(),direction:C.enum(["incoming","outgoing","both"]).optional(),proof:C.enum(["none","lsp"]).optional(),proofLimit:fe.max(25).optional(),includePackets:C.boolean().optional(),includeFacts:C.boolean().optional(),includeEdges:C.boolean().optional()}).passthrough(),fP={semantics:oP,repositories:iP,packages:sP,pullRequests:aP,commits:cP,artifacts:lP,diff:uP,research:dP,graph:pP,code:rP}});function Y(...e){throw new _t(e)}function ka(e){return Yu(e)?hP(e):Ta(e)}function hP(e){let t=Ra.safeParse(e);t.success||Y(P("invalidQuery",Go(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||Y(P("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&Y(P("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return Ta(i)}catch(a){throw a instanceof _t?new _t(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}function Ta(e){let t=ba.safeParse(e);t.success||Y(P("invalidQuery",Go(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??gP(n);r===void 0&&Y(P("invalidQuery",`Could not determine \`target\`; specify one of: ${Je.join(", ")}.`,{queryPath:"target"})),_n.includes(r)&&Y(P("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${Je.join(", ")}.`}})),Je.includes(r)||Y(P("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))mP.has(m)||Y(P("unknownField",`Unknown field "${m}" is not part of OQL.`,{queryPath:m}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=SP(n,r),a=CP(n,s),c=wP(n,r),l=OP(n,s,c,r),u=LP(n),d=bP(n,r),p={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(p.target==="code"&&!p.where&&Y(P("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.where&&Y(P("invalidQuery",`target:"${p.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.from?.kind==="github"&&!(p.from.repo&&p.from.repo.includes("/"))&&Y(P("invalidQuery",`target:"${p.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),p.target==="materialize"&&(p.where&&Y(P("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),p.from?.kind!=="github"&&p.from?.kind!=="materialized"&&Y(P("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),p.params!==void 0){let m=pd(p.target,p.params);m&&Y(P("invalidQuery",m,{queryPath:"params"}))}let f=Pr.safeParse(p);return f.success||Y(P("invalidQuery",Go(f.error))),f.data}function gP(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function bP(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!RP(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function RP(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return yP.some(n=>t.includes(n))}function SP(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&Y(P("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),PP(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Mo.includes(t)||Y(P("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function PP(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}function CP(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&Y(P("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}function wP(e,t){let n=TP(e);e.where&&n&&Y(P("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;wa(r,"where"),xa(r,"where",new Map);let o=Wt.safeParse(r);return o.success||Y(P("invalidQuery",Go(o.error),{queryPath:"where"})),o.data}function Ca(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Ca(n),0):e.kind==="not"?1+Ca(e.predicate):1}function kP(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:xP}function TP(e){let t=n=>{let r=Ca(n),o=kP(e);return r>o&&Y(P("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(Fn)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(Fn)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(Fn)}};if(Array.isArray(e.xor)){e.xor.length!==2&&Y(P("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=Fn(e.xor[0]),r=Fn(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(EP(e.oneOf.map(Fn)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&Y(P("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&Y(P("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function Fn(e){if(e&&typeof e=="object"&&"kind"in e)return e;Y(P("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function EP(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function wa(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&Y(P("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>wa(n,`${t}.of[${r}]`));break;case"not":e.predicate||Y(P("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),wa(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&Y(P("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":vP(e,t);break;default:break}}function xa(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&Y(P("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>xa(r,`${t}.of[${o}]`,n)):e.kind==="not"&&xa(e.predicate,`${t}.predicate`,n)}function vP(e,t){if(e.op==="exists"){e.value!==void 0&&Y(P("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&Y(P("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&Y(P("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function md(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return md(e.predicate);default:return!1}}function OP(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:md(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function LP(e){return e.fetch?{...e.fetch}:void 0}function Go(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var mP,yP,xP,Ea=y(()=>{"use strict";In();Ze();fd();At();mP=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"]);yP=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"];xP=64});function AP(e){return e?.mode==="auto"||e?.mode==="required"}function _P(e,t){let n=e.target==="files"?dn:Vt;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:Vt,exact:!0,reason:`${t.kind} evaluated locally by ${Vt}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function IP(e,t,n){let r=AP(e.materialize);if(n)return FP(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:dn,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:It,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:dn,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:It,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:dn,exact:!0,reason:`${Ho(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:dn,exact:!1,reason:`GitHub cannot enumerate files by ${Ho(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Ho(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:Vt,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:Vt,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:It,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:It,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?va(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:Vt,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:It,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return va(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:dn,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:It,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:It,exact:!0,reason:"path/name predicate pushed to provider"}:va(e,`field "${t.field}"`,r)}}function Ho(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function FP(e,t,n){let r=Ho(t);return n?{route:"ROUTE",backend:e.target==="files"?dn:Vt,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:It,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function va(e,t,n){if(n)return{route:"ROUTE",backend:Vt,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:It,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function hd(e,t,n=!1){return e.sourceKind==="github"?IP(e,t,n):_P(e,t)}var Vt,dn,It,gd=y(()=>{"use strict";Vt="localSearchCode",dn="localFindFiles",It="ghSearchCode"});function Mn(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var zo=y(()=>{"use strict"});function yd(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&MP.has(e.target)&&t.push(P("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "exact" or "compact".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "exact" or "compact".'}})),t}var MP,bd=y(()=>{"use strict";Ze();MP=new Set(["pullRequests","commits","diff"])});function Oa(e){let t={schema:De.schema,view:e.view??De.view,page:e.page??De.page,itemsPerPage:e.itemsPerPage??De.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??De.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??De.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??De.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?De.detailedCodeContext:De.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??De.localSearchSort),t}var De,Qo=y(()=>{"use strict";De={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function Rd(e){return JSON.stringify(e)}function La(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${Rd(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${Rd(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...La(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=La(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function Sd(e){return["rule:",...La(e,1)].join(`
9
- `)}var Pd=y(()=>{"use strict"});function Cd(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function wd(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return Cd(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),Cd(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=Sd(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function pn(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return wd(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=wd(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var Aa=y(()=>{"use strict";Pd()});function GP(e){return e.trim().replace(/^\./,"").toLowerCase()}function Dn(e){if(!e?.trim())return;let t=GP(e),n=DP[t]??NP[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function HP(e){return[...e??[]].map(t=>`**/*.${t}`)}function _a(e){return[...e??[]].map(t=>`*.${t}`)}function Bo(e){let t=Dn(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Ia(e){let t=Dn(e);return t?t.kind==="extension"&&t.extension?{include:HP([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function Fa(e){let t=Dn(e);return t?t.kind==="extension"&&t.extension?_a([t.extension]):t.kind==="language"?_a(t.extensions):t.normalized?_a([t.normalized]):[]:[]}function xd(e){let t=Dn(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Ma(e){return Dn(e)?.canonicalLanguage}var DP,NP,Da=y(()=>{"use strict";DP={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},NP={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});var $o=y(()=>{"use strict";Da()});function jo(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(jo):e.kind==="not"?jo(e.predicate):[e]}function Na(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function et(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Nn(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Ga(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var Cr=y(()=>{"use strict"});function kd(e,t,n){let r=e.where,o=r?jo(r):[],i=r&&zP.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>P("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function QP(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function wr(e,t={}){if(!e.where)return{ok:!1,diagnostics:[P("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=QP(e.where);if(n){let p=Td(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=Na(e.from),h=e.params??{},b=typeof h.extension=="string"||typeof n.extension=="string"?{}:Bo(Nn(e.scope)),x=Ga(e),S=et(e.scope);return kd(e,{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...S?{path:S}:{},...typeof h.extension=="string"?{extension:h.extension}:{},...x?{limit:x}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=pn(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[P("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=Td(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[P("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Na(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Bo(Nn(e.scope)),u=Ga(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return kd(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...et(e.scope)?{path:et(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function Td(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(P("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(P("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var zP,Ha=y(()=>{"use strict";Aa();Ze();$o();Cr();zP=new Set(["text","regex","structural","field"])});function BP(){return Uo}function fn(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return Uo.find(n=>n.id===`${t}.diff.${e.variant}`)}return Uo.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function qo(e){return Uo.find(t=>t.id===e)}function za(e){let t=$P(e.source,e.target);if(e.target==="diff"){let n=Mn(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return fn({sourceKind:t,target:"diff",variant:r})}return fn({sourceKind:t,target:e.target})}function Qa(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function Ed(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function $P(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var Uo,Ba=y(()=>{"use strict";zo();Uo=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.artifacts",target:"artifacts",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localBinaryInspect",operation:"inspectArtifact",exact:!0}],rowKind:"record",recordType:"artifact",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeArtifacts"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function jP(e,t){return e.id??t}function $a(e,t,n,r,o,i=!1){let s=jP(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>$a(e,d,`${n}.of[${p}]`,r,o,i)),l=UP(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(P("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=$a(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=hd(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(P(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&vd(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:qP(e.target),exact:a.exact}),a.route}function UP(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function qP(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"artifacts":return"inspectArtifact";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function vd(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function ja(e,t){if(!t)return;let n=Ed(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Wo(e,t,n){if(!t)return!1;for(let r of Qa(t,n))vd(e.backendCalls,r);return!0}function WP(e,t){return Od(e,t,"files")}function Od(e,t,n,r=fn({sourceKind:"materialized",target:n})){let o=fn({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),ja(e,o),ja(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),Wo(e,o,t),Wo(e,r,void 0),!0}function Vo(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Vo):e.kind==="not"?Vo(e.predicate):!1:!1}function VP(e){return e.target==="code"?qo(Vo(e.where)?"local.code.structural":"local.code.textRegex"):fn({sourceKind:"materialized",target:e.target})}function KP(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?qo(Vo(e.where)?"local.code.structural":"local.code.textRegex")??za({source:t,target:e.target,params:e.params}):za({source:t,target:e.target,params:e.params})}function Ua(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Ua(n),0):e.kind==="not"?1+Ua(e.predicate):1:0}function qa(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=KP(e,o);if(ja(n,s),e.where)$a(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&Od(n,o,e.target,VP(e));else if(e.target==="diff"){let m=Mn(e.params);m.kind==="prPatch"||m.kind==="directFile"?Wo(n,s,o)||n.diagnostics.push(P("unsupportedTarget",`No transformer registered for target:"diff" lane "${m.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(P("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let m=o.kind==="github"&&e.target==="files"&&!e.where,h=r?.mode==="auto"||r?.mode==="required";!(m?h&&WP(n,o):Wo(n,s,o))&&(!m||h)&&n.diagnostics.push(P("unsupportedTarget",m?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(P("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...XP(e,n.nodes)),n.diagnostics.push(...YP(e)),n.diagnostics.push(...yd(e));let a=JP(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??De.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(P("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=Ua(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(P("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let p={input:t,normalized:e,defaults:Oa(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},f=!n.nodes.some(m=>m.route==="UNSUPPORTED")&&!n.diagnostics.some(m=>m.severity==="error"&&m.code!=="planTruncated");return{plan:p,executable:f}}function Ld(e){return e.kind==="not"&&e.predicate.kind==="not"?Ld(e.predicate.predicate):e}function YP(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Ku[e.target]:void 0;if(n)return n.includes(t)?[]:[P("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[P("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function XP(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=Ld(e.where),r=wr({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function JP(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(P("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(P("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var Wa=y(()=>{"use strict";gd();zo();bd();Ze();Qo();Ha();Ba();At()});function xr(e){let t=eC(e),n=nC(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function eC(e){return!e.executable||e.diagnostics.some(t=>ZP.has(t.code))?"unsupported":e.approximate||tC(e.diagnostics)?"candidate":Sa(e.diagnostics)||Ad(e)?"partial":"proof"}function tC(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function Ad(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function nC(e){return!e.executable||Ad(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function Va(e){return e.some(t=>!t.exact)}function Ko(e,t,n,r,o){return xr({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var ZP,Ka=y(()=>{"use strict";Ze();ZP=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});var Se=y(()=>{"use strict"});var z,_d,Gn=y(()=>{"use strict";z={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"},_d={[z.PATH_VALIDATION_FAILED]:{code:z.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[z.FILE_ACCESS_FAILED]:{code:z.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[z.FILE_READ_FAILED]:{code:z.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[z.FILE_TOO_LARGE]:{code:z.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[z.BINARY_FILE_UNSUPPORTED]:{code:z.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[z.NO_MATCHES]:{code:z.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[z.OUTPUT_TOO_LARGE]:{code:z.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[z.COMMAND_NOT_AVAILABLE]:{code:z.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[z.COMMAND_EXECUTION_FAILED]:{code:z.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[z.COMMAND_TIMEOUT]:{code:z.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[z.TOOL_EXECUTION_FAILED]:{code:z.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[z.LSP_SERVER_UNAVAILABLE]:{code:z.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function Ya(e){return e instanceof _e}function Id(e,t=z.TOOL_EXECUTION_FAILED,n){if(Ya(e))return e;if(e instanceof Error)return new _e(t,e.message,n,e);let r=String(e);return new _e(t,r,n)}var _e,Yo=y(()=>{"use strict";Gn();_e=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=_d[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
10
- Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}}});import{redactPath as kr}from"@octocodeai/octocode-engine/pathUtils";var Fd=y(()=>{"use strict"});var at,Xo=y(()=>{"use strict";Yo();Gn();Fd();at={pathValidationFailed:(e,t,n)=>new _e(z.PATH_VALIDATION_FAILED,t||`Path validation failed: ${kr(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=kr(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new _e(z.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new _e(z.FILE_READ_FAILED,`Failed to read file: ${kr(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new _e(z.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new _e(z.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${kr(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new _e(z.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new _e(z.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new _e(z.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new _e(z.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});function B(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Dd(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function U(e,t){let n=typeof t=="number"?Dd(t):B(t);if(n===void 0)return e;try{Object.defineProperty(e,Md,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function me(e){if(!(typeof e!="object"||e===null))return Dd(e[Md])}var Md,ue=y(()=>{"use strict";Md=Symbol.for("octocode.rawResponseChars")});function rC(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function M(e,t,n={}){let{extra:r}=n,o={status:"error"};if(rC(e))o.error=e;else if(Ya(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Id(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:U(o,n.rawResponse)}function Ne(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:M(i,t,{toolName:n.toolName})}}var Xa=y(()=>{"use strict";Yo();ue()});import WN from"node:fs";import KN from"node:path";import Nd from"node:os";import Hn from"node:path";import{existsSync as hC,readFileSync as gC}from"node:fs";import yC from"node:path";function rc(e=process.env){let t=e.OCTOCODE_HOME;if(t&&t.trim())return Hn.resolve(t.trim());let n=Nd.homedir(),r=Nd.platform();if(r==="win32"){let i=e.APPDATA??Hn.join(n,"AppData","Roaming");return Hn.join(i,".octocode")}if(r==="darwin")return Hn.join(n,".octocode");let o=e.XDG_CONFIG_HOME??Hn.join(n,".config");return Hn.join(o,".octocode")}function oc(){return globalThis[iC]??"mcp"}function sC(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function tc(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Hd(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function Yd(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function aC(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function Ja(e,t){return e===void 0||e===null?null:Yd(e,t)}function Xd(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function cC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=sC(e.apiUrl,"github.apiUrl");r&&t.push(r)}function lC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Hd(n.enabled,"local.enabled");r&&t.push(r);let o=Hd(n.enableClone,"local.enableClone");o&&t.push(o);let i=Yd(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=aC(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=Xd(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function uC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=Ja(n.enabled,"tools.enabled");r&&t.push(r);let o=Ja(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=Ja(n.disabled,"tools.disabled");i&&t.push(i)}function dC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=tc(n.timeout,"network.timeout",jd,Ud);r&&t.push(r);let o=tc(n.maxRetries,"network.maxRetries",qd,Wd);o&&t.push(o)}function pC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=Xd(e.configPath,"lsp.configPath");r&&t.push(r)}function fC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=tc(r.defaultCharLength,"output.pagination.defaultCharLength",Vd,Kd);o&&t.push(o)}}function mC(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>Gd&&n.push(`version: Config version ${r.version} is newer than supported version ${Gd}`)),cC(r.github,t),lC(r.local,t),uC(r.tools,t),dC(r.network,t),pC(r.lsp,t),fC(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}function bC(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
11
- `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t.replace(/,(\s*[}\]])/g,"$1")}function RC(e){return JSON.parse(bC(e))}function SC(e=rc()){return yC.join(e,".octocoderc")}function PC(e){let t=SC(e);if(!hC(t))return{success:!1,error:"Config file does not exist",path:t};try{let n=gC(t,"utf-8");if(!n.trim())return{success:!0,config:{},path:t};let r=RC(n);return typeof r!="object"||r===null||Array.isArray(r)?{success:!1,error:"Config file has invalid structure: must be a JSON object",path:t}:{success:!0,config:r,path:t}}catch(n){return{success:!1,error:`Failed to parse config file: ${n instanceof Error?n.message:String(n)}`,path:t}}}function zd(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function nc(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function ei(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function CC(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||Bd.apiUrl}}function wC(e){let t=oc()==="cli",n=zd(process.env.ENABLE_LOCAL),r=zd(process.env.ENABLE_CLONE),o=ei(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??Tr.enabled,enableClone:r??e?.enableClone??(t?!0:Tr.enableClone),allowedPaths:o??e?.allowedPaths??Tr.allowedPaths,workspaceRoot:i??e?.workspaceRoot??Tr.workspaceRoot}}function xC(e){let t=ei(process.env.TOOLS_TO_RUN),n=ei(process.env.ENABLE_TOOLS),r=ei(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??Zo.enabled,enableAdditional:n??e?.enableAdditional??Zo.enableAdditional,disabled:r??e?.disabled??Zo.disabled}}function kC(e){let t=nc(process.env.REQUEST_TIMEOUT),n=nc(process.env.MAX_RETRIES),r=t??e?.timeout??ec.timeout;r=Math.max(jd,Math.min(Ud,r));let o=n??e?.maxRetries??ec.maxRetries;return o=Math.max(qd,Math.min(Wd,o)),{timeout:r,maxRetries:o}}function TC(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??$d.configPath}}function vC(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=nc(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||zn.format,o=n??e?.pagination?.defaultCharLength??zn.pagination.defaultCharLength,i=Math.max(Vd,Math.min(Kd,o));return{format:EC.has(r)?r:zn.format,pagination:{defaultCharLength:i}}}function Za(e,t){let n=e!==void 0,r=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??oC.version,github:CC(e?.github),local:wC(e?.local),tools:xC(e?.tools),network:kC(e?.network),lsp:TC(e?.lsp),output:vC(e?.output),source:o,configPath:n?t:void 0}}function OC(){let e=PC();return e.success&&e.config&&mC(e.config).valid?Za(e.config,e.path):Za(void 0)}function gt(){let e=Date.now();return Jo&&e-Qd<LC||(Jo=OC(),Qd=e),Jo}function Jd(e=process.env){for(let t of AC){let n=e[t];if(n?.trim())return{token:n.trim(),source:`env:${t}`}}return null}var Gd,Bd,Tr,Zo,ec,$d,zn,oC,jd,Ud,qd,Wd,Vd,Kd,iC,EC,Jo,Qd,LC,AC,Ct=y(()=>{"use strict";Gd=1,Bd={apiUrl:"https://api.github.com"},Tr={enabled:!0,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},Zo={enabled:null,enableAdditional:null,disabled:null},ec={timeout:3e4,maxRetries:3},$d={configPath:void 0},zn={format:"yaml",pagination:{defaultCharLength:2e4}},oC={version:1,github:Bd,local:Tr,tools:Zo,network:ec,lsp:$d,output:zn},jd=5e3,Ud=3e5,qd=0,Wd=10,Vd=1e3,Kd=5e4,iC="__octocodeRuntimeSurface__";EC=new Set(["yaml","json"]);Jo=null,Qd=0,LC=6e4;AC=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN"]});import Zd from"path";import{pathValidator as _C}from"@octocodeai/octocode-engine/pathValidator";function Be(e,t){if(!e.path?.trim()){let s=at.pathValidationFailed("","path is required");return{isValid:!1,errorResult:M(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||gt().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Zd.isAbsolute(r)?r:Zd.resolve(n,r),i=_C.validate(o);if(!i.isValid){let s=at.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:M(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}var Ft=y(()=>{"use strict";Xo();Xa();Ct()});import{completeMetadata as ic}from"@octocodeai/octocode-core";var O,ep=y(()=>{"use strict";O=new Proxy({},{get(e,t){return ic.toolNames[t]},ownKeys(){return Object.keys(ic.toolNames)},getOwnPropertyDescriptor(e,t){let n=ic.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as IC}from"@octocodeai/octocode-core";var sc,tp=y(()=>{"use strict";sc=new Proxy({},{get(e,t){return IC.tools[t]?.description??""}})});import{completeMetadata as FC}from"@octocodeai/octocode-core";function ac(e){return Object.prototype.hasOwnProperty.call(FC.tools,e)}var np=y(()=>{"use strict"});import{completeMetadata as MC}from"@octocodeai/octocode-core";function cc(){return MC.baseSchema}var DC,rp=y(()=>{"use strict";DC=new Proxy({},{get(e,t){return cc()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(cc())]))},getOwnPropertyDescriptor(e,t){let n=cc();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var ye=y(()=>{"use strict";ep();tp();np();rp()});import{z as ti}from"zod";function H(e,t){return ti.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,ti.number().int().min(e).max(t))}function se(e,t={}){let{maxQueries:n=5}=t;return ti.object({queries:ti.array(e).min(1).max(n).describe("Parallel queries."),...GC}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var de,Qn,Bn,GC,$e=y(()=>{"use strict";Se();de=H(1,1e3).optional().default(1),Qn=H(0,100).optional(),Bn=H(1,1e9).optional(),GC={responseCharOffset:H(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:H(1,5e4).optional().describe("Full-response char window.")}});import{z as op}from"zod";function HC(e,t){return e?.description&&!t.description?t.describe(e.description):t}function ip(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=HC(e.shape[r],o);return n}function zC(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function sp(e,t){if(!t?.length)return e;let n=new Set(t);return op.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function he(e,t={},n={}){let r=sp(e,n.omit),o=zC(r,ip(r,t));return n.strict?o.strict():o}function be(e,t={},n={}){let r=sp(e,n.omit),o=op.object({...r.shape,...ip(r,t)});return n.strict?o.strict():o}var tt=y(()=>{"use strict"});import{z as oe}from"zod";var xe,ni,Er,ap,yt=y(()=>{"use strict";xe=oe.object({currentPage:oe.number(),totalPages:oe.number(),hasMore:oe.boolean(),nextPage:oe.number().optional(),pageSize:oe.number().optional(),totalItems:oe.number().optional()}),ni=oe.object({charOffset:oe.number(),charLength:oe.number(),totalChars:oe.number(),hasMore:oe.boolean(),nextCharOffset:oe.number().optional(),currentPage:oe.number().optional(),totalPages:oe.number().optional(),chunkMode:oe.enum(["semantic","char-limit"]).optional()}),Er=oe.object({tool:oe.string(),query:oe.record(oe.string(),oe.unknown()),why:oe.string().optional(),confidence:oe.enum(["exact","heuristic"]).optional()}),ap=oe.object({level:oe.enum(["info","warning","error"]),message:oe.string(),field:oe.string().optional(),code:oe.string().optional()})});import{z as X}from"zod";function QC(e){return X.object({id:X.string(),status:X.enum(["empty","error"]).optional(),data:e,diagnostics:X.array(ap).optional(),next:X.record(X.string(),Er).optional()})}var cp,je,OG,wt,nt=y(()=>{"use strict";yt();cp=X.object({currentPage:X.number(),totalPages:X.number(),hasMore:X.boolean(),charOffset:X.number(),charLength:X.number(),totalChars:X.number(),nextCharOffset:X.number().optional()}).optional(),je={base:X.string().optional(),shared:X.record(X.string(),X.union([X.string(),X.number(),X.boolean()])).optional(),responsePagination:cp};OG=QC(X.record(X.string(),X.unknown()).optional()),wt={base:X.string().optional(),shared:X.record(X.string(),X.union([X.string(),X.number(),X.boolean()])).optional(),responsePagination:cp}});import{z as W}from"zod";import{RipgrepQuerySchema as lp}from"@octocodeai/octocode-core/schemas";var BC,$C,up,jC,UC,qC,Kt,ri,WC,VC,KC,GG,vr=y(()=>{"use strict";Se();$e();tt();nt();yt();BC=["paginated","discovery","detailed","structural"],$C=["semanticRanking"],up={mode:W.enum(BC).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters.'),pattern:W.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:W.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:Qn,matchContentLength:H(1,1e5).optional().default(500),maxMatchesPerFile:H(1,1e5).optional(),maxFiles:H(1,1e5).optional(),matchPage:de.optional(),itemsPerPage:H(1,1e3).optional(),page:de.default(1),unique:W.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:W.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},jC={...up,semanticRanking:W.never().optional()},UC=be(lp,jC),qC=he(lp,up,{strict:!0,omit:$C}),Kt=qC.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),ri=se(UC,{maxQueries:5}),WC=W.object({line:W.number(),endLine:W.number().optional(),value:W.string().optional(),column:W.number().optional(),count:W.number().optional(),metavars:W.record(W.string(),W.array(W.string())).optional()}),VC=W.object({path:W.string(),matches:W.array(WC).optional(),totalOccurrences:W.number().optional(),totalMatchedLines:W.number().optional(),totalMatchRows:W.number().optional(),returnedMatchRows:W.number().optional(),matchPagination:xe.optional(),next:W.record(W.string(),Er).optional()}),KC=W.object({files:W.array(VC).optional(),summary:W.string().optional(),searchEngine:W.string().optional(),pagination:xe.optional(),next:W.record(W.string(),Er).optional(),warnings:W.array(W.string()).optional()}),GG=W.object({results:W.array(W.object({id:W.string(),status:W.enum(["empty","error"]).optional(),data:KC}))}).extend(wt)});var xt,Or=y(()=>{"use strict";xt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function fc(e){return mp.exec(e)?.[1]?.toLowerCase()??""}function sw(e){let t=fc(e);if(!t)return!1;for(let n of iw)if(Lr[n].extensions.includes(t))return!0;return!1}function aw(e,t,n){if(n&&n!=="auto")return Lr[n];let r=fc(e),o=(t??"").toLowerCase();for(let i of dp){let s=Lr[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of dp){let s=Lr[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Lr.generic}function hp(e){return ZC.test(e)?"generated":tw.test(e)?"fixture":ew.test(e)?"test":rw.test(e)?"config":nw.test(e)?"docs":!pc.test(e)&&(ow.test(e)||sw(e))?"source":"unknown"}function cw(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function lw(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function uw(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Pw(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=Cw(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${yp(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=pe.exactWholeWord,p.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=pe.exactCaseInsensitive,p.push("case-insensitive match")):u.includes(r)&&(d+=pe.substring,p.push("substring match")));let f=c.kind;if(f)d+=dw(f,p);else{let m=ww(u,r,t.id,n.caseSensitive);m!=="code"?(d+=pe.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(dc(t.declaration,u)&&(d+=pe.declarationLine,p.push("declaration line")),dc(t.export,u)&&(d+=pe.exportLine,p.push("export/public line")),dc(t.import,u)&&(d+=pe.importLine,p.push("import line")),t.id==="markdown"&&JC.test(u)&&(d+=pe.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&pw(u,r)&&(d+=pe.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function dw(e,t){switch(e){case"declaration":return t.push("AST: declaration"),pe.declarationLine;case"export":return t.push("AST: export/public"),pe.exportLine;case"configKey":return t.push("AST: config key"),pe.configKeyLine;case"heading":return t.push("AST: heading"),pe.headingLine;case"import":return t.push("AST: import"),pe.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),pe.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function pw(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function fw(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(mp,"").includes(l))&&(s+=pe.pathSegmentToken,i.push("query token in path"))}let a=fc(e);return r.extensions.includes(a)&&t.langType&&(s+=pe.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=pe.sourceDir,i.push("source file")),s}function mw(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),pe.lowSignalPathPenalty):0}function hw(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*pe.matchCountScale,r=Math.min(n,pe.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function gw(e,t){let n=lw(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>yw(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function yw(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${yp(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function bw(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*pe.rareQueryTokenScale,pe.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function Rw(e,t,n){let r=aw(e.path,t.langType,t.profileOverride),o=hp(e.path),i=cw(t.keyword),s=[],a=0;return a+=uw(e.matches,r,t,i,s),a+=fw(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=pe.pathUnderQuery,s.push("under requested subtree")),a+=mw(o,t,s),pc.test(e.path)&&!t.explicitLowSignal&&(a+=pe.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=hw(e.matchCount??0,s),a+=bw(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function gp(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(fp),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,p)=>d.path.localeCompare(p.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??YC,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(fp);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=gw(i,n),l=i.map(d=>{try{return{file:d,s:Rw(d,n,c)}}catch{return{file:d,s:Sw()}}});l.sort((d,p)=>{if(p.s.score!==d.s.score)return p.s.score-d.s.score;let f=(p.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(p.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function Sw(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function fp(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function dc(e,t){for(let n of e)if(n.test(t))return!0;return!1}function yp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pw(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function Cw(e,t,n){if(e.indexOf(`
12
- `)<0)return e;let o=e.split(`
13
- `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function ww(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(XC.test(e))return"comment";let o=xw(e,t,r);if(o<0)return"code";let i=kw(e);return i>=0&&o>i?"comment":Tw(e,o)?"string":"code"}function xw(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function kw(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function Tw(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function bp(e){if(!e)return!1;if(pc.test(e))return!0;let t=hp(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var dp,pe,YC,XC,pp,Lr,JC,pc,ZC,ew,tw,nw,rw,ow,iw,mp,Rp=y(()=>{"use strict";dp=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],pe={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},YC=2e3,XC=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,pp={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Lr={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...pp},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...pp},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},JC=/^\s*#{1,6}\s/,pc=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,ZC=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,ew=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,tw=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,nw=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,rw=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,ow=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,iw=new Set(["typescript","javascript","rust","python","go","java","scala"]),mp=/\.([a-z0-9]+)$/i});async function ii(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=gp(e,s,Iw(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),p=!!(t.countLinesPerFile||t.countMatchesPerFile),f=d||p,m=c.reduce((G,K)=>G+(K.matchCount??0),0),h=f?o?.totalOccurrences??o?.totalStructuralMatches??m:m,b=t,x=Math.min(b.itemsPerPage||xt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=b.page||1,T=Math.max(1,Math.ceil(u/x)),L=(S-1)*x,_=Math.min(L+x,u),E=c.slice(L,_),w=b.maxMatchesPerFile||xt.DEFAULT_MATCHES_PER_PAGE,N=E.map(G=>{let K=G.matches?.length??0,j=Math.ceil(K/w),ve=Math.max(1,b.matchPage||1),Oe=(ve-1)*w,Ut=Math.min(Oe+w,K),qt=f?void 0:G.matches?.slice(Oe,Ut),re=qt?.length,Pt=l?.get(G.path);return{path:G.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:G.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:G.matchCount||1}:{totalMatchRows:K,...re!==void 0?{returnedMatchRows:re}:{}},...qt!==void 0&&{matches:qt},...Pt?{ranking:{score:Pt.score,profile:Pt.profile,pathRole:Pt.pathRole,reasons:Pt.reasons}}:{},pagination:!f&&K>w?{currentPage:ve,totalPages:j,matchesPerPage:w,totalMatches:K,hasMore:ve<j,...ve<j?{nextMatchPage:ve+1}:{}}:void 0}}),F=N.filter(G=>G.pagination?.hasMore),v=Ow(N,t,n,{isFileListMode:f,currentPage:S,totalFilePages:T,matchPage:b.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:F.length>0}),Q={searchEngine:n,...o?{stats:o}:{},files:N,pagination:{currentPage:S,totalPages:T,filesPerPage:x,totalFiles:u,...d?{}:{totalMatches:h},hasMore:S<T,...S<T?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(v).length>0?{next:v}:{}};return Pp(Q,t,{totalMatches:h,totalFiles:u})}function Pp(e,t,n){return e}function Ow(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=Lw(i);s.fetchExact={tool:"localGetFileContent",query:oi({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:oi({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=Aw(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:oi({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:oi({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function Lw(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-Sp),endLine:n+Sp}}function Aw(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return _w(e?.metavars);if(!t.matchWindow)return t.onlyMatching?mc(e?.value):mc(t.keywords)}}function _w(e){if(e)for(let t of Object.values(e))for(let n of t){let r=mc(n);if(r)return r}}function mc(e){if(typeof e!="string")return;let t=e.trim();if(vw.test(t)&&!Ew.has(t))return t}function oi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Iw(e){let t=e.rankingProfile,n=!!(e.include?.length||bp(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var Sp,Ew,vw,si=y(()=>{"use strict";Or();Rp();Sp=8,Ew=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),vw=/^[A-Za-z_$][A-Za-z0-9_$]*$/});import{createRequire as Fw}from"node:module";function J(){if(ai)return ai;try{return ai=Dw(),ai}catch(e){throw new hc(e)}}var Mw,Cp,ai,Dw,hc,D,Ce=y(()=>{"use strict";Mw=Fw(import.meta.url),Cp="@octocodeai/octocode-engine",Dw=()=>Mw(Cp),hc=class extends Error{constructor(n){super(`Failed to load native dependency ${Cp}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return J().applyContentViewMinification(e,t)},applyMinification(e,t){return J().applyMinification(e,t)},minifyContent(e,t){return J().minifyContent(e,t)},minifyContentSync(e,t){return J().minifyContentSync(e,t)},minifyContentResult(e,t){return J().minifyContentResult(e,t)},minifyMarkdownCore(e){return J().minifyMarkdownCore(e)},extractSignatures(e,t){return J().extractSignatures(e,t)},extractJsSymbols(e,t){return J().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return J().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return J().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return J().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return J().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return J().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return J().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return J().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return J().getSupportedStructuralExtensions()},inspectBinaryNative(e){return J().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return J().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return J().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return J().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return J().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return J().parseRipgrepJson(e,t)},searchRipgrep(e){return J().searchRipgrep(e)},queryFileSystem(e){return J().queryFileSystem(e)},extractMatchingLines(e,t,n){return J().extractMatchingLines(e,t,n)},filterPatch(e,t){return J().filterPatch(e,t)},charToByteOffset(e,t){return J().charToByteOffset(e,t)},byteToCharOffset(e,t){return J().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return J().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return J().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return J().SIGNATURES_ONLY_HINT}}});function wp(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&Nw(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&Gw(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function Nw(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function Gw(e){return/\(\?[=!<]/.test(e)}var xp=y(()=>{"use strict";Ce()});import{validateRipgrepQuery as Hw}from"@octocodeai/octocode-core/schemas/runtime";function zw(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function Qw(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:zw(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function Bw(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function kp(e){let t=[],n=Hw(e);if(!n.isValid)return M(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:O.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=Kt.safeParse(e);if(!r.success){let h=r.error.issues.map(b=>b.message);return M(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:O.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return M(new Error("Path is required for search"),o,{toolName:O.LOCAL_RIPGREP,extra:{warnings:t}});let s=Be(o,O.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=wp({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return M(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:O.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(Qw(a))}catch(h){return M(h instanceof Error?h:new Error(String(h)),o,{toolName:O.LOCAL_RIPGREP})}let d=u.files.map(h=>({path:h.path,matchCount:h.matchCount,matches:h.matches.map(b=>{let x={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(x.count=b.count),b.kind!==void 0&&(x.kind=b.kind),b.scoreHint!==void 0&&(x.scoreHint=b.scoreHint),x})})),p=Bw(d),f={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return U({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>xt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await ii(d,o,"rg",[...t,...l],f);return U(m,p)}var Tp=y(()=>{"use strict";Ft();vr();Or();ye();si();xp();ue();Ce()});import{readFile as $w,stat as jw}from"node:fs/promises";function Vw(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function vp(e){return e.include?.length?e.include:xd(e.langType)}async function Kw(e){try{return(await jw(e)).isFile()}catch{return!1}}async function Yw(e,t){let n=await $w(e,"utf8"),r=D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Op(e){let t=Be(e,O.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await Kw(t.sanitizedPath)?await Yw(t.sanitizedPath,e):D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...vp(e)?{include:vp(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Ep.length?{excludeDir:Ep}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??Uw,maxFileBytes:qw})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return M(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:O.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(Ww+Vw(e.pattern)),await ii(r,e,"structural",i,o)}var Ep,Uw,qw,Ww,Lp=y(()=>{"use strict";Ce();Ft();ye();Da();si();Ep=[],Uw=2e3,qw=1e6,Ww="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function Xw(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function kt(e){let t=Xw(e);if(t.mode==="structural")return await Op(t);t.contextLines===void 0&&(t.contextLines=2);try{return await kp(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:z.OUTPUT_TOO_LARGE}:M(n,t,{toolName:O.LOCAL_RIPGREP})}}var ci=y(()=>{"use strict";Ft();Gn();ye();Tp();Lp()});function $n(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 Ar(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[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 r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var li=y(()=>{"use strict"});function ex(e,t){let n=t??Zw,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function jn(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Be(e,O.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:ex(i.path,i.excludeDir)},{warnings:a,query:c}=ix(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,p=u.wasCapped,f=u.entries.map(G=>tx(G,r)),m=e.sortBy||"modified";nx(f,m,r);let h=f.slice(0,l),b=rx(h,t,n),x=b.length,S=e.itemsPerPage||20,T=e.page||1,L=Math.max(1,Math.ceil(x/S)),_=(T-1)*S,E=Math.min(_+S,x),N=b.slice(_,E),F=[...u.warnings,...u.skipped>0?[`${u.skipped} entr${u.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],v=[...a,...F],Q={...x===0?{status:"empty"}:{},path:i.path,files:N,pagination:{currentPage:T,totalPages:L,filesPerPage:S,totalFiles:x,hasMore:T<L,...T<L?{nextPage:T+1}:{},...p||d>x?{totalFilesFound:d}:{}},...v.length>0&&{warnings:v}};return U(Ap(Q,e,{totalFiles:x}),u.entries.reduce((G,K)=>G+K.path.length,0))}catch(o){return M(o,e,{toolName:O.LOCAL_FIND_FILES})}}function tx(e,t){let n={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 t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function Ap(e,t,n){return e}function nx(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function rx(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=$n(r.size),t&&(o.size=r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function ix(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!ox.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var Zw,ox,ui=y(()=>{"use strict";Ft();li();Ce();ye();Se();ue();Zw=[];ox=/^\d+[hdwm]$/});function cx(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function _p(e,t){let n=e[t];return n===void 0?!1:sx.has(n)||n==="{"&&dx(e,t)}function lx(e,t,n){let r=n.pop()??!1,o=_p(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?Fp(e,t+1):t+1})}function ux(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Fp(e,t)})}function Ip(e){if(e.length>ax)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=cx(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=lx(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(_p(e,r)){let i=ux(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function dx(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function Fp(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var sx,ax,Mp=y(()=>{"use strict";sx=new Set(["+","*","?"]),ax=1e3});function Dp(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!Ip(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function Np(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function Gp(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var Hp=y(()=>{"use strict";Mp()});function zp(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+Ar(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${$n(r)})`}function Qp(e,t){let n=e.length,r=t.itemsPerPage||xt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function Bp(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} 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`]}var $p=y(()=>{"use strict";Or();li()});async function di(e){try{let t=Be(e,O.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return px(e,t.sanitizedPath,n)}catch(t){let n=at.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function px(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=mx(e),s=r&&e.limit&&!fx(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:hx(e),limit:s})}catch(T){return bx(T,e,t)}let c=a.entries.map(T=>gx(T,n,e.details??!1)),l=Dp(c,e),u=e.sortBy??"name";l=l.sort((T,L)=>{let _=0;switch(u){case"size":{let E=T.sizeBytes??(T.size?Ar(T.size):0),w=L.sizeBytes??(L.size?Ar(L.size):0);_=E-w;break}case"time":n&&T.modified&&L.modified?_=T.modified.localeCompare(L.modified):_=T.name.localeCompare(L.name);break;case"extension":_=(T.extension||"").localeCompare(L.extension||"");break;default:_=T.name.localeCompare(L.name);break}return e.reverse?-_:_}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=Qp(l,e),h=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(T=>({...Gp(T),path:T.path??`${t.replace(/\/$/,"")}/${T.name}`}))}:{path:t,...Np(p)},b=[...a.warnings,...Bp({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],x=d===0,S=zp(l);return U(jp({...x?{status:"empty"}:{},...h,summary:S,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((T,L)=>T+L.path.length,0))}function fx(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function mx(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function hx(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function gx(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:$n(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=yx(e.permissions)),o}function yx(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function bx(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=at.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return M(a,t,{toolName:O.LOCAL_VIEW_STRUCTURE})}function jp(e,t){return e}var pi=y(()=>{"use strict";li();ye();Ft();Xo();Hp();$p();ue();Ce()});function fi(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
14
- `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var gc=y(()=>{"use strict";Ce()});function yc(e,t){return D.byteToCharOffset(e,t)}function Up(e,t){return D.charToByteOffset(e,t)}function qp(e){return D.charToByteOffset(e,e.length)}function bc(e,t,n,r){return D.sliceContent(e,t,n,r)}var Wp=y(()=>{"use strict";Ce()});function Un(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=qp(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,p,f,m,h;if(o==="bytes"){let b=Math.min(t,s),x=Math.min(b+n,s);d=yc(e,b),p=yc(e,x),p<i&&Up(e,p)<x&&(p+=1);let S=bc(e,d,p-d);c=S.text,d=S.charOffset,p=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,f=u<s;let T=r.actualOffset??b;m=Math.floor(T/a)+1,h=Math.max(m,Math.ceil(s/a))}else{let b=bc(e,t,n);c=b.text,d=b.charOffset,p=b.charOffset+b.charLength,l=b.byteOffset,u=b.byteOffset+b.byteLength,f=p<i;let x=r.actualOffset??d;m=Math.floor(x/a)+1,h=Math.max(m,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:f?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:f?p:void 0,hasMore:f,estimatedTokens:Math.ceil(c.length/4),currentPage:m,totalPages:h}}function Rc(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}var mi=y(()=>{"use strict";Wp()});function Px(e){return e&&e.trim().length>0?e:Sx}function Vp(e,t){return D.getSemanticBoundaryOffsets(e,Px(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function Cx(e,t){let n=e.indexOf(`
15
- `,t);return n===-1?void 0:n+1}function hi(e){let t=e.trimEnd().split(`
16
- `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function gi(e,t,n){let r=Cx(e,Math.max(0,t));if(r!==void 0)return Vp(e,n).find(o=>o>=r&&o>t)}function yi(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=Vp(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=Rx?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var Rx,Sx,Sc=y(()=>{"use strict";Ce();Rx=8e3,Sx="__octocode_generic__.unknown"});function _r(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Mt(e){return _r(e).length}var Ir=y(()=>{"use strict"});function ct(){try{return gt().output.pagination.defaultCharLength}catch{return zn.pagination.defaultCharLength}}var Fr=y(()=>{"use strict";Ct()});function Kp(e,t){return n=>t}var Yp=y(()=>{"use strict"});function xx(e){return wx.test(e.split(/[?#]/,1)[0]??e)}function Xp(e,t){return xx(t)?Tx(kx(e)):null}function bi(e,t){let n=Xp(e,t);if(n===null||n.length===0)return null;let r=[];return Zp(n,r),r.join(`
17
- `)}function Jp(e,t){let n=Xp(e,t);return n===null?null:n.map(ef)}function kx(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function Tx(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n[n.length-1].level>=r.level;)n.pop();let o=n[n.length-1];o?o.children.push(r):t.push(r),n.push(r)}return t}function Zp(e,t){for(let n of e){let r=String(n.line).padStart(4," "),o=" ".repeat(Math.max(0,n.level-1));t.push(`${r}| ${o}${"#".repeat(n.level)} ${n.text}`),Zp(n.children,t)}}function ef(e){let t=`${"#".repeat(e.level)} ${e.text}`;return{name:t,kind:"markdownHeading",range:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},selectionRange:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},children:e.children.map(ef)}}var wx,Ri=y(()=>{"use strict";wx=/\.(?:md|markdown|mdx)$/i});import{open as Ex,readFile as vx,stat as Ox}from"fs/promises";import{ContentSanitizer as Lx}from"@octocodeai/octocode-engine/contentSanitizer";function rf(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function tf(e,t,n){return{...e,...rf(t,n)}}function Ax(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))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(t&&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(t&&r)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&&r)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 o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function _x(e,t){try{return{fileStats:await Ox(t)}}catch(n){let r=at.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:M(r,e,{toolName:O.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Ix(e,t){return t>xt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function Fx(e,t,n){let r=at.fileTooLarge(e.path,n,xt.LARGE_FILE_THRESHOLD_KB);return M(r,e,{toolName:O.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function Mx(e,t){let n=at.binaryFileUnsupported(e.path);return M(n,e,{toolName:O.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function Dx(e){let n=Buffer.alloc(8192),r;try{r=await Ex(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(Kp("binary sample handle close",void 0))}}async function Nx(e,t){try{return{content:await vx(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?at.fileAccessFailed(e.path,r):at.fileReadFailed(e.path,r);return{errorResult:M(i,e,{toolName:O.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Gx(e,t){return{status:"empty",errorCode:z.NO_MATCHES,totalLines:t}}function Hx(e,t,n){let r=fi(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Gx(e,n)};let o=r.lines.join(`
18
- `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let p=r.matchRanges[0],f=r.matchRanges[r.matchRanges.length-1];p&&f&&(l=p.start,u=f.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function zx(e){return e.startLine!==void 0&&e.endLine!==void 0}function Qx(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:z.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \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:z.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
19
- `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function Bx(e,t,n){let r=t.split(`
20
- `),o=Mt(t);return e.matchString?Hx(e,r,o):zx(e)?Qx(e,r,o):{resultContent:t,isPartial:!1}}function of(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",d=s;if(s!==void 0){let h=yi(e,l,s,r);u=h.chunkMode,d=h.length}let p=Un(e,l,d,s!==void 0?{pageSize:s}:void 0),f;if(p.hasMore&&u==="char-limit"&&hi(p.paginatedContent)){let h=p.charOffset+p.charLength;f=gi(e,h,r)}let m=p.hasMore&&p.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:r,charOffset:p.nextCharOffset,charLength:s??p.charLength,minify:t.minify}}}:void 0;return{windowedContent:p.paginatedContent,pagination:p,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:f,next:m,showPagination:s!==void 0||i>0||a}}function $x(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=of(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,...s!=="standard"&&{contentView:s},...d&&{isPartial:d},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...Rc(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}function nf(e,t,n,r,o,i,s){let a=of(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",isSkeleton:!0,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...rf(r,o),...a.showPagination&&{pagination:{...Rc(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function jx(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function Si(e){let t=ct();try{let n=Be(e,O.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=Ax(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await _x(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await Dx(o))return U(Mx(e,o),c);if(Ix(e,l))return U(Fx(e,o,l),c);let{content:u,errorResult:d}=await Nx(e,o);if(d||u===void 0)return d;let p=Lx.sanitizeContent(u,i),f=p.content,m=f.length,h=Buffer.byteLength(f,"utf-8"),b=p.hasSecrets?`Secrets detected and redacted: ${p.secretsDetected.join(", ")}`:void 0,x=e.minify,S=x==="standard"||x==="symbols",T=S?"standard":"none",L;if(x==="symbols"){let F=D.extractSignatures(f,i);if(F===null){let v=bi(f,i);if(v!==null)return U(nf(e,v,Mt(f),m,h,b,t),m);L=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(F!==null){let v=Mt(f),Q=D.applyContentViewMinification(F,i);return U(nf(e,Q,v,m,h,b,t),m)}}let _=Mt(f),E=Bx(e,f,t),w=F=>{let v=[...L?[L]:[],...b?[b]:[]];if(v.length===0)return F;let Q=F.warnings??[];return{...F,warnings:[...Q,...v]}};if(E.earlyResult){let F=E.earlyResult.content,v=S&&typeof F=="string"?{...E.earlyResult,content:D.applyContentViewMinification(F,i)}:E.earlyResult;return U(tf(w(Pc(jx(v,T),e,_)),m,h),m)}let N=$x(e,E,s,_,t,S,T);return U(tf(w(Pc(N,e,_)),m,h),m)}catch(n){return M(n,e,{toolName:O.LOCAL_FETCH_CONTENT})}}function Pc(e,t,n){return e}var Pi=y(()=>{"use strict";gc();Ce();mi();Sc();Or();Ir();Fr();ye();Ft();Xo();Gn();Yp();ue();Ri()});function Dt(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var Ci=y(()=>{"use strict"});function Cc(e){return Dt(e)}function Ux(e){if(e)return Dt({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function wi(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:wc(Ux(e.pagination),n.length)}}function wc(e,t,n=!1){if(e)return e.totalItemsKind!=="files"&&!n?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function xi(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:Cc(e.pagination)}}function sf(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:Cc(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=Wx(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:Cc(e.pagination)}}function Wx(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=qx[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function af(e,t,n,r="compact"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var qx,xc=y(()=>{"use strict";Ci();qx={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import Ei from"node:path";import Vx from"node:fs";function Kx(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}function Oi(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function Xx(e){return Yx.test(e)}function uf(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function Li(e,t,n){if(n){e.langType=n;return}let r=Ia(Nn(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=uf(e.include,r.include))}function Jx(e){return Fa(Nn(e))}function cf(e){let t=vi(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function Ai(e){return!!(e?.include?.length||e?.exclude?.length)}function Ec(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(cf).filter(i=>!!i);n.length>0&&!e.names&&(e.names=uf(e.names,n));let r=(t?.include??[]).filter(i=>!cf(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=Jx(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function Zx(e,t){if(Ai(t.scope)){vc(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function vc(e){e.limit=kc,e.itemsPerPage=kc}async function Dr(e){let t=e.from,n=Kx(e),r=et(e.scope),o=r?Ei.join(n,r):n;if(!Vx.existsSync(o))return{results:[],diagnostics:[P("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return rk(e,t,o);case"structure":return hk(e,t,o);case"content":return gk(e,t,o);default:return pf(e,t,o)}}function ek(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?ff(e.predicate):!1}function tk(e){return e.kind==="text"||e.kind==="regex"}function df(e){return e?.kind==="not"&&tk(e.predicate)}async function pf(e,t,n){let r=e.where;if(ek(r))return fk(e,t,n,r);if(e.view==="discovery"&&df(r))return ck(e,t,n,r);let o=pn(r);if(o.unsupported)return{results:[],diagnostics:[P(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...Oi(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...Rf(e)};Li(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await kt(s),c=wi(a,t),l=qn(a,"localSearchCode"),u=nk(a);if(u.length>0){let d=u.reduce((f,m)=>f+(m.total??0),0),p=u.reduce((f,m)=>f+m.shown,0);l.push(P("matchTruncated",`${u.length} file(s) have more matches (showed ${p} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(P("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&Xx(i.keywords)&&l.push(P("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[Wn("localSearchCode",t,r)]}}function nk(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}async function rk(e,t,n){let r=e.where;if(df(r))return ak(e,t,n,r);if(r&&ff(r))return ik(e,t,n,r);if(r&&yf(r)){let l=await pf({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};Ec(o,e.scope),Zx(o,e),ok(o,e);let i=[];r&&bf(r,o,i);let s=await jn(o),a=Lc(s,e,n);return{...xi(a,t),diagnostics:[...i,...qn(a,"localFindFiles")],provenance:[Wn("localFindFiles",t,r)]}}function ok(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function ff(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function ik(e,t,n,r){let o=[],i=[],a=[...(await ki(e,r,t,n,o,i)).values()].sort(sk(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(P("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function sk(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function ki(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>ki(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:lk(a,c));case"any":{let s=await Promise.all(t.of.map(c=>ki(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,Oc(a.get(l),u));return a}case"not":{let s=await hf(e,n,r,o),a=await ki(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return gf(e,t,n,r,o,i)}}async function ak(e,t,n,r){let o=await kt(mf(e,n,r.predicate)),i=qn(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[Wn("localSearchCode",t,r)]}}async function ck(e,t,n,r){let o=await kt(mf(e,n,r.predicate));return{...wi(o,t),diagnostics:qn(o,"localSearchCode"),provenance:[Wn("localSearchCode",t,r)]}}function mf(e,t,n){let o=pn(n).match,i={path:t,filesWithoutMatch:!0,...Oi(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...Rf(e)};return Li(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}function lk(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,Oc(o,i))}return n}function uk(e,t){return new Set([...e].filter(n=>t.has(n)))}function Oc(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}async function dk(e,t,n){return new Set((await hf(e,e.from,t,n)).keys())}async function hf(e,t,n,r){let o={path:n,entryType:"f"};Ec(o,e.scope),Ai(e.scope)&&(vc(o),o.page=1);let i=await jn(o),s=Lc(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),Tc(xi({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function pk(e,t,n,r,o){return new Set((await gf(e,t,e.from,n,r,o)).keys())}async function gf(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};Ec(u,e.scope),bf(t,u,i),Ai(e.scope)&&(vc(u),u.page=1);let d=await jn(u),p=Lc(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),Tc(xi(p,n).results)}let s=pn(t);if(s.unsupported)return i.push(P(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:kc,...Oi(e.scope)};Li(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await kt(c);return o.push({backend:"localSearchCode",source:e.from}),Tc((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function Tc(e){let t=new Map;for(let n of e)t.set(n.path,Oc(t.get(n.path),n));return t}async function fk(e,t,n,r){let o=[],i=[],s=await Ti(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(P("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function Ti(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Ti(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:uk(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Ti(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await dk(e,r,o),a=await Ti(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await pk(e,t,r,o,i),rows:[]};default:{let s=await mk(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function mk(e,t,n,r,o,i){let s=pn(t);if(s.unsupported)return i.push(P(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...Oi(e.scope)};Li(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await kt(c);return o.push({backend:"localSearchCode",source:n}),wi(l,n).results}async function hk(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await di(r);return{...sf(o,t),diagnostics:qn(o,"localViewStructure"),provenance:[Wn("localViewStructure",t,void 0)]}}async function gk(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=Pk(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Si(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...af(a,t,n,c),diagnostics:qn(a,"localGetFileContent"),provenance:[Wn("localGetFileContent",t,void 0)]}}function Lc(e,t,n){if(!Ai(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>yk(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function yk(e,t,n){let r=vi(bk(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>lf(r,i))?!1:!(n?.exclude??[]).some(i=>lf(r,i))}function bk(e,t){let n=Ei.relative(t,e);return!n||n.startsWith("..")||Ei.isAbsolute(n)?e:n}function vi(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function lf(e,t){let n=vi(t),r=vi(e),o=Rk(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Ei.posix.basename(r))}function Rk(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=Sk(r)}return new RegExp(`${t}$`)}function Sk(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function Pk(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function yf(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?yf(e.predicate):!1}function bf(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(P("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(Mr(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(Mr(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(Mr(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(P("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(Mr(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(Mr(i));break}r&&n.push(P("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function Mr(e){return P("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function Rf(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}function qn(e,t){let n=[];e.status==="error"?n.push(P("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(P(Ck(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function Ck(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function Wn(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var kc,Yx,Ac=y(()=>{"use strict";Se();ci();ui();pi();Pi();Aa();xc();Ze();$o();Cr();kc=1e4;Yx=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});import{completeMetadata as wk}from"@octocodeai/octocode-core";function Nr(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var ee,rt,Vn,Fz,_i=y(()=>{"use strict";ee=wk.toolNames,rt=ee.LSP_GET_SEMANTIC_CONTENT,Vn="oqlSearch";Fz=new Set([ee.LOCAL_RIPGREP,ee.LOCAL_FETCH_CONTENT,ee.LOCAL_FIND_FILES,ee.LOCAL_VIEW_STRUCTURE,ee.LOCAL_BINARY_INSPECT,rt])});function mn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function _c(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var Sf,Gr=y(()=>{"use strict";_i();Sf=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{CloneRepoQuerySchema as xk}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as kk}from"@octocodeai/octocode-core/schemas/outputs";var Hr,Ii,$z,Ic=y(()=>{"use strict";$e();tt();nt();Hr=he(xk),Ii=se(Hr),$z=kk.extend(je)});import{z as k}from"zod";import{FileContentQuerySchema as Pf}from"@octocodeai/octocode-core/schemas";var Tk,Ek,vk,Ok,Lk,Cf,Ak,Kn,Fi,Xz,Mi=y(()=>{"use strict";Se();$e();tt();nt();Tk=k.enum(["none","standard","symbols"]).optional().default("standard"),Ek=k.object({currentPage:k.number(),totalPages:k.number(),hasMore:k.boolean(),nextPage:k.number().optional(),charOffset:k.number().optional(),charLength:k.number().optional(),totalChars:k.number().optional(),nextCharOffset:k.number().optional()}),vk=k.object({continueChars:k.object({tool:k.literal("ghGetFileContent"),query:k.record(k.string(),k.unknown())}).optional()}),Ok=k.object({path:k.string(),content:k.string(),localPath:k.string().optional(),repoRoot:k.string().optional(),contentView:k.enum(["none","standard","symbols"]).optional(),isSkeleton:k.boolean().optional(),totalLines:k.number().optional(),sourceChars:k.number().optional(),sourceBytes:k.number().optional(),resolvedBranch:k.string().optional(),pagination:Ek.optional(),next:vk.optional(),isPartial:k.boolean().optional(),startLine:k.number().optional(),endLine:k.number().optional(),matchRanges:k.array(k.object({start:k.number(),end:k.number()})).optional(),lastModified:k.string().optional(),lastModifiedBy:k.string().optional(),warnings:k.array(k.string()).optional(),matchNotFound:k.boolean().optional(),searchedFor:k.string().optional(),cached:k.boolean().optional()}),Lk=k.object({path:k.string(),localPath:k.string(),repoRoot:k.string().optional(),fileCount:k.number(),totalSize:k.number(),complete:k.boolean().optional(),directoryEntryCount:k.number().optional(),eligibleFileCount:k.number().optional(),savedFileCount:k.number().optional(),skipped:k.object({nonFile:k.number(),missingDownloadUrl:k.number(),oversized:k.number(),binary:k.number(),fileLimit:k.number(),fetchFailed:k.number(),totalSizeLimit:k.number(),pathTraversal:k.number()}).optional(),limits:k.object({maxDirectoryFiles:k.number(),maxTotalSize:k.number(),maxFileSize:k.number()}).optional(),warnings:k.array(k.string()).optional(),files:k.array(k.object({path:k.string(),size:k.number(),type:k.string()})).optional(),cached:k.boolean().optional(),resolvedBranch:k.string().optional()}),Cf={startLine:Bn,endLine:Bn,contextLines:Qn,charOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional(),minify:Tk},Ak=be(Pf,Cf),Kn=he(Pf,Cf),Fi=se(Ak),Xz=k.object({base:k.string().optional(),shared:k.record(k.string(),k.union([k.string(),k.number(),k.boolean()])).optional(),responsePagination:je.responsePagination,results:k.array(k.object({id:k.string(),data:k.object({owner:k.string(),repo:k.string(),files:k.array(Ok).optional(),directories:k.array(Lk).optional()}).optional()})),errors:k.array(k.object({id:k.string(),owner:k.string().optional(),repo:k.string().optional(),path:k.string().optional(),error:k.string()})).optional()})});import{z as $}from"zod";import{GitHubCodeSearchQuerySchema as wf}from"@octocodeai/octocode-core/schemas";var xf,Di,Ni,_k,sQ,Fc=y(()=>{"use strict";Se();$e();tt();nt();yt();xf={limit:H(1,100).optional(),page:de.default(1)},Di=he(wf,xf),Ni=se(be(wf,xf)),_k=xe.extend({totalMatchesKind:$.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:$.boolean().optional(),uniqueFileCount:$.number().optional()}),sQ=$.object({base:$.string().optional(),shared:$.record($.string(),$.union([$.string(),$.number(),$.boolean()])).optional(),responsePagination:je.responsePagination,results:$.array($.object({id:$.string(),data:$.object({files:$.array($.object({owner:$.string(),repo:$.string(),path:$.string(),queryId:$.string().optional(),matches:$.array($.object({value:$.string().optional(),pathOnly:$.boolean().optional(),matchIndices:$.array($.object({start:$.number(),end:$.number(),lineOffset:$.number()})).optional(),url:$.string().optional()}))})),pagination:_k.optional()})})),emptyQueries:$.array($.object({id:$.string(),nonExistentScope:$.literal(!0).optional(),incompleteResults:$.literal(!0).optional()})).optional(),warnings:$.array($.string()).optional(),errors:$.array($.object({id:$.string(),error:$.string()})).optional()})});import{z as hn}from"zod";import{GitHubPullRequestSearchQuerySchema as kf}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Fk}from"@octocodeai/octocode-core/schemas/outputs";var Tf,Mk,Xn,Gi,hQ,Hi=y(()=>{"use strict";Se();$e();tt();nt();Tf={perPage:H(1,100).optional().default(30),prNumber:H(1,1e9).optional(),limit:H(1,100).optional().default(30),page:de.default(1),filePage:de.optional(),commentPage:de.optional(),commitPage:de.optional(),itemsPerPage:H(1,100).optional().default(20),charOffset:H(0,1e8).optional(),commentBodyOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional()},Mk=be(kf,Tf),Xn=he(kf,Tf),Gi=se(Mk),hQ=Fk.extend({results:hn.array(hn.object({id:hn.string().optional(),status:hn.string().optional(),data:hn.object({pull_requests:hn.array(hn.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...je})});import{z as ne}from"zod";import{GitHubReposSearchSingleQuerySchema as Ef}from"@octocodeai/octocode-core/schemas";var vf,zi,Qi,Dk,Nk,Gk,xQ,Mc=y(()=>{"use strict";Se();$e();tt();nt();yt();vf={limit:H(1,100).optional(),page:de.default(1)},zi=he(Ef,vf),Qi=se(be(Ef,vf)),Dk=ne.object({owner:ne.string(),repo:ne.string(),stars:ne.number().optional(),forks:ne.number().optional(),openIssuesCount:ne.number().optional(),language:ne.string().optional(),license:ne.string().optional(),description:ne.string().optional(),homepage:ne.string().optional(),pushedAt:ne.string().optional(),createdAt:ne.string().optional(),defaultBranch:ne.string().optional(),topics:ne.array(ne.string()).optional(),visibility:ne.string().optional(),url:ne.string().optional(),updatedAt:ne.string().optional()}),Nk=xe.extend({totalMatchesKind:ne.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:ne.boolean().optional()}).optional(),Gk=ne.object({repositories:ne.array(ne.union([ne.string(),Dk])).optional(),pagination:Nk}).passthrough(),xQ=ne.object({results:ne.array(ne.object({id:ne.string().optional(),status:ne.string().optional(),data:Gk.optional()}).passthrough()).optional()}).extend(je)});import{GitHubViewRepoStructureQuerySchema as Of}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as zk}from"@octocodeai/octocode-core/schemas/outputs";var Lf,Bi,$i,IQ,Dc=y(()=>{"use strict";Se();Se();$e();tt();nt();Lf={maxDepth:H(0,20).optional(),page:de.default(1),itemsPerPage:H(1,200).optional()},Bi=he(Of,Lf),$i=se(be(Of,Lf)),IQ=zk.extend(je)});import{z as te}from"zod";import{NpmPackageQuerySchema as Af}from"@octocodeai/octocode-core/schemas";var _f,ji,Ui,QQ,Nc=y(()=>{"use strict";$e();tt();nt();yt();_f={page:de,mode:te.enum(["lean","full"]).optional()},ji=he(Af,_f),Ui=se(be(Af,_f,{strict:!0}),{maxQueries:5}),QQ=te.object({results:te.array(te.looseObject({id:te.string(),data:te.looseObject({packages:te.array(te.object({name:te.string(),version:te.string().optional(),description:te.string().optional(),license:te.string().optional(),downloads:te.number().optional(),repository:te.string().optional(),repositoryDirectory:te.string().optional(),repositoryId:te.string().optional(),next:te.record(te.string(),te.unknown()).optional()}).passthrough()).optional(),repositories:te.record(te.string(),te.object({repository:te.string(),owner:te.string(),repo:te.string(),repositoryDirectory:te.string().optional(),next:te.record(te.string(),te.unknown())}).passthrough()).optional(),pagination:xe.optional()}).optional(),status:te.string().optional()})).optional()}).extend(je)});import{z as ie}from"zod";import{FetchContentQuerySchema as If}from"@octocodeai/octocode-core/schemas";var Qk,Ff,Bk,Jn,qi,$k,jk,YQ,Wi=y(()=>{"use strict";Se();$e();tt();nt();yt();Qk=ie.enum(["none","standard","symbols"]).optional().default("standard"),Ff={startLine:Bn,endLine:Bn,contextLines:Qn.default(5),charOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional(),minify:Qk},Bk=be(If,Ff),Jn=he(If,Ff),qi=se(Bk,{maxQueries:5}),$k=ie.object({start:ie.number(),end:ie.number()}),jk=ie.object({path:ie.string().optional(),content:ie.string().optional(),contentView:ie.enum(["none","standard","symbols"]).optional(),isSkeleton:ie.boolean().optional(),totalLines:ie.number().optional(),sourceChars:ie.number().optional(),startLine:ie.number().optional(),endLine:ie.number().optional(),isPartial:ie.boolean().optional(),matchRanges:ie.array($k).optional(),pagination:ie.union([ni,xe]).optional(),modified:ie.string().optional(),lastModified:ie.string().optional(),lastModifiedBy:ie.string().optional(),warnings:ie.array(ie.string()).optional(),matchNotFound:ie.boolean().optional(),searchedFor:ie.string().optional()}),YQ=ie.object({results:ie.array(ie.object({id:ie.string(),status:ie.enum(["empty","error"]).optional(),data:jk}))}).extend(wt)});import{z as Re}from"zod";import{FindFilesQuerySchema as Uk}from"@octocodeai/octocode-core/schemas";function qk(e,t){e.minDepth!==void 0&&e.maxDepth!==void 0&&e.minDepth>e.maxDepth&&t.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var Mf,Df,Wk,Zn,Vi,Vk,Kk,iB,Ki=y(()=>{"use strict";Se();$e();tt();nt();yt();Mf={maxDepth:H(0,100).optional(),minDepth:H(0,100).optional(),limit:H(1,1e4).optional(),page:de.default(1),itemsPerPage:H(1,50).optional()},Df=Re.object(Object.fromEntries(Object.entries(Uk.shape).filter(([e])=>e!=="regexType")));Wk=be(Df,Mf),Zn=he(Df,Mf).superRefine(qk),Vi=se(Wk,{maxQueries:5}),Vk=Re.object({name:Re.string().optional(),path:Re.string().optional(),type:Re.enum(["file","dir","directory","link","symlink"]).optional(),size:Re.union([Re.number(),Re.string()]).optional(),modified:Re.string().optional(),accessed:Re.string().optional(),created:Re.string().optional(),permissions:Re.string().optional()}),Kk=Re.object({files:Re.array(Vk).optional(),summary:Re.string().optional(),pagination:xe.optional(),warnings:Re.array(Re.string()).optional()}),iB=Re.object({results:Re.array(Re.object({id:Re.string(),status:Re.enum(["empty","error"]).optional(),data:Kk}))}).extend(wt)});import{z as Z}from"zod";import{ViewStructureQuerySchema as Nf}from"@octocodeai/octocode-core/schemas";var Gf,Yk,er,Yi,Xk,Jk,mB,Xi=y(()=>{"use strict";Se();$e();tt();nt();yt();Gf={maxDepth:H(0,20).optional(),limit:H(1,1e4).optional(),page:de.default(1),itemsPerPage:H(1,50).optional()},Yk=be(Nf,Gf),er=he(Nf,Gf),Yi=se(Yk,{maxQueries:5}),Xk=Z.object({name:Z.string().optional(),type:Z.enum(["file","dir","directory","link","symlink"]),path:Z.string().optional(),depth:Z.number().optional(),size:Z.union([Z.number(),Z.string()]).optional(),modified:Z.string().optional(),permissions:Z.string().optional()}),Jk=Z.object({path:Z.string().optional(),entries:Z.array(Xk).optional(),files:Z.array(Z.string()).optional(),folders:Z.array(Z.string()).optional(),links:Z.array(Z.string()).optional(),summary:Z.union([Z.string(),Z.record(Z.string(),Z.unknown())]).optional(),pagination:xe.optional(),warnings:Z.array(Z.string()).optional()}),mB=Z.object({results:Z.array(Z.object({id:Z.string(),status:Z.enum(["empty","error"]).optional(),data:Jk}))}).extend(wt)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as Qf}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as Zk}from"@octocodeai/octocode-core/schemas/outputs";var eT,tT,nT,Bf,rT,es,ts,Hf,oT,iT,Ji,Zi,sT,aT,$f,tr,cT,lT,uT,jf,dT,pT,fT,mT,hT,gT,yT,zf,xB,Hc=y(()=>{"use strict";Se();$e();tt();Gr();yt();eT=H(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),tT=H(0,1e5).optional(),nT=["structured","compact"],Bf={type:R.enum(Sf).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:R.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:eT.optional(),orderHint:tT,depth:H(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:de,itemsPerPage:H(1,100).optional(),contextLines:H(0,100).optional(),format:R.enum(nT).optional().default("structured")},rT=be(Qf,Bf),es=he(Qf,Bf),ts=se(rT,{maxQueries:5}),Hf=R.object({line:R.number(),character:R.number()}),oT=R.object({start:Hf,end:Hf}),iT=R.object({startLine:R.number(),endLine:R.number()}),Ji=R.object({uri:R.string(),content:R.string().optional(),displayRange:iT.optional(),isDefinition:R.boolean().optional()}),Zi=R.string(),sT=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),aT=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),$f=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),tr=R.object({category:$f,reason:R.string()}),cT=xe,lT=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),uT=R.string(),jf=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),dT=R.string(),pT=R.object({direction:R.enum(["incoming","outgoing"]),item:jf,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),fT=R.string(),mT=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),hT=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),gT=R.string(),yT=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Ji,Zi]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Ji,Zi]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Ji,Zi]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Ji,Zi])).optional(),byFile:R.array(R.union([hT,gT])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:tr.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([jf,dT]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([pT,fT])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:mT,empty:tr.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:oT.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([lT,uT])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:tr.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:tr.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:tr.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:tr.optional()}),R.object({kind:R.literal("empty"),category:$f,reason:R.string()})]),zf=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:sT.optional(),lsp:aT.optional(),payload:yT,pagination:cT.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),xB=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:zf}),R.object({id:R.string().min(1),status:R.literal("error"),data:Zk}),R.object({id:R.string().min(1),data:zf})]))})});import{z as I}from"zod";import{LocalBinaryInspectQuerySchema as bT}from"@octocodeai/octocode-core/schemas";var RT,Uf,nr,ns,ST,PT,CT,wT,xT,kT,TT,AB,rs=y(()=>{"use strict";$e();nt();yt();RT={entryPageNumber:de.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:H(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:H(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:de.default(1).describe("1-based page for paginated entry/content listings."),detailed:I.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Uf=I.object({...bT.shape,...RT}),nr=Uf.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),ns=se(Uf,{maxQueries:5}),ST=I.object({path:I.string(),mode:I.literal("inspect"),format:I.string().optional(),size:I.number().optional(),isText:I.boolean().optional(),encoding:I.string().optional(),symbols:I.array(I.string()).optional(),imports:I.array(I.string()).optional(),exports:I.array(I.string()).optional(),sections:I.array(I.string()).optional(),warnings:I.array(I.string()).optional()}),PT=I.object({name:I.string(),size:I.number().optional(),compressedSize:I.number().optional(),isDir:I.boolean().optional(),modified:I.string().optional()}),CT=I.object({path:I.string(),mode:I.literal("list"),entries:I.array(PT).optional(),pagination:xe.optional(),warnings:I.array(I.string()).optional()}),wT=I.object({path:I.string(),mode:I.enum(["extract","decompress"]),archiveFile:I.string().optional(),content:I.string().optional(),isPartial:I.boolean().optional(),pagination:ni.optional(),warnings:I.array(I.string()).optional()}),xT=I.object({path:I.string(),mode:I.literal("strings"),strings:I.array(I.object({value:I.string(),offset:I.number().optional()})).optional(),content:I.string().optional(),totalStrings:I.number().optional(),scanOffset:I.number().optional(),nextScanOffset:I.number().optional(),hasMore:I.boolean().optional(),warnings:I.array(I.string()).optional()}),kT=I.object({path:I.string(),mode:I.literal("unpack"),localPath:I.string().optional(),fileCount:I.number().optional(),totalSize:I.number().optional(),warnings:I.array(I.string()).optional()}),TT=I.union([ST,CT,wT,xT,kT]),AB=I.object({results:I.array(I.object({id:I.string(),status:I.enum(["empty","error","success"]).optional(),data:TT}))}).extend(wt)});import{z as FB}from"zod";var XB,ET,JB,ZB,zc=y(()=>{"use strict";_i();Gr();Ic();Mi();Fc();Hi();Mc();Dc();Nc();Wi();Ki();vr();Xi();Hc();rs();In();XB=new Map([ee.GITHUB_SEARCH_CODE,ee.GITHUB_SEARCH_REPOSITORIES,ee.GITHUB_SEARCH_PULL_REQUESTS,ee.GITHUB_FETCH_CONTENT,ee.GITHUB_VIEW_REPO_STRUCTURE,ee.GITHUB_CLONE_REPO,ee.LOCAL_RIPGREP,ee.LOCAL_FIND_FILES,ee.LOCAL_FETCH_CONTENT,ee.LOCAL_VIEW_STRUCTURE,rt,ee.PACKAGE_SEARCH,...Nr()?[Vn]:[]].map((e,t)=>[e,t])),ET=["id","mainResearchGoal","researchGoal","reasoning"],JB=new Set([...ET]),ZB=[{name:ee.GITHUB_SEARCH_CODE,schema:Di,inputSchema:Ni},{name:ee.GITHUB_FETCH_CONTENT,schema:Kn,inputSchema:Fi},{name:ee.GITHUB_VIEW_REPO_STRUCTURE,schema:Bi,inputSchema:$i},{name:ee.GITHUB_SEARCH_REPOSITORIES,schema:zi,inputSchema:Qi},{name:ee.GITHUB_SEARCH_PULL_REQUESTS,schema:Xn,inputSchema:Gi},{name:ee.PACKAGE_SEARCH,schema:ji,inputSchema:Ui},{name:ee.GITHUB_CLONE_REPO,schema:Hr,inputSchema:Ii},{name:ee.LOCAL_RIPGREP,schema:Kt,inputSchema:ri},{name:ee.LOCAL_VIEW_STRUCTURE,schema:er,inputSchema:Yi},{name:ee.LOCAL_FIND_FILES,schema:Zn,inputSchema:Vi},{name:ee.LOCAL_FETCH_CONTENT,schema:Jn,inputSchema:qi},{name:rt,schema:es,inputSchema:ts},{name:ee.LOCAL_BINARY_INSPECT,schema:nr,inputSchema:ns},...Nr()?[{name:Vn,schema:No,inputSchema:un}]:[]]});function Xt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function rr(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let n=new Date;return t.getTime()-n.getTime()<300*1e3}function os(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var is=y(()=>{"use strict"});function OT(e){let t=Xt(e),n=Br.get(t);return!n||Date.now()-n.cachedAt>=vT?!1:n.credentials?!rr(n.credentials):!0}function Qc(e){e?Br.delete(Xt(e)):Br.clear()}function qf(e){let t=Xt(e);if(OT(t))return Br.get(t).credentials}function Wf(e,t){let n=Xt(e);Br.set(n,{credentials:t,cachedAt:Date.now()})}var Br,vT,Vf=y(()=>{"use strict";is();Br=new Map,vT=300*1e3});import{existsSync as LT,mkdirSync as AT}from"node:fs";import{join as ot}from"node:path";function IT(){return rc(process.env)}function $r(){return Ge}function Kf(){LT(lt.home)||AT(lt.home,{recursive:!0,mode:_T})}var _T,Ge,lt,jr=y(()=>{"use strict";Ct();_T=448;Ge=IT(),lt={home:Ge,config:ot(Ge,".octocoderc"),credentials:ot(Ge,"credentials.json"),key:ot(Ge,".key"),session:ot(Ge,"session.json"),stats:ot(Ge,"stats.json"),tmp:ot(Ge,"tmp"),clone:ot(Ge,"tmp","clone"),tree:ot(Ge,"tmp","tree"),binary:ot(Ge,"tmp","binary"),repos:ot(Ge,"tmp","clone"),unzip:ot(Ge,"tmp","unzip"),cliConfig:ot(Ge,"config.json"),lspConfig:ot(Ge,"lsp-servers.json")}});import{z as Le}from"zod";var FT,MT,Yf,Xf=y(()=>{"use strict";FT=Le.object({token:Le.string(),tokenType:Le.literal("oauth"),scopes:Le.array(Le.string()).optional(),refreshToken:Le.string().optional(),expiresAt:Le.string().optional(),refreshTokenExpiresAt:Le.string().optional()}),MT=Le.object({hostname:Le.string(),username:Le.string(),token:FT,gitProtocol:Le.enum(["ssh","https"]),createdAt:Le.string(),updatedAt:Le.string()}),Yf=Le.object({version:Le.number(),credentials:Le.record(Le.string(),MT)})});import{existsSync as Jf,readFileSync as Zf,writeFileSync as em,unlinkSync as d$,statSync as DT,chmodSync as NT}from"node:fs";import{createCipheriv as GT,createDecipheriv as HT,randomBytes as tm}from"node:crypto";function yn(){Kf()}function om(){if(yn(),Jf(gn))return DT(gn).mode&511&63&&NT(gn,384),Buffer.from(Zf(gn,"utf8"),"hex");let e=tm(32);return em(gn,e.toString("hex"),{mode:384}),e}function Bc(e){let t=om(),n=tm(zT),r=GT(rm,t,n),o=r.update(e,"utf8","hex");o+=r.final("hex");let i=r.getAuthTag();return`${n.toString("hex")}:${i.toString("hex")}:${o}`}function $c(e){let t=om(),[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"hex"),s=Buffer.from(r,"hex"),a=HT(rm,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function ss(){if(yn(),!Jf(Ur))return{version:1,credentials:{}};try{let e=Zf(Ur,"utf8"),t=$c(e),n=JSON.parse(t),r=Yf.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function im(e){yn();let t=Bc(JSON.stringify(e,null,2));em(Ur,t,{mode:384})}var nm,Ur,gn,rm,zT,sm=y(()=>{"use strict";jr();Xf();nm=lt.home,Ur=lt.credentials,gn=lt.key,rm="aes-256-gcm",zT=16});var qr,or,jc=y(()=>{"use strict";qr="178c6fc778ccc68e1d6a",or="github.com"});import{refreshToken as QT}from"@octokit/oauth-methods";import{request as BT}from"@octokit/request";function $T(e){return e.replace(/\b(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9]{36,}\b/g,"***MASKED***").replace(/\b[a-zA-Z0-9]{40,}\b/g,"***MASKED***")}function jT(e){return e==="github.com"||e===or?"https://api.github.com":`https://${e}/api/v3`}async function am(e,t=or,n=qr){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(os(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await QT({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:BT.defaults({baseUrl:jT(t)})}),i={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,i),{success:!0,username:r.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?$T(o.message):"Token refresh failed"}}}async function cm(e,t=or,n=qr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!rr(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await am(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var lm=y(()=>{"use strict";is();jc()});import{execFile as UT}from"child_process";function Uc(e){return new Promise(t=>{let n=["auth","token"];e&&n.push("--hostname",e);let r=process.env.PATH??"",o=new Set(r.split(":")),i=qT.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;UT("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var qT,qc=y(()=>{"use strict";qT=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function um(e){Wc=e}function WT(){if(!Wc)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Wc}async function as(e){let t=e?.hostname??or,n=e?.clientId??qr,r=e?.getGhCliToken??Uc,o=Jd();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await WT().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
21
- `)}return null}var Wc,dm=y(()=>{"use strict";Ct();qc();jc();Wc=null});async function pm(e){let t=Xt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=ss();return r.credentials[t]=n,im(r),Qc(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Vc(e="github.com",t){let n=Xt(e);if(!t?.bypassCache){let i=qf(n);if(i!==void 0)return i}let o=ss().credentials[n]||null;return Wf(n,o),o}async function fm(e,t){let n=await Vc(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await pm(n),!0):!1}async function mm(e,t){return cm({getCredentials:Vc,updateToken:fm},e,t)}var Kc=y(()=>{"use strict";Vf();sm();lm();dm();is();um({getTokenWithRefresh:mm})});var hm=y(()=>{"use strict";Kc();qc()});import cs from"node:os";import J$ from"node:path";var XT,JT,ZT,eE,gm=y(()=>{"use strict";XT=cs.platform()==="win32",JT=cs.platform()==="darwin",ZT=cs.platform()==="linux",eE=cs.homedir()});var ym=y(()=>{"use strict";gm()});import{z as V}from"zod";var tE,nE,ls,rE,us,bm,Rm,Sm=y(()=>{"use strict";tE=V.object({rawChars:V.number(),responseChars:V.number(),savedChars:V.number(),calls:V.number()}),nE=V.object({hits:V.record(V.string(),V.number()).default({}),rateLimits:V.number().default(0)}),ls=V.record(V.string(),V.number()).default({}),rE=V.object({toolCalls:V.number(),errors:V.number(),rateLimits:V.number(),rateLimitsByProvider:ls,rawChars:V.number(),responseChars:V.number(),savedChars:V.number(),charSavingsCalls:V.number(),githubCacheHits:V.number(),githubCacheRateLimits:V.number(),packageRegistryFailures:V.number().default(0),packageRegistryFailuresByRegistry:ls}),us=V.object({toolCalls:V.number(),errors:V.number(),rateLimits:V.number(),rateLimitsByProvider:ls,charsSavedByTool:V.record(V.string(),tE).default({}),githubCacheHits:nE.default({hits:{},rateLimits:0}),packageRegistryFailures:ls,totalUsage:rE.optional()}),bm=V.object({version:V.literal(1),sessionId:V.string(),createdAt:V.string(),lastActiveAt:V.string(),stats:us.optional()}),Rm=V.object({version:V.literal(1),stats:us})});function Pm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function oE(e){let t=e.charsSavedByTool??{},n=e.githubCacheHits??{hits:{},rateLimits:0},r=e.rateLimitsByProvider??{},o=e.packageRegistryFailures??{},i=Object.values(t).reduce((s,a)=>({rawChars:s.rawChars+a.rawChars,responseChars:s.responseChars+a.responseChars,savedChars:s.savedChars+a.savedChars,charSavingsCalls:s.charSavingsCalls+a.calls}),{rawChars:0,responseChars:0,savedChars:0,charSavingsCalls:0});return{toolCalls:e.toolCalls,errors:e.errors,rateLimits:e.rateLimits,rateLimitsByProvider:r,...i,githubCacheHits:Pm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Pm(o),packageRegistryFailuresByRegistry:o}}function Nt(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:oE(t)}}function Yc(){return Nt({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Xc=y(()=>{"use strict"});import{existsSync as wm,readFileSync as xm,writeFileSync as iE,unlinkSync as uj,renameSync as sE}from"node:fs";function Cm(e,t){let n=`${e}.tmp`;iE(n,JSON.stringify(t,null,2),{mode:384}),sE(n,e)}function aE(e){let{stats:t,...n}=e;return n}function cE(e){let t=JSON.parse(e),n=Rm.safeParse(t);if(n.success)return Nt(n.data.stats);let r=us.safeParse(t);return r.success?Nt(r.data):null}function lE(e){let t=e?Nt(e):Yc();if(!wm(Vr))return t;try{let n=xm(Vr,"utf8"),r=cE(n);return r||t}catch{return t}}function Jc(e){yn(),Cm(Vr,{version:e.version,stats:Nt(e.stats)}),Cm(Wr,aE(e))}function km(){if(!wm(Wr))return null;try{let e=xm(Wr,"utf8"),t=JSON.parse(e),n=bm.safeParse(t);return n.success?{...n.data,stats:lE(n.data.stats)}:null}catch{return null}}var Wr,Vr,ds=y(()=>{"use strict";Kc();jr();Sm();Xc();Wr=lt.session,Vr=lt.stats});function dE(){Tm||(Tm=!0,Em=()=>{ps()},vm=()=>{ps()},Om=()=>{ps()},process.on("exit",Em),process.on("SIGINT",vm),process.on("SIGTERM",Om))}function pE(){Zc||(Zc=setInterval(()=>{Kr&&Jt&&(Jc(Jt),Kr=!1)},uE),Zc.unref())}function Lm(){if(Jt)return Jt;let e=km();return e&&(Jt=e),e}function Am(e){Jt=e,Kr=!0,dE(),pE()}function ps(){if(!el&&Kr&&Jt){el=!0;try{Jc(Jt),Kr=!1}catch{}finally{el=!1}}}var uE,Jt,Kr,Zc,Tm,Em,vm,Om,el,_m=y(()=>{"use strict";ds();uE=6e4,Jt=null,Kr=!1,Zc=null,Tm=!1,Em=null,vm=null,Om=null,el=!1});import{randomUUID as kj}from"node:crypto";function fE(e){return Nt(e)}function mE(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let i=n[r]??{rawChars:0,responseChars:0,savedChars:0,calls:0};n[r]={rawChars:i.rawChars+o.rawChars,responseChars:i.responseChars+o.responseChars,savedChars:i.savedChars+o.savedChars,calls:i.calls+o.calls}}return n}function Im(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function hE(e,t){if(!t)return e;let n={...e.hits};for(let[r,o]of Object.entries(t.hits??{}))n[r]=(n[r]??0)+o;return{hits:n,rateLimits:e.rateLimits+(t.rateLimits??0)}}function Zt(e){let t=Lm();if(!t)return{success:!1,session:null};let n=fE(t.stats),r=Nt({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Im(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:mE(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:hE(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Im(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Am(o),{success:!0,session:o}}function tl(e=1){return Zt({rateLimits:e})}function nl(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Zt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function rl(e,t=1){return Zt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ol(e=1){return Zt({githubCacheHits:{hits:{},rateLimits:e}})}var Yr=y(()=>{"use strict";ds();Xc();_m();ds()});var Fm=y(()=>{"use strict";Yr();Yr();Yr();Yr()});import{z as Pe}from"zod";var gE,Mm=y(()=>{"use strict";gE=Pe.looseObject({$schema:Pe.string().optional(),version:Pe.number().int().optional(),github:Pe.record(Pe.string(),Pe.unknown()).optional(),local:Pe.record(Pe.string(),Pe.unknown()).optional(),tools:Pe.record(Pe.string(),Pe.unknown()).optional(),network:Pe.record(Pe.string(),Pe.unknown()).optional(),lsp:Pe.record(Pe.string(),Pe.unknown()).optional(),output:Pe.record(Pe.string(),Pe.unknown()).optional()})});var Dm=y(()=>{"use strict";Mm();Ct()});import{existsSync as bE,readdirSync as RE,lstatSync as SE}from"node:fs";import{join as PE}from"node:path";function fs(e){if(!bE(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=RE(r)}catch{continue}for(let i of o){let s=PE(r,i);try{let a=SE(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var Nm=y(()=>{"use strict"});var Gt=y(()=>{"use strict";hm();ym();Fm();Dm();jr();Nm()});var bn,ms=y(()=>{bn="16.6.3"});var il,Xr,Jr,wE,en,ir,Ue,xE,Zr,kE,pU,Tt=y(()=>{"use strict";il={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},Xr={PROMISES_NOT_ARRAY:{code:"VALIDATION_PROMISES_NOT_ARRAY",message:"promises must be an array"},TIMEOUT_NOT_POSITIVE:{code:"VALIDATION_TIMEOUT_NOT_POSITIVE",message:"timeout must be positive"},CONCURRENCY_NOT_POSITIVE:{code:"VALIDATION_CONCURRENCY_NOT_POSITIVE",message:"concurrency must be positive"}},Jr={FETCH_NOT_AVAILABLE:{code:"FETCH_NOT_AVAILABLE",message:"Global fetch is not available in this environment."},FETCH_FAILED_AFTER_RETRIES:{code:"FETCH_FAILED_AFTER_RETRIES",message:(e,t)=>`Failed to fetch after ${e} attempts: ${t}`},FETCH_HTTP_ERROR:{code:"FETCH_HTTP_ERROR",message:(e,t)=>`Failed to fetch (${e} ${t})`}},wE={INVALID_FORMAT:{code:"TOOL_METADATA_INVALID_FORMAT",message:"Invalid tool metadata format from remote source."},INVALID_API_RESPONSE:{code:"TOOL_METADATA_INVALID_API_RESPONSE",message:"Invalid API response structure"}},en={PATH_IS_DIRECTORY:{code:"FILE_PATH_IS_DIRECTORY",message:e=>`Path is a directory. Use ${e} to list directory contents`},FILE_TOO_LARGE:{code:"FILE_TOO_LARGE",message:(e,t,n)=>`File too large (${e}KB > ${t}KB). Use ${n} to search within the file or use startLine/endLine parameters to get specific sections`},FILE_EMPTY:{code:"FILE_EMPTY",message:"File is empty - no content to display"},BINARY_FILE:{code:"FILE_BINARY",message:"Binary file detected. Cannot display as text - download directly from GitHub"},DECODE_FAILED:{code:"FILE_DECODE_FAILED",message:"Failed to decode file. Encoding may not be supported (expected UTF-8)"},UNSUPPORTED_TYPE:{code:"FILE_UNSUPPORTED_TYPE",message:e=>`Unsupported file type: ${e}`}},ir={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},Ue={QUERY_EMPTY:{code:"SEARCH_QUERY_EMPTY",message:"Search query cannot be empty"},NO_VALID_PARAMETERS:{code:"SEARCH_NO_VALID_PARAMETERS",message:"No valid search parameters provided"},PR_REQUIRED_PARAMS:{code:"SEARCH_PR_REQUIRED_PARAMS",message:"Owner, repo, and prNumber are required parameters"},PR_SINGLE_VALUES:{code:"SEARCH_PR_SINGLE_VALUES",message:"Owner and repo must be single values"},PULL_REQUEST_SEARCH_FAILED:{code:"SEARCH_PR_SEARCH_FAILED",message:e=>`Pull request search failed: ${e}`},PULL_REQUEST_LIST_FAILED:{code:"SEARCH_PR_LIST_FAILED",message:e=>`Pull request list failed: ${e}`},PULL_REQUEST_FETCH_FAILED:{code:"SEARCH_PR_FETCH_FAILED",message:(e,t)=>`Failed to fetch pull request #${e}: ${t}`}},xE={NO_TOOLS_REGISTERED:{code:"STARTUP_NO_TOOLS_REGISTERED",message:"No tools were successfully registered"},UNCAUGHT_EXCEPTION:{code:"STARTUP_UNCAUGHT_EXCEPTION",message:e=>`Uncaught exception: ${e}`},UNHANDLED_REJECTION:{code:"STARTUP_UNHANDLED_REJECTION",message:e=>`Unhandled rejection: ${e}`},STARTUP_FAILED:{code:"STARTUP_FAILED",message:e=>`Startup failed: ${e}`}},Zr={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},kE={EXECUTION_FAILED:{code:"TOOL_EXECUTION_FAILED",message:(e,t)=>`Tool ${e} execution failed: ${t}`},SECURITY_VALIDATION_FAILED:{code:"TOOL_SECURITY_VALIDATION_FAILED",message:(e,t)=>`Security validation failed for ${e}: ${t}`}},pU={...il,...Xr,...Jr,...wE,...en,...ir,...Ue,...xE,...Zr,...kE}});import{maskSensitiveData as TE}from"@octocodeai/octocode-engine/mask";async function Gm(){try{let e=await EE({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:vE.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Hm(){if(to!==null)return;if(eo!==null)return eo;let e=(async()=>{let t=gt(),n=await Gm();to={version:bn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();eo=e;try{await e}catch(t){throw eo===e&&(to=null,eo=null),t}}function zm(){if(!to){let e=TE(il.NOT_INITIALIZED.message);throw new Error(e)}return to}async function Qm(){return(await Gm()).token}function sl(){return"github"}function al(){let e=gt().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var to,eo,EE,vE,no=y(()=>{"use strict";Gt();Ct();ms();Tt();to=null,eo=null,EE=as,vE=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});function tn(e){(e.provider?Zt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):tl(1)).session&&e.provider==="github"&&ol(1)}function Bm(e){Zt({packageRegistryFailures:{[e]:1}})}var hs=y(()=>{"use strict";Gt()});import{Octokit as OE}from"octokit";import{throttling as LE}from"@octokit/plugin-throttling";import{createHash as AE}from"crypto";function _E(e){return AE("sha256").update(e).digest("hex").substring(0,16)}function Wm(e){return Date.now()-e.createdAt>FE}function Vm(){for(let[e,t]of Ht.entries())Wm(t)&&Ht.delete(e);if(Ht.size>cl){let e=Ht.size-cl,t=0;for(let[n]of Ht){if(t>=e)break;Ht.delete(n),t++}}}function DE(){ro||(ro=setInterval(Vm,ME),typeof ro=="object"&&"unref"in ro&&ro.unref())}function Um(e,t,n){tn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function GE(e){let t=zm(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${bn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:NE(),log:r,...e&&{auth:e}};return new IE(o)}async function ge(e){DE();let t=e?.token??await Qm(),n=t?_E(t):"ANONYMOUS",r=Ht.get(n);if(r&&!Wm(r))return r.client;Ht.size>=cl&&Vm();let o=GE(t??void 0);return Ht.set(n,{client:o,createdAt:Date.now()}),o}async function it(e,t,n){let r=`${e}/${t}`,o=oo.get(r);if(o)return o;let i=await ge(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return qm(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),qm(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function qm(e,t){if(oo.size>=HE){let n=oo.keys().next().value;n!==void 0&&oo.delete(n)}oo.set(e,t)}var IE,FE,cl,ME,Ht,ro,$m,jm,NE,HE,oo,qe=y(()=>{"use strict";no();no();ms();hs();IE=OE.plugin(LE),FE=300*1e3,cl=50,ME=60*1e3;Ht=new Map,ro=null;$m=3,jm=60;NE=()=>({onRateLimit:(e,t,n,r)=>(Um("primary",e,t),r<$m&&e<jm),onSecondaryRateLimit:(e,t,n,r)=>(Um("secondary",e,t),r<$m&&e<jm)});HE=200,oo=new Map});var q,ke,Km,ll,ul,gs,Ym=y(()=>{"use strict";q={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},ke={[q.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[q.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[q.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[q.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[q.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[q.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[q.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[q.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[q.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[q.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Km={401:q.AUTH_REQUIRED,403:q.FORBIDDEN_PERMISSIONS,404:q.NOT_FOUND,422:q.INVALID_REQUEST,502:q.SERVER_UNAVAILABLE,503:q.SERVER_UNAVAILABLE,504:q.SERVER_UNAVAILABLE},ll={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},ul={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},gs={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as Xm}from"octokit";function Rn(e){if(!(e instanceof Xm)||e.status!==422)return!1;let t=e.response?.data?.errors;return!Array.isArray(t)||t.length===0?!1:t.some(n=>{let r=typeof n?.message=="string"?n.message.toLowerCase():"";return zE.some(o=>r.includes(o))})}function ae(e){return e instanceof Xm?QE(e):e instanceof Error?KE(e):{error:typeof e=="string"?e:ke[q.UNKNOWN].message,type:"unknown"}}function QE(e){let{status:t,message:n,response:r}=e;if(t===403)return $E(n,r);if(t===429)return BE(n,r);let o=Km[t];return o?VE(o,t):sr(q.UNKNOWN,{error:n||ke[q.UNKNOWN].message,status:t})}function dl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function BE(e,t){let n=t?.headers,r=dl(n,"retry-after"),o=dl(n,"x-ratelimit-reset"),i=dl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+gs.RESET_BUFFER_SECONDS,0):void 0);return tn({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),sr(q.RATE_LIMIT_PRIMARY,{error:e||ke[q.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ke[q.RATE_LIMIT_PRIMARY].suggestion})}function $E(e,t){let n=t?.headers;if(ul.SECONDARY.test(e))return jE(n);let r=n?.["x-ratelimit-remaining"],o=WE(t);return r!==void 0&&String(r)==="0"||o?UE(n):qE(n)}function jE(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?gs.SECONDARY_FALLBACK_SECONDS:t;return tn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),sr(q.RATE_LIMIT_SECONDARY,{error:ke[q.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ke[q.RATE_LIMIT_SECONDARY].suggestion})}function UE(e){let t=e?.["x-ratelimit-reset"],n=t?parseInt(String(t),10):NaN,r=isNaN(n)?null:new Date(n*1e3),o=r?Math.max(Math.ceil((r.getTime()-Date.now())/1e3)+gs.RESET_BUFFER_SECONDS,0):void 0,i=r?ke[q.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ke[q.RATE_LIMIT_PRIMARY].messageWithoutTime;return tn({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),sr(q.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ke[q.RATE_LIMIT_PRIMARY].suggestion})}function qE(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ke[q.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=YE(String(t),String(n))),sr(q.FORBIDDEN_PERMISSIONS,{error:ke[q.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function WE(e){return e?.data?.errors?.some(n=>n.type===ul.GRAPHQL_TYPE)??!1}function VE(e,t){let n=ke[e];return sr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function KE(e){return ll.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ke[q.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ke[q.NETWORK_CONNECTION_FAILED].suggestion}:ll.TIMEOUT.some(t=>e.message.includes(t))?{error:ke[q.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ke[q.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function sr(e,t){return{type:"http",...t}}function YE(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?ke[q.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ke[q.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var zE,zt=y(()=>{"use strict";Ym();hs();zE=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function XE(e){return`user:${e}`}function Jm(e){return e.startsWith('"')||ev.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function Zm(e){return new pl().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function eh(e){return new fl().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function th(e){return new ml().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function nh(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var JE,ZE,ev,io,pl,fl,ml,ys=y(()=>{"use strict";JE=/[@/]/,ZE=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ev=/^[A-Za-z0-9_-]+$/;io=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(XE(r))});return this}addDateFilters(t){return Object.entries({created:"created",updated:"updated","author-date":"author-date","committer-date":"committer-date","merged-at":"merged",closed:"closed"}).forEach(([r,o])=>{let i=t[r];i&&this.queryParts.push(`${o}:${i}`)}),this}addArrayFilter(t,n,r=!1){return t&&t!==null&&(Array.isArray(t)?t:[t]).forEach(i=>{let s=r?`"${i}"`:i;this.queryParts.push(`${n}:${s}`)}),this}addBooleanFilter(t,n,r){return t===!0?this.queryParts.push(n):t===!1&&this.queryParts.push(r),this}addSimpleFilter(t,n){return t!=null&&this.queryParts.push(`${n}:${t}`),this}addQuotedFilter(t,n){if(t!=null){let o=JE.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},pl=class extends io{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(Jm))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(ZE):null;return o&&(r=o[1],n=n.slice(0,o.index)||void 0),this.addSimpleFilter(r,"filename"),this.addSimpleFilter(t.extension,"extension"),this.addQuotedFilter(n,"path"),t.language&&this.queryParts.push(`language:${t.language}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="file"?this.queryParts.push("in:file"):r==="path"&&this.queryParts.push("in:path")}),this}},fl=class extends io{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Jm)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},ml=class extends io{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});import tv from"node-cache";import nv from"crypto";function iv(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function sv(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function av(e){let t=iv(e);if(!(!t||!sv(t)))try{rl(t,1)}catch{}}function cv(){let e=Date.now();for(let[t,n]of so.entries())e-n.startedAt>ov&&so.delete(t)}function uv(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t=e,n=!1,r={};for(let o of Object.keys(t)){if(lv.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function We(e,t,n){let r=hl(uv(t)),o=n?`${n}:${r}`:r,i=nv.createHash("sha256").update(o).digest("hex");return`${rv}-${e}:${i}`}function hl(e,t=new WeakSet){return e===null?"null":e===void 0?"undefined":typeof e!="object"?String(e):t.has(e)?'"[Circular]"':(t.add(e),Array.isArray(e)?`[${e.map(o=>hl(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${hl(i,t)}`}).join(",")}}`)}function dv(e){return rh[e]||rh.default}function pv(e,t,n){try{return Sn.set(e,t,n),ar.sets++,ar.totalKeys=Sn.keys().length,!0}catch{try{let r=Sn.keys();for(let o of r)Sn.get(o);return Sn.set(e,t,n),ar.sets++,ar.totalKeys=Sn.keys().length,!0}catch{return!1}}}async function Ve(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Sn.get(e);if(i!==void 0)return ar.hits++,av(e),i}catch{}cv();let r=so.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ar.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=dv(l)}pv(e,i,a)}return i}finally{so.delete(e)}})();return so.set(e,{promise:o,startedAt:Date.now()}),o}var rv,ov,Sn,ar,rh,so,lv,nn=y(()=>{"use strict";Gt();rv="v1",ov=300*1e3,Sn=new tv({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ar={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},rh={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},so=new Map;lv=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as BU,DISCOVERY_IGNORED_FILE_NAMES as $U,DISCOVERY_IGNORED_FOLDER_NAMES as jU,getDiscoveryExtension as oh,shouldIgnoreDiscoveryDir as ao,shouldIgnoreDiscoveryFile as cr}from"@octocodeai/octocode-engine/security";var co=y(()=>{"use strict"});function bs(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var gl=y(()=>{"use strict"});import{ContentSanitizer as fv}from"@octocodeai/octocode-engine/contentSanitizer";async function sh(e,t,n){let r=We("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await Ve(r,async()=>await mv(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function mv(e,t){try{let n=await ge(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(x=>x&&x.trim()).length===0)return{error:Ue.QUERY_EMPTY.message,type:"http",status:400};let r=Zm(e);if(!r.trim())return{error:Ue.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:ih,100),i=e.page||1,s={q:r,per_page:o,page:i,headers:{Accept:"application/vnd.github.v3.text-match+json"}},a=await n.rest.search.code(s),c=await hv(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),p=Math.min(Math.ceil(d/o),10),f=Math.min(i,Math.max(1,p)),m=f<p,h=Math.min(d,p*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:f,totalPages:p,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:m,...m?{nextPage:f+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:bs(a.headers),rawResponseChars:B(a.data)}}catch(n){if(Rn(n)){let o=Math.min(typeof e.limit=="number"?e.limit:ih,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return ae(n)}}async function hv(e,t){let n=gv(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!cr(f.path)),c=0,l=0,u=await Promise.allSettled(a.map(async f=>{s.add(f.path);let m=[],h=await Promise.allSettled((f.text_matches||[]).map(async L=>{let _=L.fragment,E=fv.sanitizeContent(_||"",f.path);_=E.content,E.hasSecrets&&r.add(`Secrets detected in ${f.path}: ${E.secretsDetected.join(", ")}`),E.warnings.length>0&&E.warnings.forEach(w=>r.add(`${f.path}: ${w}`));try{let w=await D.minifyContent(_||"",f.path);_=w.content,w.failed?o=!0:w.type!=="failed"&&(m.push(w.type),i.push(w.type))}catch{o=!0}return{context:_||"",positions:L.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),b=h.filter(L=>L.status==="fulfilled").map(L=>L.value),x=h.filter(L=>L.status==="rejected").length;x>0&&(l+=x);let S=f,T=Array.from(new Set(m));return{path:f.path,matches:b,url:f.html_url,repository:{nameWithOwner:f.repository.full_name,url:f.repository.url,pushedAt:f.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...T.length>0&&{minificationType:T.join(",")}}})),d=u.filter(f=>f.status==="fulfilled").map(f=>f.value);c=u.filter(f=>f.status==="rejected").length;let p={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let f=n.full_name.split("/");return f.length===2&&f[0]&&f[1]?{owner:f[0],repo:f[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(p.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(p.matchLocations=Array.from(r)),p.minified=!o,p.minificationFailed=o,i.length>0&&(p.minificationTypes=Array.from(new Set(i))),p}function gv(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var ih,ah=y(()=>{"use strict";Ce();qe();zt();ys();nn();co();Tt();ue();gl();Se();ih=30});function lh(e){let t={},n=e.license;n?.spdx_id&&n.spdx_id!=="NOASSERTION"&&(t.license=n.spdx_id);let r=e.homepage;return r&&(t.homepage=r),t}async function uh(e,t,n){let r=We("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await Ve(r,async()=>await bv(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function yv(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(f){if(f?.status!==404)return ae(f);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(h){return ae(h)}}let a=i.map(f=>{let h=f.full_name.split("/"),b=h[0]||"",x=h[1]||"";return{owner:b,repo:x,defaultBranch:f.default_branch,stars:f.stargazers_count||0,description:f.description?f.description:"No description",url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at,pushedAt:f.pushed_at,visibility:f.visibility,...f.topics&&f.topics.length>0&&{topics:f.topics},...f.forks_count&&f.forks_count>0&&{forksCount:f.forks_count},...f.open_issues_count&&f.open_issues_count>0&&{openIssuesCount:f.open_issues_count},...f.language&&{language:f.language},...lh(f)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),p=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:p,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:B(i)}}async function bv(e,t){try{let n=await ge(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await yv({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=eh(e);if(!i.trim())return{error:Ue.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||ch,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let L=S.full_name.split("/"),_=L[0]||"",E=L[1]||"";return{owner:_,repo:E,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...lh(S)}}),p=u.data.total_count,f=Math.min(p,1e3),m=Math.min(Math.ceil(f/s),10),h=Math.min(a,Math.max(1,m)),b=h<m,x=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:h,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:x,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:h+1}:{}}},status:200,headers:bs(u.headers),rawResponseChars:B(u.data)}}catch(n){if(Rn(n)){let r=Math.min(e.limit||ch,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return ae(n)}}var ch,dh=y(()=>{"use strict";qe();zt();ys();nn();Tt();ue();gl();Se();ch=30});function lr(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var Rs=y(()=>{"use strict"});function Te(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function Rv(e){if(e.rateLimitRemaining===void 0&&e.retryAfter===void 0&&e.rateLimitReset===void 0)return;let t=e.rateLimitReset,n=t&&!isNaN(t)?Math.floor(t/1e3):Math.floor(Date.now()/1e3)+(e.retryAfter??3600);return{remaining:e.rateLimitRemaining??0,reset:n,retryAfter:e.retryAfter}}function Qt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:Rv(e)}}function Ss(e){return Sv(e)?Qt({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function Sv(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||Pv(n)}function Pv(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var Et=y(()=>{"use strict"});function ph(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Cv(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ph(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function wv(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ph(e.pagination)},nonExistentScope:e.nonExistentScope}}async function fh(e,t,n=Te){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await sh(s,t);return lr(a)?Qt(a):a.data?{data:Cv(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??B(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function mh(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await uh(n,t);return"error"in r?Ss(r)??{error:"Unknown GitHub API error",status:500,provider:"github"}:!("data"in r)||!r.data?{error:"No data returned from GitHub API",status:500,provider:"github"}:{data:wv(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??B(r.data)}}var hh=y(()=>{"use strict";ah();dh();Rs();ue();Et();Et()});import{RequestError as gh}from"octokit";async function kv(e,t,n,r,o,i,s,a){let c=await it(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=ae(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,p=await Sh(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...Rh(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function Tv(e,t,n,r,o,i){let s=ae(t),a=await Sh(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Rh(o,a)]),s}async function yh(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:en.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:en.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:en.DECODE_FAILED.message,type:"unknown",status:422}}}async function bh(e,t,n,r,o){try{let i=await e.rest.git.getBlob({owner:t,repo:n,file_sha:r}),{content:s,encoding:a}=i.data;return a==="base64"?yh(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return ae(i)}}async function Ev(e,t,n,r,o,i){try{let s=r.split("/").slice(0,-1).join("/"),a=r.split("/").pop();if(!a)return{error:`Cannot determine file name from path: ${r}`,type:"unknown",status:400};let c=o||await it(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(p=>p.name===a&&p.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await bh(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return ae(s)}}async function Ps(e,t){try{let n=await ge(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof gh&&d.status===404)if(s){let p=await kv(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await Tv(n,d,r,o,i,s);else{if(d instanceof gh&&d.status===413)return await Ev(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:en.PATH_IS_DIRECTORY.message(O.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in u&&u.type==="file"){let d=typeof u.content=="string"?u.content:"",p=u.size??0,f;if(d.length>0)f=await yh(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await bh(n,r,o,u.sha,i);else return{error:en.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await it(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:B(u)}}return{error:en.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return ae(n)}}function Rh(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Sh(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(f=>f.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(f=>f.name===s?!1:!!f.name.startsWith(d+".")).forEach(f=>l.push(f.path)),l.length===0&&d.length>=3&&c.filter(m=>{let h=m.name.replace(/\.[^/.]+$/,"");return h!==d&&h.length>=3&&(d.startsWith(h)||h.startsWith(d))}).forEach(m=>l.push(m.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var yl=y(()=>{"use strict";qe();zt();ye();Tt();ue()});import{ContentSanitizer as Ph}from"@octocodeai/octocode-engine/contentSanitizer";function Ov(){let e=ct();return Math.min(e,8e3)}function lo(e,t){return{sourceChars:e,sourceBytes:t}}function Ch(e,t,n){let r=e.content??"",o=n??Ov();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=yi(r,t,o,i),c=Un(r,t,s),l;if(c.hasMore&&a==="char-limit"&&hi(c.paginatedContent)){let u=c.charOffset+c.charLength;l=gi(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function wh(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function xh(e,t,n,r,o,i,s,a,c=5,l,u,d,p="standard"){let f=e.length,m=Buffer.byteLength(e,"utf-8"),h=p==="standard"||p==="symbols",b=h?"standard":"none",x;if(p==="symbols"){let K=D.extractSignatures(e,o);if(K===null){let j=bi(e,o);if(j!==null)return{owner:t,repo:n,path:o,content:j,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Mt(e),...lo(f,m),isPartial:!1,signaturesExtracted:!0,hints:[D.SIGNATURES_ONLY_HINT]};x=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(K!==null){let j=Ph.sanitizeContent(K,o),ve=D.applyContentViewMinification(j.content,o),Oe=[D.SIGNATURES_ONLY_HINT];return l&&Oe.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),j.hasSecrets&&Oe.push(`Secrets detected and redacted: ${j.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ve,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Mt(e),...lo(f,m),isPartial:!1,signaturesExtracted:!0,hints:Oe}}}let S=new Set,T=e,L=T.split(`
22
- `),_=Mt(T),E=e,w,N,F=!1,v;if(i)E=e;else if(l){let K=d===!0,j;try{j=fi(L,l,c,u??!1,K)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:_,...lo(f,m),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(j.matchCount===0){let re=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${K?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${K?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:_,...lo(f,m),matchNotFound:!0,searchedFor:l,hints:re}}E=j.lines.join(`
23
- `);let ve=j.matchRanges[0],Oe=j.matchRanges[j.matchRanges.length-1];s=ve.start,a=Oe.end,w=ve.start,N=Oe.end,F=!0,j.matchRanges.length>1&&(v=j.matchRanges);let Ut=j.matchingLines.slice(0,5).join(", "),qt=j.matchingLines.length>5?` and ${j.matchingLines.length-5} more`:"";S.add(j.matchCount>1?`Found ${j.matchCount} occurrences of "${l}" on lines ${Ut}${qt} \u2014 all shown as ${j.matchRanges.length} slice${j.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${j.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let K=s||1,j=a||_;if(K<1||K>_)E=e;else if(j<K)E=e;else{let ve=Math.max(1,K),Oe=Math.min(_,j),Ut=L.slice(ve-1,Oe);w=ve,N=Oe,F=!0,E=Ut.join(`
24
- `),j>_&&S.add(`Requested endLine ${j} adjusted to ${_} (file end)`)}}let Q=Ph.sanitizeContent(E,o);if(E=h?D.applyContentViewMinification(Q.content,o):Q.content,Q.hasSecrets&&S.add(`Secrets detected and redacted: ${Q.secretsDetected.join(", ")}`),Q.warnings.length>0&&Q.warnings.forEach(K=>S.add(K)),_>2e3&&p!=="symbols"&&!l&&!s&&!a&&!i){let K=Math.max(1,_-200);S.add(`Large file (${_} lines) \u2014 minify:"symbols" for an export index, or startLine=${K} for the tail.`)}let G=Array.from(S);return{owner:t,repo:n,path:o,content:E,...b!=="standard"&&{contentView:b},branch:r,totalLines:_,...lo(f,m),...F&&{startLine:w,endLine:N,isPartial:F},...v&&{matchRanges:v},...G.length>0&&{matchLocations:G},...(G.length>0||x)&&{warnings:[...x?[x]:[],...G]}}}var kh=y(()=>{"use strict";Fr();Se();Ce();Ir();mi();Sc();gc();Ri()});async function Th(e,t,n){let r=We("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await Ve(r,async()=>await Ps(e,t),{shouldCache:m=>"data"in m&&!m.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await xh(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,l=e.charOffset??0,u=e.charLength,d=e.fullContent===!0&&l===0&&u===void 0,p=a||d?c:Ch(c,l,u),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let m=await ge(t),h=await Ve(We("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>wh(m,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});h&&(p.lastModified=h.lastModified,p.lastModifiedBy=h.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:o.rawResponseChars}}var Eh=y(()=>{"use strict";qe();nn();yl();kh()});function Lv(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:Av(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function Av(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function vh(e,t,n=Te){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Th(i,t);if(lr(s))return Qt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:Lv(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??B(s.data),...a?.length?{hints:a}:{}}}var Oh=y(()=>{"use strict";Eh();Rs();ue();Et();Et()});function uo(e,t=Fv){let n=e?_r(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Lh(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function Ah(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:Iv}):""}var Iv,Fv,Cs=y(()=>{"use strict";Ce();Ir();Iv=2,Fv=20});import{ContentSanitizer as _h}from"@octocodeai/octocode-engine/contentSanitizer";function bl(e){let t=_h.sanitizeContent(e.title??""),n=e.body?_h.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function Fh(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function po(e,t={}){let n=t.charOffset??0,r=t.charLength??Mv,o=t.charLength??Dv,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=Fh(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((m,h)=>{let b=m.commentType==="review_inline"?0:1,x=h.commentType==="review_inline"?0:1;return b-x}),c=a.filter(m=>m.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Ih),d=u.map(m=>{let h=Fh(m.body,n,o,!t.includeFullCommentDetails);return{...m,body:h.value??"",...h.pagination?{body_pagination:h.pagination}:{}}}),p=!t.includeFullCommentDetails&&(a.length>u.length||d.some(m=>"body_pagination"in m)),f=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...p?[`PR comments are paginated/summarized to ${Ih} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(m=>({id:0,name:m,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((m,h)=>m+h.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((m,h)=>m+h.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(m=>({filename:m.filename,status:m.status,additions:m.additions,deletions:m.deletions,patch:m.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...p?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||f.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...f]}}}function fo(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function ws(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?Lh(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?Ah(a.patch):a.patch}))}var Mv,Dv,Ih,xs=y(()=>{"use strict";Cs();Ce();Fr();Mv=ct(),Dv=Math.round(ct()/4),Ih=3});import{ContentSanitizer as Rl}from"@octocodeai/octocode-engine/contentSanitizer";function ks(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Mh(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Dh(e){let t=Mh(e);return t?t.discussion!==!1:!1}function Nh(e){let t=Mh(e);return t?t.reviewInline!==!1:!1}function Gh(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function Hh(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function zh(e){return!!e.content?.comments?.includeBots}function Qh(e){let t=e.toLowerCase();return t.endsWith("[bot]")||Nv.has(t.replace(/\[bot\]$/,""))}function Sl(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
8
+ var KT=Object.defineProperty;var f=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var YT=(e,t)=>{for(var n in t)KT(e,n,{get:t[n],enumerable:!0})};var Ye,_n,ho,kl,Cf=f(()=>{"use strict";Ye=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","diff","research","graph","materialize"],_n=["fixes","dataflow"],ho=["packages","repositories"],kl={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});function Tl(e){return Array.isArray(e.queries)}function El(e){return Array.isArray(e.queries)}function Ol(e){return Array.isArray(e.children)}var wf=f(()=>{"use strict"});var Pt=f(()=>{"use strict";Cf();wf()});import{z}from"zod";var kf,Tf,XT,JT,sn,vl,ZT,eE,zt,Ef=f(()=>{"use strict";kf=z.enum(["smart","sensitive","insensitive"]),Tf=z.string().max(1e4),XT=z.strictObject({id:z.string().optional(),kind:z.literal("text"),value:Tf,case:kf.optional(),wholeWord:z.boolean().optional()}),JT=z.strictObject({id:z.string().optional(),kind:z.literal("regex"),value:Tf,dialect:z.enum(["rust","pcre2","provider"]).optional(),case:kf.optional(),wholeWord:z.boolean().optional(),multiline:z.boolean().optional(),dotAll:z.boolean().optional()}),sn=z.lazy(()=>z.strictObject({pattern:z.string().optional(),kind:z.string().optional(),inside:sn.optional(),has:sn.optional(),not:sn.optional(),all:z.array(sn).optional(),any:z.array(sn).optional(),stopBy:z.literal("end").optional()})),vl=z.union([sn,z.string().min(1)]),ZT=z.strictObject({id:z.string().optional(),kind:z.literal("structural"),lang:z.string().min(1),pattern:z.string().optional(),rule:vl.optional()}),eE=z.strictObject({id:z.string().optional(),kind:z.literal("field"),field:z.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:z.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:z.unknown().optional()}),zt=z.lazy(()=>z.discriminatedUnion("kind",[z.strictObject({kind:z.literal("all"),id:z.string().optional(),of:z.array(zt).min(1)}),z.strictObject({kind:z.literal("any"),id:z.string().optional(),of:z.array(zt).min(1)}),z.strictObject({kind:z.literal("not"),id:z.string().optional(),predicate:zt}),XT,JT,ZT,eE]))});import{z as P}from"zod";var As,Al,tE,Of,vf,Af,Lf,go,_f,nE,Ff,If,Mf,Df,yo,Ll,_l,an,Fn=f(()=>{"use strict";Pt();Ef();As=P.lazy(()=>P.union([P.strictObject({kind:P.literal("local"),path:P.string().min(1)}),P.strictObject({kind:P.literal("github"),repo:P.string().min(1).optional(),owner:P.string().min(1).optional(),ref:P.string().min(1).optional()}),P.strictObject({kind:P.literal("materialized"),localPath:P.string().min(1),source:As.optional()}),P.strictObject({kind:P.literal("npm")})])),Al=P.union([P.string(),P.array(P.string()).max(100)]),tE=P.strictObject({path:Al.optional(),language:Al.optional(),include:P.array(P.string()).max(100).optional(),exclude:P.array(P.string()).max(100).optional(),excludeDir:P.array(P.string()).max(100).optional(),hidden:P.boolean().optional(),noIgnore:P.boolean().optional(),minDepth:P.number().int().min(0).max(64).optional(),maxDepth:P.number().int().min(0).max(64).optional()}).optional(),Of=P.strictObject({mode:P.enum(["never","auto","required"]),strategy:P.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:P.boolean().optional(),forceRefresh:P.boolean().optional()}),vf=P.strictObject({content:P.strictObject({range:P.strictObject({startLine:P.number().int().min(1).optional(),endLine:P.number().int().min(1).optional(),contextLines:P.number().int().min(0).max(100).optional()}).optional(),match:P.strictObject({text:P.string(),regex:P.boolean().optional(),caseSensitive:P.boolean().optional()}).optional(),contentView:P.enum(["none","standard","symbols","exact","compact"]).transform(e=>e==="exact"?"none":e==="compact"?"standard":e).optional(),charOffset:P.number().int().min(0).max(1e8).optional(),charLength:P.number().int().min(1).max(5e4).optional(),fullContent:P.boolean().optional()}).optional(),tree:P.strictObject({maxDepth:P.number().int().min(0).max(64).optional(),pattern:P.string().optional(),includeSizes:P.boolean().optional(),extensions:P.array(P.string()).optional(),filesOnly:P.boolean().optional(),directoriesOnly:P.boolean().optional(),sortBy:P.enum(["name","size","time","extension"]).optional(),reverse:P.boolean().optional()}).optional()}),Af=P.strictObject({search:P.strictObject({countLinesPerFile:P.boolean().optional(),countMatchesPerFile:P.boolean().optional(),onlyMatching:P.boolean().optional(),unique:P.boolean().optional(),countUnique:P.boolean().optional(),contextLines:P.number().int().min(0).max(100).optional(),invertMatch:P.boolean().optional(),matchWindow:P.number().int().min(0).optional(),matchContentLength:P.number().int().min(1).optional(),maxMatchesPerFile:P.number().int().min(1).optional(),matchPage:P.number().int().min(1).optional(),sort:P.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:P.boolean().optional(),rankingProfile:P.string().optional(),debugRanking:P.boolean().optional()}).optional(),budget:P.strictObject({maxFiles:P.number().int().min(1).optional(),maxCandidates:P.number().int().min(1).optional(),maxBytes:P.number().int().min(1).optional(),maxMaterializedBytes:P.number().int().min(1).optional(),maxPlanNodes:P.number().int().min(1).optional(),maxBooleanExpansion:P.number().int().min(1).optional(),timeoutMs:P.number().int().min(1).optional()}).optional()}),Lf=P.enum(["discovery","paginated","detailed"]),go=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),target:P.enum(Ye),from:As.optional(),scope:tE,where:zt.optional(),materialize:Of.optional(),fetch:vf.optional(),select:P.array(P.string()).optional(),view:Lf.optional(),controls:Af.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional()}),_f=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),queries:P.array(go).min(1).max(5),combine:P.enum(["independent","merge"]).optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),explain:P.boolean().optional()}),nE=P.union([go,_f]),Ff=[...Ye,..._n],If={schema:P.literal("oql").optional(),id:P.string().optional(),mainResearchGoal:P.string().optional(),researchGoal:P.string().optional(),reasoning:P.string().optional()},Mf={...If,target:P.enum(Ff).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:As.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:zt.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:P.union([Of,P.enum(["never","auto","required"])]).optional(),fetch:vf.optional(),select:P.array(P.string()).optional(),view:Lf.optional(),controls:Af.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional(),repo:P.string().optional(),owner:P.string().optional(),ref:P.string().optional(),path:Al.optional(),text:P.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:P.string().optional(),pattern:P.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:vl.optional(),lang:P.string().optional(),and:P.array(P.unknown()).optional(),or:P.array(P.unknown()).optional(),xor:P.array(P.unknown()).optional(),noneOf:P.array(P.unknown()).optional(),oneOf:P.array(P.unknown()).optional(),invert:P.unknown().optional(),filesOnly:P.boolean().optional(),filesWithoutMatch:P.boolean().optional(),verbose:P.boolean().optional()},Df={...Mf,target:P.enum(Ff).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},yo=P.object(Df).catchall(P.unknown()),Ll=P.object(Mf).catchall(P.unknown()),_l=P.object({...If,queries:P.array(P.unknown()).min(1)}).catchall(P.unknown()),an=P.object({...Df,queries:P.array(P.unknown()).min(1).max(5).optional(),combine:P.enum(["independent","merge"]).optional()}).catchall(P.unknown())});function x(e,t,n={}){let r=n.severity??(oE.has(e)?"error":"warning"),o=n.blocksAnswer??(rE.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function Fl(e){return e.some(t=>t.blocksAnswer)}function iE(e){return e.some(t=>t.severity==="error")}var rE,oE,Ot,J=f(()=>{"use strict";rE=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),oE=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);Ot=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});function Y(...e){throw new Ot(e)}function In(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var hr=f(()=>{"use strict";J()});import{z as k}from"zod";function Gf(e,t){let n=gE[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var Te,sE,Nf,aE,cE,lE,uE,dE,pE,mE,fE,hE,gE,Hf=f(()=>{"use strict";Te=k.number().int().min(1),sE=k.number().int().min(0),Nf=k.enum(["symbols","files","dependencies","relations"]),aE=k.object({match:k.enum(["file","path"]).optional(),concise:k.boolean().optional(),extension:k.string().optional(),filename:k.string().optional(),page:Te.optional(),limit:Te.optional()}).passthrough(),cE=k.object({type:k.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:k.string().optional(),symbolName:k.string().optional(),symbolKind:k.string().optional(),lineHint:Te.optional(),orderHint:k.number().int().optional(),includeDeclaration:k.boolean().optional(),depth:k.number().int().min(0).max(20).optional(),groupByFile:k.boolean().optional(),workspaceRoot:k.string().optional(),format:k.enum(["structured","compact"]).optional(),page:Te.optional(),itemsPerPage:Te.optional()}).passthrough(),lE=k.object({keywords:k.array(k.string()).optional(),topicsToSearch:k.union([k.string(),k.array(k.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:k.string().optional(),owner:k.string().optional(),stars:k.union([k.string(),k.number()]).optional(),forks:k.string().optional(),goodFirstIssues:k.string().optional(),size:k.string().optional(),created:k.string().optional(),updated:k.string().optional(),license:k.string().optional(),match:k.array(k.enum(["name","description","readme"])).optional(),visibility:k.enum(["public","private"]).optional(),archived:k.boolean().optional(),sort:k.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:k.boolean().optional(),page:Te.optional()}).passthrough(),uE=k.object({packageName:k.string().optional(),keywords:k.array(k.string()).optional(),mode:k.enum(["lean","full"]).optional(),page:Te.optional()}).passthrough(),dE=k.object({prNumber:Te.optional(),concise:k.boolean().optional(),state:k.enum(["open","closed","merged"]).optional(),author:k.string().optional(),label:k.union([k.string(),k.array(k.string())]).optional(),keywordsToSearch:k.union([k.string(),k.array(k.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:k.string().optional(),base:k.string().optional(),created:k.string().optional(),updated:k.string().optional(),closed:k.string().optional(),"merged-at":k.string().optional(),draft:k.boolean().optional(),archived:k.boolean().optional(),sort:k.enum(["created","updated","best-match","comments","reactions"]).optional(),order:k.enum(["asc","desc"]).optional(),reviewMode:k.string().optional(),filePage:Te.optional(),commentPage:Te.optional(),commitPage:Te.optional(),charOffset:sE.optional(),charLength:Te.optional(),minify:k.enum(["none","standard"]).optional(),limit:Te.optional(),page:Te.optional(),matchString:k.string().optional(),matchScope:k.enum(["body","title","comments","reviews","all"]).optional(),content:k.record(k.string(),k.unknown()).optional()}).passthrough(),pE=k.object({path:k.string().optional(),branch:k.string().optional(),since:k.string().optional(),until:k.string().optional(),author:k.string().optional(),includeDiff:k.boolean().optional(),limit:Te.optional(),page:Te.optional()}).passthrough(),mE=k.object({prNumber:Te.optional(),files:k.array(k.string()).optional(),baseRef:k.string().optional(),headRef:k.string().optional(),path:k.string().optional()}).passthrough(),fE=k.object({goal:k.string().optional(),intent:k.enum(["general","reachability","dependencies","symbols"]).optional(),facets:k.array(Nf).optional(),mode:k.enum(["plan","analyze","prove"]).optional(),maxFiles:Te.optional()}).passthrough(),hE=k.object({goal:k.string().optional(),intent:k.enum(["general","reachability","dependencies","symbols"]).optional(),facets:k.array(Nf).optional(),mode:k.enum(["plan","analyze","prove"]).optional(),maxFiles:Te.optional(),subject:k.string().optional(),subjectKind:k.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:k.union([k.string(),k.array(k.string())]).optional(),verdict:k.union([k.string(),k.array(k.string())]).optional(),direction:k.enum(["incoming","outgoing","both"]).optional(),proof:k.enum(["none","lsp"]).optional(),proofLimit:Te.max(25).optional(),includePackets:k.boolean().optional(),includeFacts:k.boolean().optional(),includeEdges:k.boolean().optional()}).passthrough(),gE={semantics:cE,repositories:lE,packages:uE,pullRequests:dE,commits:pE,diff:mE,research:fE,graph:hE,code:aE}});function Qf(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&Y(x("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),yE(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};ho.includes(t)||Y(x("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function yE(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}var jf=f(()=>{"use strict";J();Pt();hr()});function Bf(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&Y(x("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}var zf=f(()=>{"use strict";J();hr()});function gr(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+gr(n),0):e.kind==="not"?1+gr(e.predicate):1:0}var Il=f(()=>{"use strict"});function $f(e,t){let n=SE(e);e.where&&n&&Y(x("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Ml(r,"where"),Dl(r,"where",new Map);let o=zt.safeParse(r);return o.success||Y(x("invalidQuery",In(o.error),{queryPath:"where"})),o.data}function RE(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:bE}function SE(e){let t=n=>{let r=gr(n),o=RE(e);return r>o&&Y(x("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(yr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(yr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(yr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&Y(x("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=yr(e.xor[0]),r=yr(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(PE(e.oneOf.map(yr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&Y(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&Y(x("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function yr(e){if(e&&typeof e=="object"&&"kind"in e)return e;Y(x("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function PE(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Ml(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&Y(x("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Ml(n,`${t}.of[${r}]`));break;case"not":e.predicate||Y(x("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Ml(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&Y(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":xE(e,t);break;default:break}}function Dl(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&Y(x("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>Dl(r,`${t}.of[${o}]`,n)):e.kind==="not"&&Dl(e.predicate,`${t}.predicate`,n)}function xE(e,t){if(e.op==="exists"){e.value!==void 0&&Y(x("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&Y(x("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&Y(x("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}var bE,Uf=f(()=>{"use strict";Fn();J();Il();hr();bE=64});function qf(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return qf(e.predicate);default:return!1}}function Wf(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:qf(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}var Vf=f(()=>{"use strict"});function Kf(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!wE(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function wE(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return CE.some(n=>t.includes(n))}var CE,Yf=f(()=>{"use strict";CE=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"]});function br(e){let t=Ll.safeParse(e);t.success||Y(x("invalidQuery",In(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??TE(n);r===void 0&&Y(x("invalidQuery",`Could not determine \`target\`; specify one of: ${Ye.join(", ")}.`,{queryPath:"target"})),_n.includes(r)&&Y(x("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${Ye.join(", ")}.`}})),Ye.includes(r)||Y(x("unknownField",`Unknown target "${r}".`));for(let h of Object.keys(n))kE.has(h)||Y(x("unknownField",`Unknown field "${h}" is not part of OQL.`,{queryPath:h}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=Qf(n,r),a=Bf(n,s),c=$f(n,r),l=Wf(n,s,c,r),u=EE(n),d=Kf(n,r),m={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(m.target==="code"&&!m.where&&Y(x("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.where&&Y(x("invalidQuery",`target:"${m.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.from?.kind==="github"&&!(m.from.repo&&m.from.repo.includes("/"))&&Y(x("invalidQuery",`target:"${m.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),m.target==="materialize"&&(m.where&&Y(x("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),m.from?.kind!=="github"&&m.from?.kind!=="materialized"&&Y(x("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),m.params!==void 0){let h=Gf(m.target,m.params);h&&Y(x("invalidQuery",h,{queryPath:"params"}))}let p=go.safeParse(m);return p.success||Y(x("invalidQuery",In(p.error))),p.data}function TE(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function EE(e){return e.fetch?{...e.fetch}:void 0}var kE,Ls=f(()=>{"use strict";Fn();J();Hf();Pt();hr();jf();zf();Uf();Vf();Yf();kE=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"])});function Xf(e){let t=_l.safeParse(e);t.success||Y(x("invalidQuery",In(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||Y(x("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&Y(x("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return br(i)}catch(a){throw a instanceof Ot?new Ot(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}var Jf=f(()=>{"use strict";Fn();J();hr();Ls()});function Nl(e){return Tl(e)?Xf(e):br(e)}var Gl=f(()=>{"use strict";Pt();Jf();Ls();Ls()});function Rr(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var _s=f(()=>{"use strict"});function Zf(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&OE.has(e.target)&&t.push(x("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "none" or "standard".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "none" or "standard".'}})),t}var OE,eh=f(()=>{"use strict";J();OE=new Set(["pullRequests","commits","diff"])});function Hl(e){let t={schema:$e.schema,view:e.view??$e.view,page:e.page??$e.page,itemsPerPage:e.itemsPerPage??$e.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??$e.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??$e.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??$e.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?$e.detailedCodeContext:$e.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??$e.localSearchSort),t}var $e,Fs=f(()=>{"use strict";$e={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"standard",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function vE(e){return e?.mode==="auto"||e?.mode==="required"}function AE(e,t){let n=e.target==="files"?Mn:cn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:cn,exact:!0,reason:`${t.kind} evaluated locally by ${cn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function LE(e,t,n){let r=vE(e.materialize);if(n)return _E(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:Mn,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:$t,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:Mn,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:$t,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:Mn,exact:!0,reason:`${Is(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:Mn,exact:!1,reason:`GitHub cannot enumerate files by ${Is(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Is(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:cn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:cn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:$t,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:$t,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?Ql(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:cn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:$t,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return Ql(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:Mn,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:$t,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:$t,exact:!0,reason:"path/name predicate pushed to provider"}:Ql(e,`field "${t.field}"`,r)}}function Is(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function _E(e,t,n){let r=Is(t);return n?{route:"ROUTE",backend:e.target==="files"?Mn:cn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:$t,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function Ql(e,t,n){if(n)return{route:"ROUTE",backend:cn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:$t,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function th(e,t,n=!1){return e.sourceKind==="github"?LE(e,t,n):AE(e,t)}var cn,Mn,$t,nh=f(()=>{"use strict";cn="localSearchCode",Mn="localFindFiles",$t="ghSearchCode"});function FE(){return Ms}function Dn(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return Ms.find(n=>n.id===`${t}.diff.${e.variant}`)}return Ms.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function Ds(e){return Ms.find(t=>t.id===e)}function jl(e){let t=IE(e.source,e.target);if(e.target==="diff"){let n=Rr(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return Dn({sourceKind:t,target:"diff",variant:r})}return Dn({sourceKind:t,target:e.target})}function Bl(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function rh(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function IE(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var Ms,zl=f(()=>{"use strict";_s();Ms=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function ME(e,t){return e.id??t}function Ns(e,t,n,r,o,i=!1){let s=ME(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,m)=>Ns(e,d,`${n}.of[${m}]`,r,o,i)),l=DE(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(x("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=Ns(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=th(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(x(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&oh(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:NE(e.target),exact:a.exact}),a.route}function DE(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function NE(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function oh(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Gs(e,t){if(!t)return;let n=rh(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function bo(e,t,n){if(!t)return!1;for(let r of Bl(t,n))oh(e.backendCalls,r);return!0}function ih(e,t){return $l(e,t,"files")}function $l(e,t,n,r=Dn({sourceKind:"materialized",target:n})){let o=Dn({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Gs(e,o),Gs(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),bo(e,o,t),bo(e,r,void 0),!0}function Hs(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Hs):e.kind==="not"?Hs(e.predicate):!1:!1}function sh(e){return e.target==="code"?Ds(Hs(e.where)?"local.code.structural":"local.code.textRegex"):Dn({sourceKind:"materialized",target:e.target})}function ah(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?Ds(Hs(e.where)?"local.code.structural":"local.code.textRegex")??jl({source:t,target:e.target,params:e.params}):jl({source:t,target:e.target,params:e.params})}var ch=f(()=>{"use strict";nh();J();zl()});function lh(e){return JSON.stringify(e)}function Ul(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${lh(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${lh(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Ul(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=Ul(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function uh(e){return["rule:",...Ul(e,1)].join(`
9
+ `)}var dh=f(()=>{"use strict"});function ph(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function mh(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return ph(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),ph(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=uh(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function Ut(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return mh(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=mh(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var Ro=f(()=>{"use strict";dh()});var fh,hh,gh=f(()=>{"use strict";fh={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},hh={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});function GE(e){return e.trim().replace(/^\./,"").toLowerCase()}function Nn(e){if(!e?.trim())return;let t=GE(e),n=fh[t]??hh[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function HE(e){return[...e??[]].map(t=>`**/*.${t}`)}function ql(e){return[...e??[]].map(t=>`*.${t}`)}function So(e){let t=Nn(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Qs(e){let t=Nn(e);return t?t.kind==="extension"&&t.extension?{include:HE([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function js(e){let t=Nn(e);return t?t.kind==="extension"&&t.extension?ql([t.extension]):t.kind==="language"?ql(t.extensions):t.normalized?ql([t.normalized]):[]:[]}function Wl(e){let t=Nn(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Bs(e){return Nn(e)?.canonicalLanguage}var yh=f(()=>{"use strict";gh()});var Vl=f(()=>{"use strict";yh()});var zs=f(()=>{"use strict";Vl()});function $s(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap($s):e.kind==="not"?$s(e.predicate):[e]}function Kl(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function Ie(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Sr(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Yl(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var ln=f(()=>{"use strict"});function bh(e,t,n){let r=e.where,o=r?$s(r):[],i=r&&QE.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>x("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function jE(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function Po(e,t={}){if(!e.where)return{ok:!1,diagnostics:[x("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=jE(e.where);if(n){let m=Rh(e,t);if(m.length>0)return{ok:!1,diagnostics:m};let{owner:p,repo:h}=Kl(e.from),g=e.params??{},y=typeof g.extension=="string"||typeof n.extension=="string"?{}:So(Sr(e.scope)),b=Yl(e),S=Ie(e.scope);return bh(e,{...p?{owner:p}:{},...h?{repo:h}:{},...y,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...b?{limit:b}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=Ut(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[x("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=Rh(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[x("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Kl(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:So(Sr(e.scope)),u=Yl(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return bh(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...Ie(e.scope)?{path:Ie(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function Rh(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var QE,Xl=f(()=>{"use strict";Ro();J();zs();ln();QE=new Set(["text","regex","structural","field"])});function Sh(e){return e.kind==="not"&&e.predicate.kind==="not"?Sh(e.predicate.predicate):e}function Ph(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?kl[e.target]:void 0;if(n)return n.includes(t)?[]:[x("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[x("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function xh(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=Sh(e.where),r=Po({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function Ch(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(x("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(x("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var wh=f(()=>{"use strict";J();Xl();Pt()});function Jl(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=ah(e,o);if(Gs(n,s),e.where)Ns(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(h=>h.route==="ROUTE")&&$l(n,o,e.target,sh(e));else if(e.target==="diff"){let h=Rr(e.params);h.kind==="prPatch"||h.kind==="directFile"?bo(n,s,o)||n.diagnostics.push(x("unsupportedTarget",`No transformer registered for target:"diff" lane "${h.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let h=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(h?g&&ih(n,o):bo(n,s,o))&&(!h||g)&&n.diagnostics.push(x("unsupportedTarget",h?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(x("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...xh(e,n.nodes)),n.diagnostics.push(...Ph(e)),n.diagnostics.push(...Zf(e));let a=Ch(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??$e.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(x("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=gr(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(x("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let m={input:t,normalized:e,defaults:Hl(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},p=!n.nodes.some(h=>h.route==="UNSUPPORTED")&&!n.diagnostics.some(h=>h.severity==="error"&&h.code!=="planTruncated");return{plan:m,executable:p}}var Zl=f(()=>{"use strict";_s();eh();J();Fs();Il();ch();wh()});function Pr(e){let t=zE(e),n=UE(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function zE(e){return!e.executable||e.diagnostics.some(t=>BE.has(t.code))?"unsupported":e.approximate||$E(e.diagnostics)?"candidate":Fl(e.diagnostics)||kh(e)?"partial":"proof"}function $E(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function kh(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function UE(e){return!e.executable||kh(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function eu(e){return e.some(t=>!t.exact)}function xo(e,t,n,r,o){return Pr({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var BE,xr=f(()=>{"use strict";J();BE=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});import Gn from"node:path";import{statSync as qE}from"node:fs";function Th(e){let t=Gn.resolve(e);try{if(qE(t).isDirectory())return`${t}${Gn.sep}`}catch{}return`${Gn.dirname(t)}${Gn.sep}`}function Eh(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function Oh(e,t){let n=Eh(e);if(!n)return;let r=Th(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function vh(e){let t=Eh(e);if(!t)return;let n=Th(t).slice(0,-Gn.sep.length);return r=>({kind:"local",path:Gn.isAbsolute(r)?r:Gn.join(n,r)})}var tu=f(()=>{"use strict"});function Ah(e,t){for(let n of t)n.proofGrade??=WE(e,n)}function WE(e,t){return t.kind==="code"?Co(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Co(e.where,"text")||Co(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?wo(t.data)?"missing":"graph":t.recordType==="research"?wo(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"?"text":"candidate"}function Co(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Co(n,t)):e.kind==="not"?Co(e.predicate,t):!1:!1}function wo(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!VE(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function VE(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var nu=f(()=>{"use strict"});function KE(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function Lh(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:KE(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"none",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function _h(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function YE(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function XE(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function Fh(e){let t=XE(e);return t?YE(t,"materialized"):void 0}function Ih(e,t){return Dh(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function Mh(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(wo(r))return Dh(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function Dh(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!wo(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=ZE(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function ZE(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&JE.has(o));return r.length>0?r:void 0}var JE,Nh=f(()=>{"use strict";nu();JE=new Set(["symbols","files","dependencies","relations"])});import ko from"node:path";import{statSync as eO}from"node:fs";function Gh(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=rO(e)??oO(t.query),i=tO(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"none",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function tO(e,t){if(e&&ko.isAbsolute(e))return e;if(t&&ko.isAbsolute(t)){let n=nO(t);return e?ko.resolve(n,e):t}return t??e}function nO(e){try{return eO(e).isDirectory()?e:ko.dirname(e)}catch{return ko.dirname(e)}}function rO(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function oO(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}var Hh=f(()=>{"use strict"});function iO(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function sO(e){let t=iO(e),n=Ie(e.scope),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${Qh(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${Qh(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function Qh(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function jh(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${sO(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:vh(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=aO[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function Bh(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||ru(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function ru(e,t){return e.why===t.why&&e.confidence===t.confidence}var aO,ou=f(()=>{"use strict";ln();tu();Nh();Hh();aO={code:Lh,content:_h,"record:materialized":Fh,"record:semantics":Gh,"record:research":Ih,"record:graph":Mh}});import{completeMetadata as cO}from"@octocodeai/octocode-core";function To(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var se,je,Hn,UQ,Eo=f(()=>{"use strict";se=cO.toolNames,je=se.LSP_GET_SEMANTIC_CONTENT,Hn="oqlSearch";UQ=new Set([se.LOCAL_RIPGREP,se.LOCAL_FETCH_CONTENT,se.LOCAL_FIND_FILES,se.LOCAL_VIEW_STRUCTURE,je])});function qt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function iu(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var zh,vt=f(()=>{"use strict";Eo();zh=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});var ae=f(()=>{"use strict"});import{z as Us}from"zod";function B(e,t){return Us.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Us.number().int().min(e).max(t))}function fe(e,t={}){let{maxQueries:n=5}=t;return Us.object({queries:Us.array(e).min(1).max(n).describe("Parallel queries."),...uO}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var Re,Cr,wr,uO,tt=f(()=>{"use strict";ae();Re=B(1,1e3).optional().default(1),Cr=B(0,100).optional(),wr=B(1,1e9).optional(),uO={responseCharOffset:B(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:B(1,5e4).optional().describe("Full-response char window.")}});import{z as $h}from"zod";function dO(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Uh(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=dO(e.shape[r],o);return n}function pO(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function qh(e,t){if(!t?.length)return e;let n=new Set(t);return $h.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function he(e,t={},n={}){let r=qh(e,n.omit),o=pO(r,Uh(r,t));return n.strict?o.strict():o}function Se(e,t={},n={}){let r=qh(e,n.omit),o=$h.object({...r.shape,...Uh(r,t)});return n.strict?o.strict():o}var nt=f(()=>{"use strict"});import{z as $}from"zod";function qs(e,t,n="Continue to the next page of results."){return{tool:e,query:t,why:n,confidence:"exact"}}function Ws(e,t,n,r){if(!n||!n.hasMore||n.nextCharOffset===void 0)return;let o=r?.includeCharLength!==!1;return{continueChars:{tool:e,query:{...t,charOffset:n.nextCharOffset,...o&&n.charLength!==void 0?{charLength:n.charLength}:{}}}}}var rt,kr,Pe,un,Tr,Be=f(()=>{"use strict";rt=$.object({currentPage:$.number(),totalPages:$.number(),hasMore:$.boolean(),nextPage:$.number().optional(),pageSize:$.number().optional(),totalItems:$.number().optional(),perPage:$.number().optional(),totalFound:$.number().optional(),returned:$.number().optional(),totalMatches:$.number().optional(),reportedTotalMatches:$.number().optional(),reachableTotalMatches:$.number().optional(),totalMatchesKind:$.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:$.boolean().optional(),totalResults:$.number().optional(),itemsPerPage:$.number().optional()}),kr=$.object({charOffset:$.number(),charLength:$.number(),totalChars:$.number(),hasMore:$.boolean(),nextCharOffset:$.number().optional(),currentPage:$.number().optional(),totalPages:$.number().optional(),chunkMode:$.enum(["semantic","char-limit"]).optional()}),Pe=$.object({tool:$.string(),query:$.record($.string(),$.unknown()),why:$.string().optional(),confidence:$.enum(["exact","heuristic"]).optional()}),un=rt.extend({filesPerPage:$.number().optional(),entriesPerPage:$.number().optional(),matchesPerPage:$.number().optional(),totalFiles:$.number().optional(),totalEntries:$.number().optional(),totalMatches:$.number().optional(),totalFilesFound:$.number().optional(),nextMatchPage:$.number().optional()});Tr=$.object({level:$.enum(["info","warning","error"]),message:$.string(),field:$.string().optional(),code:$.string().optional()})});import{z as ge}from"zod";function fO(e){return ge.object({id:ge.string(),status:ge.enum(["empty","error"]).optional(),data:e,diagnostics:ge.array(Tr).optional(),next:ge.record(ge.string(),Pe).optional()})}var mO,Ue,ij,dn,at=f(()=>{"use strict";Be();mO=ge.object({currentPage:ge.number(),totalPages:ge.number(),hasMore:ge.boolean(),charOffset:ge.number(),charLength:ge.number(),totalChars:ge.number(),nextCharOffset:ge.number().optional()}).optional(),Ue={base:ge.string().optional(),shared:ge.record(ge.string(),ge.union([ge.string(),ge.number(),ge.boolean()])).optional(),responsePagination:mO};ij=fO(ge.record(ge.string(),ge.unknown()).optional()),dn=Ue});import{CloneRepoQuerySchema as hO}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as gO}from"@octocodeai/octocode-core/schemas/outputs";var Er,Oo,pj,Wh=f(()=>{"use strict";tt();nt();at();Er=he(hO),Oo=fe(Er),pj=gO.extend(Ue)});import{z as O}from"zod";import{FileContentQuerySchema as Vh}from"@octocodeai/octocode-core/schemas";var yO,bO,RO,SO,PO,Kh,xO,Qn,Ao,Pj,au=f(()=>{"use strict";ae();tt();nt();at();Be();yO=O.enum(["none","standard","symbols"]).optional().default("standard"),bO=O.union([kr.extend({nextPage:O.number().optional()}),rt.extend({charOffset:O.number().optional(),charLength:O.number().optional(),totalChars:O.number().optional(),nextCharOffset:O.number().optional()})]),RO=O.record(O.string(),Pe),SO=O.object({path:O.string(),content:O.string(),localPath:O.string().optional(),repoRoot:O.string().optional(),contentView:O.enum(["none","standard","symbols"]).optional(),totalLines:O.number().optional(),sourceChars:O.number().optional(),sourceBytes:O.number().optional(),resolvedBranch:O.string().optional(),modified:O.string().optional(),fileSize:O.number().optional(),pagination:bO.optional(),next:RO.optional(),isPartial:O.boolean().optional(),startLine:O.number().optional(),endLine:O.number().optional(),matchRanges:O.array(O.object({start:O.number(),end:O.number()})).optional(),lastModified:O.string().optional(),lastModifiedBy:O.string().optional(),warnings:O.array(O.string()).optional(),matchNotFound:O.boolean().optional(),searchedFor:O.string().optional(),cached:O.boolean().optional()}),PO=O.object({path:O.string(),localPath:O.string(),repoRoot:O.string().optional(),fileCount:O.number(),totalSize:O.number(),complete:O.boolean().optional(),directoryEntryCount:O.number().optional(),eligibleFileCount:O.number().optional(),savedFileCount:O.number().optional(),skipped:O.object({nonFile:O.number(),missingDownloadUrl:O.number(),oversized:O.number(),binary:O.number(),fileLimit:O.number(),fetchFailed:O.number(),totalSizeLimit:O.number(),pathTraversal:O.number()}).optional(),limits:O.object({maxDirectoryFiles:O.number(),maxTotalSize:O.number(),maxFileSize:O.number()}).optional(),warnings:O.array(O.string()).optional(),files:O.array(O.object({path:O.string(),size:O.number(),type:O.string()})).optional(),cached:O.boolean().optional(),resolvedBranch:O.string().optional()}),Kh={startLine:wr,endLine:wr,contextLines:Cr,charOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional(),minify:yO},xO=Se(Vh,Kh),Qn=he(Vh,Kh),Ao=fe(xO),Pj=O.object({base:O.string().optional(),shared:O.record(O.string(),O.union([O.string(),O.number(),O.boolean()])).optional(),responsePagination:Ue.responsePagination,results:O.array(O.object({id:O.string(),data:O.object({owner:O.string(),repo:O.string(),files:O.array(SO).optional(),directories:O.array(PO).optional()}).optional()})),errors:O.array(O.object({id:O.string(),owner:O.string().optional(),repo:O.string().optional(),path:O.string().optional(),error:O.string()})).optional()})});import{z as Q}from"zod";import{GitHubCodeSearchQuerySchema as Yh}from"@octocodeai/octocode-core/schemas";var Xh,Lo,_o,CO,Aj,Jh=f(()=>{"use strict";ae();tt();nt();at();Be();Xh={limit:B(1,100).optional(),page:Re.default(1),match:Q.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghHistoryResearch, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},Lo=he(Yh,Xh),_o=fe(Se(Yh,Xh)),CO=rt.extend({totalMatchesKind:Q.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:Q.boolean().optional(),uniqueFileCount:Q.number().optional()}),Aj=Q.object({base:Q.string().optional(),shared:Q.record(Q.string(),Q.union([Q.string(),Q.number(),Q.boolean()])).optional(),responsePagination:Ue.responsePagination,results:Q.array(Q.object({id:Q.string(),data:Q.object({files:Q.array(Q.union([Q.string(),Q.object({owner:Q.string(),repo:Q.string(),path:Q.string(),queryId:Q.string().optional(),matches:Q.array(Q.object({value:Q.string().optional(),pathOnly:Q.boolean().optional(),matchIndices:Q.array(Q.object({start:Q.number(),end:Q.number(),lineOffset:Q.number()})).optional(),url:Q.string().optional()}))})])),pagination:CO.optional()})})),emptyQueries:Q.array(Q.object({id:Q.string(),nonExistentScope:Q.literal(!0).optional(),incompleteResults:Q.literal(!0).optional()})).optional(),warnings:Q.array(Q.string()).optional(),diagnostics:Q.array(Tr).optional(),next:Q.record(Q.string(),Pe).optional(),errors:Q.array(Q.object({id:Q.string(),error:Q.string()})).optional()})});import{z as qe}from"zod";import{GitHubPullRequestSearchQuerySchema as eg}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as kO}from"@octocodeai/octocode-core/schemas/outputs";var tg,TO,jn,Fo,Zh,Qj,cu=f(()=>{"use strict";ae();tt();nt();at();Be();tg={type:qe.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),perPage:B(1,100).optional().default(30),prNumber:B(1,1e9).optional(),issueNumber:B(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:B(1,100).optional().default(30),match:qe.array(qe.enum(["title","body","comments"])).optional().describe('Fields to match keywords against: "title", "body", "comments". Default searches all three. Use ["title"] for the most precise and fastest match. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)'),page:Re.default(1),filePage:Re.optional(),commentPage:Re.optional(),commitPage:Re.optional(),itemsPerPage:B(1,100).optional().default(20),charOffset:B(0,1e8).optional(),commentBodyOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional()},TO=Se(eg,tg),jn=he(eg,tg),Fo=fe(TO),Zh=qe.union([qe.string(),qe.object({}).passthrough()]),Qj=kO.extend({results:qe.array(qe.object({id:qe.string().optional(),status:qe.string().optional(),data:qe.object({pull_requests:qe.array(Zh).optional(),issues:qe.array(Zh).optional(),next:qe.record(qe.string(),Pe).optional()}).passthrough().optional()}).passthrough()).optional(),...Ue})});import{z as ne}from"zod";import{GitHubReposSearchSingleQuerySchema as ng}from"@octocodeai/octocode-core/schemas";var rg,Io,Mo,EO,OO,vO,Kj,og=f(()=>{"use strict";ae();tt();nt();at();Be();rg={limit:B(1,100).optional(),page:Re.default(1),match:ne.array(ne.enum(["name","description","readme"])).optional().describe("Which text fields to search: name, description, and/or readme. Defaults to name+description; add 'readme' for broader, slower full-text search. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)")},Io=he(ng,rg),Mo=fe(Se(ng,rg)),EO=ne.object({owner:ne.string(),repo:ne.string(),stars:ne.number().optional(),forks:ne.number().optional(),openIssuesCount:ne.number().optional(),language:ne.string().optional(),license:ne.string().optional(),description:ne.string().optional(),homepage:ne.string().optional(),pushedAt:ne.string().optional(),createdAt:ne.string().optional(),defaultBranch:ne.string().optional(),topics:ne.array(ne.string()).optional(),visibility:ne.string().optional(),url:ne.string().optional(),updatedAt:ne.string().optional()}),OO=rt.extend({totalMatchesKind:ne.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:ne.boolean().optional()}).optional(),vO=ne.object({repositories:ne.array(ne.union([ne.string(),EO])).optional(),pagination:OO}).passthrough(),Kj=ne.object({results:ne.array(ne.object({id:ne.string().optional(),status:ne.string().optional(),data:vO.optional()}).passthrough()).optional()}).extend(Ue)});import{GitHubViewRepoStructureQuerySchema as ig}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as LO}from"@octocodeai/octocode-core/schemas/outputs";var sg,No,Go,oB,ag=f(()=>{"use strict";ae();ae();tt();nt();at();sg={maxDepth:B(0,20).optional(),page:Re.default(1),itemsPerPage:B(1,200).optional()},No=he(ig,sg),Go=fe(Se(ig,sg)),oB=LO.extend(Ue)});import{z as Z}from"zod";import{NpmPackageQuerySchema as cg}from"@octocodeai/octocode-core/schemas";var lg,Ho,Qo,pB,ug=f(()=>{"use strict";tt();nt();at();Be();lg={page:Re,mode:Z.enum(["lean","full"]).optional(),keywords:Z.union([Z.string(),Z.array(Z.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},Ho=he(cg,lg),Qo=fe(Se(cg,lg,{strict:!0}),{maxQueries:5}),pB=Z.object({results:Z.array(Z.looseObject({id:Z.string(),data:Z.looseObject({packages:Z.array(Z.object({name:Z.string(),version:Z.string().optional(),description:Z.string().optional(),license:Z.string().optional(),downloads:Z.number().optional(),repository:Z.string().optional(),repositoryDirectory:Z.string().optional(),repositoryId:Z.string().optional(),next:Z.record(Z.string(),Pe).optional(),warnings:Z.array(Z.string()).optional(),diagnostics:Z.array(Tr).optional()}).passthrough()).optional(),repositories:Z.record(Z.string(),Z.object({repository:Z.string(),owner:Z.string(),repo:Z.string(),repositoryDirectory:Z.string().optional(),next:Z.record(Z.string(),Pe)}).passthrough()).optional(),pagination:rt.optional()}).optional(),status:Z.string().optional()})).optional()}).extend(Ue)});import{z as re}from"zod";import{FetchContentQuerySchema as dg}from"@octocodeai/octocode-core/schemas";var _O,pg,FO,Bn,jo,IO,MO,PB,lu=f(()=>{"use strict";ae();tt();nt();at();Be();_O=re.enum(["none","standard","symbols"]).optional().default("standard"),pg={startLine:wr,endLine:wr,contextLines:Cr.default(5),charOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional(),minify:_O},FO=Se(dg,pg),Bn=he(dg,pg),jo=fe(FO,{maxQueries:5}),IO=re.object({start:re.number(),end:re.number()}),MO=re.object({path:re.string().optional(),content:re.string().optional(),contentView:re.enum(["none","standard","symbols"]).optional(),totalLines:re.number().optional(),sourceChars:re.number().optional(),sourceBytes:re.number().optional(),startLine:re.number().optional(),endLine:re.number().optional(),isPartial:re.boolean().optional(),matchRanges:re.array(IO).optional(),pagination:re.union([kr.extend({nextBlockChar:re.number().optional()}),rt]).optional(),next:re.record(re.string(),Pe).optional(),modified:re.string().optional(),lastModified:re.string().optional(),lastModifiedBy:re.string().optional(),warnings:re.array(re.string()).optional(),matchNotFound:re.boolean().optional(),searchedFor:re.string().optional()}),PB=re.object({results:re.array(re.object({id:re.string(),status:re.enum(["empty","error"]).optional(),data:MO}))}).extend(dn)});import{z as ce}from"zod";import{FindFilesQuerySchema as DO}from"@octocodeai/octocode-core/schemas";function NO(e,t){e.minDepth!==void 0&&e.maxDepth!==void 0&&e.minDepth>e.maxDepth&&t.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var mg,fg,GO,zn,Bo,HO,QO,AB,du=f(()=>{"use strict";ae();tt();nt();at();Be();mg={maxDepth:B(0,100).optional(),minDepth:B(0,100).optional(),limit:B(1,1e4).optional(),page:Re.default(1),itemsPerPage:B(1,50).optional(),excludeDir:ce.array(ce.string()).optional().describe('Directory names to prune from the walk (e.g. ["node_modules","dist","coverage"]). NOTHING is excluded by default \u2014 results include build output and vendor dirs unless you pass this explicitly.')},fg=ce.object(Object.fromEntries(Object.entries(DO.shape).filter(([e])=>e!=="regexType")));GO=Se(fg,mg),zn=he(fg,mg).superRefine(NO),Bo=fe(GO,{maxQueries:5}),HO=ce.object({name:ce.string().optional(),path:ce.string().optional(),type:ce.enum(["file","dir","directory","link","symlink"]).optional(),size:ce.union([ce.number(),ce.string()]).optional(),sizeFormatted:ce.string().optional(),modified:ce.string().optional(),accessed:ce.string().optional(),created:ce.string().optional(),permissions:ce.string().optional()}),QO=ce.object({path:ce.string().optional(),files:ce.array(HO).optional(),summary:ce.string().optional(),pagination:un.optional(),next:ce.record(ce.string(),Pe).optional(),warnings:ce.array(ce.string()).optional()}),AB=ce.object({results:ce.array(ce.object({id:ce.string(),status:ce.enum(["empty","error"]).optional(),data:QO}))}).extend(dn)});import{z as F}from"zod";import{RipgrepQuerySchema as hg}from"@octocodeai/octocode-core/schemas";var jO,BO,gg,zO,$O,UO,Wt,zo,qO,WO,VO,HB,Vs=f(()=>{"use strict";ae();tt();nt();at();Be();jO=["paginated","discovery","detailed","structural"],BO=["semanticRanking"],gg={mode:F.enum(jO).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghHistoryResearch\'s `patches.mode` \u2014 different concepts sharing this name.)'),keywords:F.string().optional().describe("The search pattern (text or regex). Set fixedString:true for a literal match, or perlRegex:true for advanced regex features (lookaheads, backreferences). (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)"),filesOnly:F.boolean().optional().describe("Returns matching file paths without line content. Mutually exclusive with filesWithoutMatch. (Unlike localViewStructure's `filesOnly`, which filters a directory listing to file entries only \u2014 a different concept sharing this name.)"),pattern:F.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:F.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:Cr,matchContentLength:B(1,1e5).optional().default(500),maxMatchesPerFile:B(1,1e5).optional(),maxFiles:B(1,1e5).optional(),matchPage:Re.optional(),itemsPerPage:B(1,1e3).optional(),page:Re.default(1),unique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},zO={...gg,semanticRanking:F.never().optional()},$O=Se(hg,zO),UO=he(hg,gg,{strict:!0,omit:BO}),Wt=UO.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),zo=fe($O,{maxQueries:5}),qO=F.object({line:F.number(),endLine:F.number().optional(),value:F.string().optional(),column:F.number().optional(),endColumn:F.number().optional(),count:F.number().optional(),kind:F.string().optional(),scoreHint:F.number().optional(),metavars:F.record(F.string(),F.array(F.string())).optional(),metavarRanges:F.record(F.string(),F.array(F.object({text:F.string(),line:F.number(),column:F.number(),endLine:F.number(),endColumn:F.number()}))).optional()}),WO=F.object({path:F.string(),matches:F.array(qO).optional(),totalOccurrences:F.number().optional(),totalMatchedLines:F.number().optional(),totalMatchRows:F.number().optional(),returnedMatchRows:F.number().optional(),ranking:F.object({score:F.number(),profile:F.string().optional(),pathRole:F.string().optional(),reasons:F.array(F.string()).optional()}).optional(),matchPagination:un.optional(),pagination:un.optional(),next:F.record(F.string(),Pe).optional()}),VO=F.object({files:F.array(WO).optional(),summary:F.string().optional(),searchEngine:F.string().optional(),stats:F.object({totalOccurrences:F.number().optional(),matchedLines:F.number().optional(),filesMatched:F.number().optional(),filesSearched:F.number().optional(),bytesSearched:F.number().optional(),searchTime:F.string().optional()}).passthrough().optional(),pagination:un.optional(),next:F.record(F.string(),Pe).optional(),warnings:F.array(F.string()).optional()}),HB=F.object({results:F.array(F.object({id:F.string(),status:F.enum(["empty","error"]).optional(),data:VO}))}).extend(dn)});import{z as ee}from"zod";import{ViewStructureQuerySchema as yg}from"@octocodeai/octocode-core/schemas";var bg,KO,$n,$o,YO,XO,VB,mu=f(()=>{"use strict";ae();tt();nt();at();Be();bg={maxDepth:B(0,20).optional(),limit:B(1,1e4).optional(),page:Re.default(1),itemsPerPage:B(1,50).optional(),filesOnly:ee.boolean().optional().describe("Returns files only. Mutually exclusive with directoriesOnly. (Unlike localSearchCode's `filesOnly`, which filters search results to matching file paths \u2014 a different concept sharing this name.)")},KO=Se(yg,bg),$n=he(yg,bg),$o=fe(KO,{maxQueries:5}),YO=ee.object({name:ee.string().optional(),type:ee.enum(["file","dir","directory","link","symlink"]),path:ee.string().optional(),depth:ee.number().optional(),size:ee.union([ee.number(),ee.string()]).optional(),sizeBytes:ee.number().optional(),modified:ee.string().optional(),permissions:ee.string().optional()}),XO=ee.object({path:ee.string().optional(),entries:ee.array(YO).optional(),files:ee.array(ee.string()).optional(),folders:ee.array(ee.string()).optional(),links:ee.array(ee.string()).optional(),summary:ee.union([ee.string(),ee.record(ee.string(),ee.unknown())]).optional(),pagination:un.optional(),next:ee.record(ee.string(),Pe).optional(),warnings:ee.array(ee.string()).optional()}),VB=ee.object({results:ee.array(ee.object({id:ee.string(),status:ee.enum(["empty","error"]).optional(),data:XO}))}).extend(dn)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as Pg}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as JO}from"@octocodeai/octocode-core/schemas/outputs";var ZO,ev,tv,xg,nv,Uo,qo,Rg,rv,ov,Ks,Ys,iv,sv,Cg,Or,av,cv,lv,wg,uv,dv,pv,mv,fv,hv,gv,Sg,oz,kg=f(()=>{"use strict";ae();tt();nt();vt();Be();ZO=B(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),ev=B(0,1e5).optional(),tv=["structured","compact"],xg={type:R.enum(zh).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:R.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:ZO.optional(),orderHint:ev,depth:B(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:Re,itemsPerPage:B(1,100).optional(),contextLines:B(0,100).optional(),format:R.enum(tv).optional().default("structured")},nv=Se(Pg,xg),Uo=he(Pg,xg),qo=fe(nv,{maxQueries:5}),Rg=R.object({line:R.number(),character:R.number()}),rv=R.object({start:Rg,end:Rg}),ov=R.object({startLine:R.number(),endLine:R.number()}),Ks=R.object({uri:R.string(),content:R.string().optional(),displayRange:ov.optional(),isDefinition:R.boolean().optional()}),Ys=R.string(),iv=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),sv=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),Cg=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Or=R.object({category:Cg,reason:R.string()}),av=rt,cv=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),lv=R.string(),wg=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),uv=R.string(),dv=R.object({direction:R.enum(["incoming","outgoing"]),item:wg,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),pv=R.string(),mv=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),fv=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),hv=R.string(),gv=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Ks,Ys]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Ks,Ys]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Ks,Ys]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Ks,Ys])).optional(),byFile:R.array(R.union([fv,hv])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:Or.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([wg,uv]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([dv,pv])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:mv,empty:Or.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:rv.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([cv,lv])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:Or.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:Or.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:Or.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:Or.optional()}),R.object({kind:R.literal("empty"),category:Cg,reason:R.string()})]),Sg=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:iv.optional(),lsp:sv.optional(),payload:gv,pagination:av.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional(),next:R.record(R.string(),Pe).optional(),hints:R.array(R.string()).optional()}),oz=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),responsePagination:kr.optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:Sg}),R.object({id:R.string().min(1),status:R.literal("error"),data:JO}),R.object({id:R.string().min(1),data:Sg})]))})});var fu=f(()=>{"use strict";Wh();au();Jh();cu();og();ag();ug();lu();du();Vs();mu();kg();Fn()});import{z as Pz}from"zod";var kz,yv,Tg,Tz,Wo=f(()=>{"use strict";Eo();vt();fu();kz=new Map([se.GITHUB_SEARCH_CODE,se.GITHUB_SEARCH_REPOSITORIES,se.GITHUB_SEARCH_PULL_REQUESTS,se.GITHUB_FETCH_CONTENT,se.GITHUB_VIEW_REPO_STRUCTURE,se.GITHUB_CLONE_REPO,se.LOCAL_RIPGREP,se.LOCAL_FIND_FILES,se.LOCAL_FETCH_CONTENT,se.LOCAL_VIEW_STRUCTURE,je,se.PACKAGE_SEARCH,...To()?[Hn]:[]].map((e,t)=>[e,t])),yv=["id","mainResearchGoal","researchGoal","reasoning"],Tg=new Set([...yv]),Tz=[{name:se.GITHUB_SEARCH_CODE,schema:Lo,inputSchema:_o},{name:se.GITHUB_FETCH_CONTENT,schema:Qn,inputSchema:Ao},{name:se.GITHUB_VIEW_REPO_STRUCTURE,schema:No,inputSchema:Go},{name:se.GITHUB_SEARCH_REPOSITORIES,schema:Io,inputSchema:Mo},{name:se.GITHUB_SEARCH_PULL_REQUESTS,schema:jn,inputSchema:Fo},{name:se.PACKAGE_SEARCH,schema:Ho,inputSchema:Qo},{name:se.GITHUB_CLONE_REPO,schema:Er,inputSchema:Oo},{name:se.LOCAL_RIPGREP,schema:Wt,inputSchema:zo},{name:se.LOCAL_VIEW_STRUCTURE,schema:$n,inputSchema:$o},{name:se.LOCAL_FIND_FILES,schema:zn,inputSchema:Bo},{name:se.LOCAL_FETCH_CONTENT,schema:Bn,inputSchema:jo},{name:je,schema:Uo,inputSchema:qo},...To()?[{name:Hn,schema:yo,inputSchema:an}]:[]]});import{z as vz}from"zod";var Xs=f(()=>{"use strict";Wo()});var Og=f(()=>{"use strict";Eo()});var vg=f(()=>{"use strict";vt();Wo();Og();Xs()});var Ag=f(()=>{"use strict";Wo();Xs()});var hu=f(()=>{"use strict";Wo();Xs();vg();Ag()});function fn(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function vr(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let n=new Date;return t.getTime()-n.getTime()<300*1e3}function Js(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Zs=f(()=>{"use strict"});function Pv(e){let t=fn(e),n=Vo.get(t);return!n||Date.now()-n.cachedAt>=Sv?!1:n.credentials?!vr(n.credentials):!0}function gu(e){e?Vo.delete(fn(e)):Vo.clear()}function Lg(e){let t=fn(e);if(Pv(t))return Vo.get(t).credentials}function _g(e,t){let n=fn(e);Vo.set(n,{credentials:t,cachedAt:Date.now()})}var Vo,Sv,Fg=f(()=>{"use strict";Zs();Vo=new Map,Sv=300*1e3});import{existsSync as xv,mkdirSync as Cv}from"node:fs";import{join as xt}from"node:path";import{getOctocodeHome as wv}from"@octocodeai/config";function Tv(){return wv(process.env)}function Ar(){return ot}function Ig(){xv(Vt.home)||Cv(Vt.home,{recursive:!0,mode:kv})}var kv,ot,Vt,ea=f(()=>{"use strict";kv=448;ot=Tv(),Vt={home:ot,config:xt(ot,".octocoderc"),credentials:xt(ot,"credentials.json"),key:xt(ot,".key"),session:xt(ot,"session.json"),stats:xt(ot,"stats.json"),tmp:xt(ot,"tmp"),clone:xt(ot,"tmp","clone"),tree:xt(ot,"tmp","tree"),repos:xt(ot,"tmp","clone"),cliConfig:xt(ot,"config.json"),lspConfig:xt(ot,"lsp-servers.json")}});import{z as Me}from"zod";var Ev,Ov,Mg,Dg=f(()=>{"use strict";Ev=Me.object({token:Me.string(),tokenType:Me.literal("oauth"),scopes:Me.array(Me.string()).optional(),refreshToken:Me.string().optional(),expiresAt:Me.string().optional(),refreshTokenExpiresAt:Me.string().optional()}),Ov=Me.object({hostname:Me.string(),username:Me.string(),token:Ev,gitProtocol:Me.enum(["ssh","https"]),createdAt:Me.string(),updatedAt:Me.string()}),Mg=Me.object({version:Me.number(),credentials:Me.record(Me.string(),Ov)})});import{existsSync as Ng,readFileSync as Gg,writeFileSync as Hg,unlinkSync as a$,statSync as vv,chmodSync as Av}from"node:fs";import{createCipheriv as Lv,createDecipheriv as _v,randomBytes as Qg}from"node:crypto";function qn(){Ig()}function zg(){if(qn(),Ng(Un))return vv(Un).mode&511&63&&Av(Un,384),Buffer.from(Gg(Un,"utf8"),"hex");let e=Qg(32);return Hg(Un,e.toString("hex"),{mode:384}),e}function yu(e){let t=zg(),n=Qg(Fv),r=Lv(Bg,t,n),o=r.update(e,"utf8","hex");o+=r.final("hex");let i=r.getAuthTag();return`${n.toString("hex")}:${i.toString("hex")}:${o}`}function bu(e){let t=zg(),[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"hex"),s=Buffer.from(r,"hex"),a=_v(Bg,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function ta(){if(qn(),!Ng(Ko))return{version:1,credentials:{}};try{let e=Gg(Ko,"utf8"),t=bu(e),n=JSON.parse(t),r=Mg.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function $g(e){qn();let t=yu(JSON.stringify(e,null,2));Hg(Ko,t,{mode:384})}var jg,Ko,Un,Bg,Fv,Ug=f(()=>{"use strict";ea();Dg();jg=Vt.home,Ko=Vt.credentials,Un=Vt.key,Bg="aes-256-gcm",Fv=16});var Yo,Lr,Ru=f(()=>{"use strict";Yo="178c6fc778ccc68e1d6a",Lr="github.com"});import{refreshToken as Iv}from"@octokit/oauth-methods";import{request as Mv}from"@octokit/request";function Dv(e){return e.replace(/\b(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9]{36,}\b/g,"***MASKED***").replace(/\b[a-zA-Z0-9]{40,}\b/g,"***MASKED***")}function Nv(e){return e==="github.com"||e===Lr?"https://api.github.com":`https://${e}/api/v3`}async function qg(e,t=Lr,n=Yo){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(Js(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Iv({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:Mv.defaults({baseUrl:Nv(t)})}),i={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,i),{success:!0,username:r.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?Dv(o.message):"Token refresh failed"}}}async function Wg(e,t=Lr,n=Yo){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!vr(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await qg(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var Vg=f(()=>{"use strict";Zs();Ru()});import{execFile as Gv}from"child_process";function Su(e){return new Promise(t=>{let n=["auth","token"];e&&n.push("--hostname",e);let r=process.env.PATH??"",o=new Set(r.split(":")),i=Hv.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Gv("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Hv,Pu=f(()=>{"use strict";Hv=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});import{resolveEnvToken as Qv}from"@octocodeai/config";function Kg(e){xu=e}function jv(){if(!xu)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return xu}async function na(e){let t=e?.hostname??Lr,n=e?.clientId??Yo,r=e?.getGhCliToken??Su,o=Qv();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await jv().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
10
+ `)}return null}var xu,Yg=f(()=>{"use strict";Pu();Ru();xu=null});async function Xg(e){let t=fn(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=ta();return r.credentials[t]=n,$g(r),gu(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Cu(e="github.com",t){let n=fn(e);if(!t?.bypassCache){let i=Lg(n);if(i!==void 0)return i}let o=ta().credentials[n]||null;return _g(n,o),o}async function Jg(e,t){let n=await Cu(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Xg(n),!0):!1}async function Zg(e,t){return Wg({getCredentials:Cu,updateToken:Jg},e,t)}var wu=f(()=>{"use strict";Fg();Ug();Vg();Yg();Zs();Kg({getTokenWithRefresh:Zg})});var ey=f(()=>{"use strict";wu();Pu()});import ra from"node:os";import V$ from"node:path";var Uv,qv,Wv,Vv,ty=f(()=>{"use strict";Uv=ra.platform()==="win32",qv=ra.platform()==="darwin",Wv=ra.platform()==="linux",Vv=ra.homedir()});var ny=f(()=>{"use strict";ty()});import{z as X}from"zod";var Kv,Yv,oa,Xv,ia,ry,oy,iy=f(()=>{"use strict";Kv=X.object({rawChars:X.number(),responseChars:X.number(),savedChars:X.number(),calls:X.number()}),Yv=X.object({hits:X.record(X.string(),X.number()).default({}),rateLimits:X.number().default(0)}),oa=X.record(X.string(),X.number()).default({}),Xv=X.object({toolCalls:X.number(),errors:X.number(),rateLimits:X.number(),rateLimitsByProvider:oa,rawChars:X.number(),responseChars:X.number(),savedChars:X.number(),charSavingsCalls:X.number(),githubCacheHits:X.number(),githubCacheRateLimits:X.number(),packageRegistryFailures:X.number().default(0),packageRegistryFailuresByRegistry:oa}),ia=X.object({toolCalls:X.number(),errors:X.number(),rateLimits:X.number(),rateLimitsByProvider:oa,charsSavedByTool:X.record(X.string(),Kv).default({}),githubCacheHits:Yv.default({hits:{},rateLimits:0}),packageRegistryFailures:oa,totalUsage:Xv.optional()}),ry=X.object({version:X.literal(1),sessionId:X.string(),createdAt:X.string(),lastActiveAt:X.string(),stats:ia.optional()}),oy=X.object({version:X.literal(1),stats:ia})});function sy(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Jv(e){let t=e.charsSavedByTool??{},n=e.githubCacheHits??{hits:{},rateLimits:0},r=e.rateLimitsByProvider??{},o=e.packageRegistryFailures??{},i=Object.values(t).reduce((s,a)=>({rawChars:s.rawChars+a.rawChars,responseChars:s.responseChars+a.responseChars,savedChars:s.savedChars+a.savedChars,charSavingsCalls:s.charSavingsCalls+a.calls}),{rawChars:0,responseChars:0,savedChars:0,charSavingsCalls:0});return{toolCalls:e.toolCalls,errors:e.errors,rateLimits:e.rateLimits,rateLimitsByProvider:r,...i,githubCacheHits:sy(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:sy(o),packageRegistryFailuresByRegistry:o}}function hn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Jv(t)}}function _r(){return hn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var ku=f(()=>{"use strict"});import{existsSync as cy,readFileSync as ly,writeFileSync as Zv,unlinkSync as sU,renameSync as eA}from"node:fs";import{isStatsEnabled as uy}from"@octocodeai/config";function ay(e,t){let n=`${e}.tmp`;Zv(n,JSON.stringify(t,null,2),{mode:384}),eA(n,e)}function tA(e){let t=JSON.parse(e),n=oy.safeParse(t);if(n.success)return hn(n.data.stats);let r=ia.safeParse(t);return r.success?hn(r.data):null}function nA(){if(!cy(Jo))return _r();try{let e=ly(Jo,"utf8");return tA(e)??_r()}catch{return _r()}}function Tu(e){qn(),uy()&&ay(Jo,{version:e.version,stats:hn(e.stats)});let{stats:t,...n}=e;ay(Xo,n)}function dy(){if(!cy(Xo))return null;try{let e=ly(Xo,"utf8"),t=JSON.parse(e),n=ry.safeParse(t);return n.success?{...n.data,stats:uy()?nA():_r()}:null}catch{return null}}var Xo,Jo,sa=f(()=>{"use strict";wu();ea();iy();ku();Xo=Vt.session,Jo=Vt.stats});function oA(){py||(py=!0,my=()=>{aa()},fy=()=>{aa()},hy=()=>{aa()},process.on("exit",my),process.on("SIGINT",fy),process.on("SIGTERM",hy))}function iA(){Eu||(Eu=setInterval(()=>{Zo&&gn&&(Tu(gn),Zo=!1)},rA),Eu.unref())}function gy(){if(gn)return gn;let e=dy();return e&&(gn=e),e}function yy(e){gn=e,Zo=!0,oA(),iA()}function aa(){if(!Ou&&Zo&&gn){Ou=!0;try{Tu(gn),Zo=!1}catch{}finally{Ou=!1}}}var rA,gn,Zo,Eu,py,my,fy,hy,Ou,by=f(()=>{"use strict";sa();rA=6e4,gn=null,Zo=!1,Eu=null,py=!1,my=null,fy=null,hy=null,Ou=!1});import{randomUUID as xU}from"node:crypto";function sA(e){return hn(e)}function aA(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let i=n[r]??{rawChars:0,responseChars:0,savedChars:0,calls:0};n[r]={rawChars:i.rawChars+o.rawChars,responseChars:i.responseChars+o.responseChars,savedChars:i.savedChars+o.savedChars,calls:i.calls+o.calls}}return n}function Ry(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function cA(e,t){if(!t)return e;let n={...e.hits};for(let[r,o]of Object.entries(t.hits??{}))n[r]=(n[r]??0)+o;return{hits:n,rateLimits:e.rateLimits+(t.rateLimits??0)}}function yn(e){let t=gy();if(!t)return{success:!1,session:null};let n=sA(t.stats),r=hn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Ry(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:aA(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:cA(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Ry(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return yy(o),{success:!0,session:o}}function vu(e=1){return yn({rateLimits:e})}function Au(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return yn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function Lu(e,t=1){return yn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function _u(e=1){return yn({githubCacheHits:{hits:{},rateLimits:e}})}var ei=f(()=>{"use strict";sa();ku();by();sa()});var Sy=f(()=>{"use strict";ei();ei();ei();ei()});import{z as xe}from"zod";var lA,Py=f(()=>{"use strict";lA=xe.looseObject({$schema:xe.string().optional(),version:xe.number().int().optional(),github:xe.record(xe.string(),xe.unknown()).optional(),local:xe.record(xe.string(),xe.unknown()).optional(),tools:xe.record(xe.string(),xe.unknown()).optional(),network:xe.record(xe.string(),xe.unknown()).optional(),lsp:xe.record(xe.string(),xe.unknown()).optional(),output:xe.record(xe.string(),xe.unknown()).optional()})});import{setRuntimeSurface as XU,invalidateConfigCache as JU}from"@octocodeai/config";var xy=f(()=>{"use strict";Py()});import{existsSync as uA,readdirSync as dA,lstatSync as pA}from"node:fs";import{join as mA}from"node:path";function ca(e){if(!uA(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=dA(r)}catch{continue}for(let i of o){let s=mA(r,i);try{let a=pA(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var Cy=f(()=>{"use strict"});var At=f(()=>{"use strict";ey();ny();Sy();xy();ea();Cy()});var Wn,la=f(()=>{Wn="17.0.2"});var Fu,ti,ni,hA,bn,Rn,We,gA,ri,yA,u1,ct=f(()=>{"use strict";Fu={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},ti={PROMISES_NOT_ARRAY:{code:"VALIDATION_PROMISES_NOT_ARRAY",message:"promises must be an array"},TIMEOUT_NOT_POSITIVE:{code:"VALIDATION_TIMEOUT_NOT_POSITIVE",message:"timeout must be positive"},CONCURRENCY_NOT_POSITIVE:{code:"VALIDATION_CONCURRENCY_NOT_POSITIVE",message:"concurrency must be positive"}},ni={FETCH_NOT_AVAILABLE:{code:"FETCH_NOT_AVAILABLE",message:"Global fetch is not available in this environment."},FETCH_FAILED_AFTER_RETRIES:{code:"FETCH_FAILED_AFTER_RETRIES",message:(e,t)=>`Failed to fetch after ${e} attempts: ${t}`},FETCH_HTTP_ERROR:{code:"FETCH_HTTP_ERROR",message:(e,t)=>`Failed to fetch (${e} ${t})`}},hA={INVALID_FORMAT:{code:"TOOL_METADATA_INVALID_FORMAT",message:"Invalid tool metadata format from remote source."},INVALID_API_RESPONSE:{code:"TOOL_METADATA_INVALID_API_RESPONSE",message:"Invalid API response structure"}},bn={PATH_IS_DIRECTORY:{code:"FILE_PATH_IS_DIRECTORY",message:e=>`Path is a directory. Use ${e} to list directory contents`},FILE_TOO_LARGE:{code:"FILE_TOO_LARGE",message:(e,t,n)=>`File too large (${e}KB > ${t}KB). Use ${n} to search within the file or use startLine/endLine parameters to get specific sections`},FILE_EMPTY:{code:"FILE_EMPTY",message:"File is empty - no content to display"},BINARY_FILE:{code:"FILE_BINARY",message:"Binary file detected. Cannot display as text - download directly from GitHub"},DECODE_FAILED:{code:"FILE_DECODE_FAILED",message:"Failed to decode file. Encoding may not be supported (expected UTF-8)"},UNSUPPORTED_TYPE:{code:"FILE_UNSUPPORTED_TYPE",message:e=>`Unsupported file type: ${e}`}},Rn={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},We={QUERY_EMPTY:{code:"SEARCH_QUERY_EMPTY",message:"Search query cannot be empty"},NO_VALID_PARAMETERS:{code:"SEARCH_NO_VALID_PARAMETERS",message:"No valid search parameters provided"},PR_REQUIRED_PARAMS:{code:"SEARCH_PR_REQUIRED_PARAMS",message:"Owner, repo, and prNumber are required parameters"},PR_SINGLE_VALUES:{code:"SEARCH_PR_SINGLE_VALUES",message:"Owner and repo must be single values"},PULL_REQUEST_SEARCH_FAILED:{code:"SEARCH_PR_SEARCH_FAILED",message:e=>`Pull request search failed: ${e}`},PULL_REQUEST_LIST_FAILED:{code:"SEARCH_PR_LIST_FAILED",message:e=>`Pull request list failed: ${e}`},PULL_REQUEST_FETCH_FAILED:{code:"SEARCH_PR_FETCH_FAILED",message:(e,t)=>`Failed to fetch pull request #${e}: ${t}`}},gA={NO_TOOLS_REGISTERED:{code:"STARTUP_NO_TOOLS_REGISTERED",message:"No tools were successfully registered"},UNCAUGHT_EXCEPTION:{code:"STARTUP_UNCAUGHT_EXCEPTION",message:e=>`Uncaught exception: ${e}`},UNHANDLED_REJECTION:{code:"STARTUP_UNHANDLED_REJECTION",message:e=>`Unhandled rejection: ${e}`},STARTUP_FAILED:{code:"STARTUP_FAILED",message:e=>`Startup failed: ${e}`}},ri={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},yA={EXECUTION_FAILED:{code:"TOOL_EXECUTION_FAILED",message:(e,t)=>`Tool ${e} execution failed: ${t}`},SECURITY_VALIDATION_FAILED:{code:"TOOL_SECURITY_VALIDATION_FAILED",message:(e,t)=>`Security validation failed for ${e}: ${t}`}},u1={...Fu,...ti,...ni,...hA,...bn,...Rn,...We,...gA,...ri,...yA}});import{getConfigSync as wy,invalidateConfigCache as f1}from"@octocodeai/config";import{maskSensitiveData as bA}from"@octocodeai/octocode-engine/mask";async function ky(){try{let e=await RA({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:SA.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Ty(){if(ii!==null)return;if(oi!==null)return oi;let e=(async()=>{let t=wy(),n=await ky();ii={version:Wn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();oi=e;try{await e}catch(t){throw oi===e&&(ii=null,oi=null),t}}function Iu(){if(!ii){let e=bA(Fu.NOT_INITIALIZED.message);throw new Error(e)}return ii}async function Mu(){return(await ky()).token}function Du(){return"github"}function Nu(){let e=wy().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var ii,oi,RA,SA,si=f(()=>{"use strict";At();la();ct();ii=null,oi=null,RA=na,SA=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});import{createRequire as PA}from"node:module";function ie(){if(ua)return ua;try{return ua=CA(),ua}catch(e){throw new Gu(e)}}var xA,Ey,ua,CA,Gu,D,Ee=f(()=>{"use strict";xA=PA(import.meta.url),Ey="@octocodeai/octocode-engine",CA=()=>xA(Ey),Gu=class extends Error{constructor(n){super(`Failed to load native dependency ${Ey}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return ie().applyContentViewMinification(e,t)},applyMinification(e,t){return ie().applyMinification(e,t)},minifyContent(e,t){return ie().minifyContent(e,t)},minifyContentSync(e,t){return ie().minifyContentSync(e,t)},minifyContentResult(e,t){return ie().minifyContentResult(e,t)},minifyMarkdownCore(e){return ie().minifyMarkdownCore(e)},extractSignatures(e,t){return ie().extractSignatures(e,t)},extractJsSymbols(e,t){return ie().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ie().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ie().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return ie().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ie().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ie().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ie().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ie().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return ie().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return ie().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ie().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ie().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ie().parseRipgrepJson(e,t)},searchRipgrep(e){return ie().searchRipgrep(e)},queryFileSystem(e){return ie().queryFileSystem(e)},extractMatchingLines(e,t,n){return ie().extractMatchingLines(e,t,n)},filterPatch(e,t){return ie().filterPatch(e,t)},computeLineDiff(e,t){return ie().computeLineDiff(e,t)},charToByteOffset(e,t){return ie().charToByteOffset(e,t)},byteToCharOffset(e,t){return ie().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ie().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ie().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ie().SIGNATURES_ONLY_HINT}}});function Sn(e){(e.provider?yn({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):vu(1)).session&&e.provider==="github"&&_u(1)}function Oy(e){yn({packageRegistryFailures:{[e]:1}})}var da=f(()=>{"use strict";At()});import{Octokit as wA}from"octokit";import{throttling as kA}from"@octokit/plugin-throttling";import{createHash as TA}from"crypto";function Fy(e){return TA("sha256").update(e).digest("hex").substring(0,16)}async function Ge(e){let t=e?.token??await Mu(),n=t?Fy(t):"anon",r=Iu().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}function Iy(e){return Date.now()-e.createdAt>OA}function My(){for(let[e,t]of Kt.entries())Iy(t)&&Kt.delete(e);if(Kt.size>Hu){let e=Kt.size-Hu,t=0;for(let[n]of Kt){if(t>=e)break;Kt.delete(n),t++}}}function AA(){ai||(ai=setInterval(My,vA),typeof ai=="object"&&"unref"in ai&&ai.unref())}function Ly(e,t,n){Sn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function _A(e){let t=Iu(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Wn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:LA(),log:r,...e&&{auth:e}};return new EA(o)}async function oe(e){AA();let t=e?.token??await Mu(),n=t?Fy(t):"ANONYMOUS",r=Kt.get(n);if(r&&!Iy(r))return r.client;Kt.size>=Hu&&My();let o=_A(t??void 0);return Kt.set(n,{client:o,createdAt:Date.now()}),o}async function Ve(e,t,n){let r=`${e}/${t}`,o=ci.get(r);if(o)return o;let i=await oe(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return _y(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),_y(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function _y(e,t){if(ci.size>=FA){let n=ci.keys().next().value;n!==void 0&&ci.delete(n)}ci.set(e,t)}var EA,OA,Hu,vA,Kt,ai,vy,Ay,LA,FA,ci,Ae=f(()=>{"use strict";si();si();la();da();EA=wA.plugin(kA),OA=300*1e3,Hu=50,vA=60*1e3;Kt=new Map,ai=null;vy=3,Ay=60;LA=()=>({onRateLimit:(e,t,n,r)=>(Ly("primary",e,t),r<vy&&e<Ay),onSecondaryRateLimit:(e,t,n,r)=>(Ly("secondary",e,t),r<vy&&e<Ay)});FA=200,ci=new Map});var V,Le,Dy,Qu,ju,pa,Ny=f(()=>{"use strict";V={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},Le={[V.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[V.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[V.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[V.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[V.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[V.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[V.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[V.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[V.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[V.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Dy={401:V.AUTH_REQUIRED,403:V.FORBIDDEN_PERMISSIONS,404:V.NOT_FOUND,422:V.INVALID_REQUEST,502:V.SERVER_UNAVAILABLE,503:V.SERVER_UNAVAILABLE,504:V.SERVER_UNAVAILABLE},Qu={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},ju={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},pa={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as Gy}from"octokit";function Lt(e){if(!(e instanceof Gy)||e.status!==422)return!1;let t=e.response?.data?.errors;return!Array.isArray(t)||t.length===0?!1:t.some(n=>{let r=typeof n?.message=="string"?n.message.toLowerCase():"";return IA.some(o=>r.includes(o))})}function te(e){return e instanceof Gy?MA(e):e instanceof Error?zA(e):{error:typeof e=="string"?e:Le[V.UNKNOWN].message,type:"unknown"}}function MA(e){let{status:t,message:n,response:r}=e;if(t===403)return NA(n,r);if(t===429)return DA(n,r);let o=Dy[t];return o?BA(o,t):Fr(V.UNKNOWN,{error:n||Le[V.UNKNOWN].message,status:t})}function Bu(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function DA(e,t){let n=t?.headers,r=Bu(n,"retry-after"),o=Bu(n,"x-ratelimit-reset"),i=Bu(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+pa.RESET_BUFFER_SECONDS,0):void 0);return Sn({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Fr(V.RATE_LIMIT_PRIMARY,{error:e||Le[V.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Le[V.RATE_LIMIT_PRIMARY].suggestion})}function NA(e,t){let n=t?.headers;if(ju.SECONDARY.test(e))return GA(n);let r=n?.["x-ratelimit-remaining"],o=jA(t);return r!==void 0&&String(r)==="0"||o?HA(n):QA(n)}function GA(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?pa.SECONDARY_FALLBACK_SECONDS:t;return Sn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Fr(V.RATE_LIMIT_SECONDARY,{error:Le[V.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Le[V.RATE_LIMIT_SECONDARY].suggestion})}function HA(e){let t=e?.["x-ratelimit-reset"],n=t?parseInt(String(t),10):NaN,r=isNaN(n)?null:new Date(n*1e3),o=r?Math.max(Math.ceil((r.getTime()-Date.now())/1e3)+pa.RESET_BUFFER_SECONDS,0):void 0,i=r?Le[V.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Le[V.RATE_LIMIT_PRIMARY].messageWithoutTime;return Sn({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Fr(V.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Le[V.RATE_LIMIT_PRIMARY].suggestion})}function QA(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Le[V.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=$A(String(t),String(n))),Fr(V.FORBIDDEN_PERMISSIONS,{error:Le[V.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function jA(e){return e?.data?.errors?.some(n=>n.type===ju.GRAPHQL_TYPE)??!1}function BA(e,t){let n=Le[e];return Fr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function zA(e){return Qu.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Le[V.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Le[V.NETWORK_CONNECTION_FAILED].suggestion}:Qu.TIMEOUT.some(t=>e.message.includes(t))?{error:Le[V.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Le[V.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Fr(e,t){return{type:"http",...t}}function $A(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?Le[V.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Le[V.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var IA,it=f(()=>{"use strict";Ny();da();IA=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function Hy(e){return`user:${e}`}function zu(e){return e.startsWith('"')||qA.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var UA,qA,Yt,li=f(()=>{"use strict";UA=/[@/]/,qA=/^[A-Za-z0-9_-]+$/;Yt=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(Hy(r))});return this}addDateFilters(t){return Object.entries({created:"created",updated:"updated","author-date":"author-date","committer-date":"committer-date","merged-at":"merged",closed:"closed"}).forEach(([r,o])=>{let i=t[r];i&&this.queryParts.push(`${o}:${i}`)}),this}addArrayFilter(t,n,r=!1){return t&&t!==null&&(Array.isArray(t)?t:[t]).forEach(i=>{let s=r?`"${i}"`:i;this.queryParts.push(`${n}:${s}`)}),this}addBooleanFilter(t,n,r){return t===!0?this.queryParts.push(n):t===!1&&this.queryParts.push(r),this}addSimpleFilter(t,n){return t!=null&&this.queryParts.push(`${n}:${t}`),this}addQuotedFilter(t,n){if(t!=null){let o=UA.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}}});function qu(e){return new $u().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function Wu(e){return new Uu().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var WA,$u,Uu,Qy=f(()=>{"use strict";li();WA=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,$u=class extends Yt{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(zu))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(WA):null;return o&&(r=o[1],n=n.slice(0,o.index)||void 0),this.addSimpleFilter(r,"filename"),this.addSimpleFilter(t.extension,"extension"),this.addQuotedFilter(n,"path"),t.language&&this.queryParts.push(`language:${t.language}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="file"?this.queryParts.push("in:file"):r==="path"&&this.queryParts.push("in:path")}),this}},Uu=class extends Yt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(zu)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}}});function Ku(e){return new Vu().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Yu(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Vu,jy=f(()=>{"use strict";li();Vu=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});function Ju(e){return new Xu().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Zu(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Xu,By=f(()=>{"use strict";li();Xu=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}}});var Ir=f(()=>{"use strict";li();Qy();jy();By()});import VA from"crypto";function XA(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t=e,n=!1,r={};for(let o of Object.keys(t)){if(YA.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Oe(e,t,n){let r=ed(XA(t)),o=n?`${n}:${r}`:r,i=VA.createHash("sha256").update(o).digest("hex");return`${KA}-${e}:${i}`}function ed(e,t=new WeakSet){return e===null?"null":e===void 0?"undefined":typeof e!="object"?String(e):t.has(e)?'"[Circular]"':(t.add(e),Array.isArray(e)?`[${e.map(o=>ed(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${ed(i,t)}`}).join(",")}}`)}var KA,YA,zy=f(()=>{"use strict";KA="v2",YA=new Set([])});import JA from"node-cache";function eL(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function tL(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function ui(e){let t=eL(e);if(!(!t||!tL(t)))try{Lu(t,1)}catch{}}function ma(){let e=Date.now();for(let[t,n]of wt.entries())e-n.startedAt>ZA&&wt.delete(t)}function di(e){return $y[e]||$y.default}function pi(e,t,n){try{return Ct.set(e,t,n),lt.sets++,lt.totalKeys=Ct.keys().length,!0}catch{try{let r=Ct.keys();for(let o of r)Ct.get(o);return Ct.set(e,t,n),lt.sets++,lt.totalKeys=Ct.keys().length,!0}catch{return!1}}}var ZA,Ct,lt,$y,wt,fa=f(()=>{"use strict";At();ZA=300*1e3,Ct=new JA({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),lt={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},$y={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},wt=new Map});async function He(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Ct.get(e);if(i!==void 0)return lt.hits++,ui(e),i}catch{}ma();let r=wt.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||lt.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=di(l)}pi(e,i,a)}return i}finally{wt.delete(e)}})();return wt.set(e,{promise:o,startedAt:Date.now()}),o}var Uy=f(()=>{"use strict";fa()});import nL from"node-cache";async function ha(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Ct.get(e);if(i!==void 0)return lt.hits++,ui(e),i}catch{}ma();let r=wt.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:td.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){lt.hits++,ui(e);let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=di(u)}return pi(e,i.data,c),i.data}if(n.forceRefresh||lt.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=di(u)}pi(e,s.value,c),td.set(e,{data:s.value,etag:s.etag})}return s.value}finally{wt.delete(e)}})();return wt.set(e,{promise:o,startedAt:Date.now()}),o}var td,nd=f(()=>{"use strict";fa();td=new nL({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1})});var qy=f(()=>{"use strict";fa();nd()});var ut=f(()=>{"use strict";zy();Uy();nd();qy()});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as fq,DISCOVERY_IGNORED_FILE_NAMES as hq,DISCOVERY_IGNORED_FOLDER_NAMES as gq,getDiscoveryExtension as Wy,shouldIgnoreDiscoveryDir as mi,shouldIgnoreDiscoveryFile as Mr}from"@octocodeai/octocode-engine/security";var fi=f(()=>{"use strict"});function j(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Ky(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function W(e,t){let n=typeof t=="number"?Ky(t):j(t);if(n===void 0)return e;try{Object.defineProperty(e,Vy,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function le(e){if(!(typeof e!="object"||e===null))return Ky(e[Vy])}var Vy,ue=f(()=>{"use strict";Vy=Symbol.for("octocode.rawResponseChars")});function hi(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function Dr(e){let t=hi(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}var Nr=f(()=>{"use strict"});import{ContentSanitizer as rL}from"@octocodeai/octocode-engine/contentSanitizer";async function Xy(e,t,n){let r=await Ge(t),o=Oe("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await He(o,async()=>await oL(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function oL(e,t){try{let n=await oe(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(b=>b&&b.trim()).length===0)return{error:We.QUERY_EMPTY.message,type:"http",status:400};let r=qu(e);if(!r.trim())return{error:We.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Yy,100),i=e.page||1,s={q:r,per_page:o,page:i,headers:{Accept:"application/vnd.github.v3.text-match+json"}},a=await n.rest.search.code(s),c=await iL(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),h=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:h,...h?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:hi(a.headers),rawResponseChars:j(a.data)}}catch(n){if(Lt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Yy,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return te(n)}}async function iL(e,t){let n=sL(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Mr(p.path)),c=0,l=0,u=await Promise.allSettled(a.map(async p=>{s.add(p.path);let h=[],g=await Promise.allSettled((p.text_matches||[]).map(async E=>{let T=E.fragment,_=rL.sanitizeContent(T||"",p.path);T=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(w=>r.add(`${p.path}: ${w}`));try{let w=await D.minifyContent(T||"",p.path);T=w.content,w.failed?o=!0:w.type!=="failed"&&(h.push(w.type),i.push(w.type))}catch{o=!0}return{context:T||"",positions:E.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),y=g.filter(E=>E.status==="fulfilled").map(E=>E.value),b=g.filter(E=>E.status==="rejected").length;b>0&&(l+=b);let S=p,C=Array.from(new Set(h));return{path:p.path,matches:y,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...C.length>0&&{minificationType:C.join(",")}}})),d=u.filter(p=>p.status==="fulfilled").map(p=>p.value);c=u.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function sL(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var Yy,Jy=f(()=>{"use strict";Ee();Ae();it();Ir();ut();fi();ct();ue();Nr();ae();Yy=30});function eb(e){let t={},n=e.license;n?.spdx_id&&n.spdx_id!=="NOASSERTION"&&(t.license=n.spdx_id);let r=e.homepage;return r&&(t.homepage=r),t}async function tb(e,t,n){let r=await Ge(t),o=e,i=Oe("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await He(i,async()=>await cL(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function aL(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){if(p?.status!==404)return te(p);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return te(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),y=g[0]||"",b=g[1]||"";return{owner:y,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...eb(p)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:m,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:j(i)}}async function cL(e,t){try{let n=await oe(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await aL({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=Wu(e);if(!i.trim())return{error:We.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Zy,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let E=S.full_name.split("/"),T=E[0]||"",_=E[1]||"";return{owner:T,repo:_,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...eb(S)}}),m=u.data.total_count,p=Math.min(m,1e3),h=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,h)),y=g<h,b=Math.min(p,h*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:h,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:y,...y?{nextPage:g+1}:{}}},status:200,headers:hi(u.headers),rawResponseChars:j(u.data)}}catch(n){if(Lt(n)){let r=Math.min(e.limit||Zy,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return te(n)}}var Zy,nb=f(()=>{"use strict";Ae();it();Ir();ut();ct();ue();Nr();ae();Zy=30});function _t(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var Gr=f(()=>{"use strict"});function _e(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function lL(e){if(e.rateLimitRemaining===void 0&&e.retryAfter===void 0&&e.rateLimitReset===void 0)return;let t=e.rateLimitReset,n=t&&!isNaN(t)?Math.floor(t/1e3):Math.floor(Date.now()/1e3)+(e.retryAfter??3600);return{remaining:e.rateLimitRemaining??0,reset:n,retryAfter:e.retryAfter}}function Xt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:lL(e)}}function ga(e){return uL(e)?Xt({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function uL(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||dL(n)}function dL(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var Ft=f(()=>{"use strict"});function gi(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}var rd=f(()=>{"use strict"});function pL(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...gi(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function mL(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...gi(e.pagination)},nonExistentScope:e.nonExistentScope}}async function rb(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await Xy(s,t);return _t(a)?Xt(a):a.data?{data:pL(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function ob(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await tb(n,t);return"error"in r?ga(r)??{error:"Unknown GitHub API error",status:500,provider:"github"}:!("data"in r)||!r.data?{error:"No data returned from GitHub API",status:500,provider:"github"}:{data:mL(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??j(r.data)}}var ib=f(()=>{"use strict";Jy();nb();Gr();ue();Ft();Ft();rd()});import{completeMetadata as od}from"@octocodeai/octocode-core";var v,sb=f(()=>{"use strict";v=new Proxy({},{get(e,t){return od.toolNames[t]},ownKeys(){return Object.keys(od.toolNames)},getOwnPropertyDescriptor(e,t){let n=od.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as id}from"@octocodeai/octocode-core";function lb(e=id){if(sd&&e===id)return sd;let t=e,n=t.tools?.localFindFiles;n?.description&&ab.test(n.description)&&(t={...t,tools:{...t.tools,localFindFiles:{...n,description:n.description.replace(ab,hL)}}});let r=t.tools?.ghHistoryResearch;return r?.description&&cb.test(r.description)&&(t={...t,tools:{...t.tools,ghHistoryResearch:{...r,description:r.description.replace(cb,gL)}}}),e===id&&(sd=t),t}var ab,hL,cb,gL,sd,ub=f(()=>{"use strict";ab=/Default excludeDir skips common generated\/vendor dirs; pass \[\] to search all\./,hL='Nothing is excluded by default \u2014 pass excludeDir (e.g. ["node_modules","dist","coverage"]) to prune build/vendor dirs.',cb=/type:"prs" searches PRs; add prNumber to read selected content\. type:"commits" reads owner\/repo\/path history\./,gL='type:"prs" searches PRs; add prNumber to read selected content. type:"commits" reads owner/repo/path history. type:"issues" searches or reads GitHub issues; add issueNumber to read a specific issue (body + comments). type:"releases" lists repo releases.',sd=null});var ad,db=f(()=>{"use strict";ub();ad=new Proxy({},{get(e,t){return lb().tools[t]?.description??""}})});import{completeMetadata as yL}from"@octocodeai/octocode-core";function cd(e){return Object.prototype.hasOwnProperty.call(yL.tools,e)}var pb=f(()=>{"use strict"});import{completeMetadata as bL}from"@octocodeai/octocode-core";function ld(){return bL.baseSchema}var RL,mb=f(()=>{"use strict";RL=new Proxy({},{get(e,t){return ld()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(ld())]))},getOwnPropertyDescriptor(e,t){let n=ld();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var pe=f(()=>{"use strict";sb();db();pb();mb()});function ud(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function dd(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(p=>p.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>l.push(p.path)),l.length===0&&d.length>=3&&c.filter(h=>{let g=h.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(h=>l.push(h.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var fb=f(()=>{"use strict"});import{RequestError as pd}from"octokit";async function SL(e,t,n,r,o,i,s,a){let c=await Ve(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=te(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await dd(e,r,o,i,s||c);return m.length>0&&(u.hints=[...u.hints||[],...ud(i,m)]),{...u,...d&&{scopesSuggestion:d}}}async function PL(e,t,n,r,o,i){let s=te(t),a=await dd(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...ud(o,a)]),s}async function hb(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:bn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:bn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:bn.DECODE_FAILED.message,type:"unknown",status:422}}}async function gb(e,t,n,r,o){try{let i=await e.rest.git.getBlob({owner:t,repo:n,file_sha:r}),{content:s,encoding:a}=i.data;return a==="base64"?hb(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return te(i)}}async function xL(e,t,n,r,o,i){try{let s=r.split("/").slice(0,-1).join("/"),a=r.split("/").pop();if(!a)return{error:`Cannot determine file name from path: ${r}`,type:"unknown",status:400};let c=o||await Ve(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(m=>m.name===a&&m.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await gb(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return te(s)}}async function yi(e,t,n={}){try{let r=await oe(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(p){if(p instanceof pd&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof pd&&p.status===404)if(a){let h=await SL(r,p,c,o,i,s,a,t);if("result"in h)l=h.result,u=h.actualBranch;else return h}else return await PL(r,p,o,i,s,a);else{if(p instanceof pd&&p.status===413)return await xL(r,o,i,s,a||u,t);throw p}}let d=l.data,m=Dr(l.headers);if(Array.isArray(d))return{error:bn.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",h=d.size??0,g;if(p.length>0)g=await hb(p,s);else if(h>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await gb(r,o,i,d.sha,s);else return{error:bn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!u&&!a)try{u=await Ve(o,i,t)}catch{}return{data:{rawContent:g.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:j(d),...m?{etag:m}:{}}}return{error:bn.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return te(r)}}var yb=f(()=>{"use strict";Ae();it();pe();ct();ue();Nr();fb()});var md=f(()=>{"use strict";yb()});function bi(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function It(e){return bi(e).length}var Hr=f(()=>{"use strict"});function ya(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
11
+ `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var fd=f(()=>{"use strict";Ee()});function wL(e){return CL.test(e.split(/[?#]/,1)[0]??e)}function bb(e,t){return wL(t)?TL(kL(e)):null}function ba(e,t){let n=bb(e,t);if(n===null||n.length===0)return null;let r=[];return Sb(n,r),r.join(`
12
+ `)}function Rb(e,t){let n=bb(e,t);return n===null?null:n.map(Pb)}function kL(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function TL(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n[n.length-1].level>=r.level;)n.pop();let o=n[n.length-1];o?o.children.push(r):t.push(r),n.push(r)}return t}function Sb(e,t){for(let n of e){let r=String(n.line).padStart(4," "),o=" ".repeat(Math.max(0,n.level-1));t.push(`${r}| ${o}${"#".repeat(n.level)} ${n.text}`),Sb(n.children,t)}}function Pb(e){let t=`${"#".repeat(e.level)} ${e.text}`;return{name:t,kind:"markdownHeading",range:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},selectionRange:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},children:e.children.map(Pb)}}var CL,Ra=f(()=>{"use strict";CL=/\.(?:md|markdown|mdx)$/i});import{getConfigSync as EL,DEFAULT_OUTPUT_CONFIG as OL}from"@octocodeai/config";function Vn(){try{return EL().output.pagination.defaultCharLength}catch{return OL.pagination.defaultCharLength}}var Sa=f(()=>{"use strict"});function hd(e,t){return D.byteToCharOffset(e,t)}function xb(e,t){return D.charToByteOffset(e,t)}function Cb(e){return D.charToByteOffset(e,e.length)}function gd(e,t,n,r){return D.sliceContent(e,t,n,r)}var wb=f(()=>{"use strict";Ee()});function Pa(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Cb(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,m,p,h,g;if(o==="bytes"){let y=Math.min(t,s),b=Math.min(y+n,s);d=hd(e,y),m=hd(e,b),m<i&&xb(e,m)<b&&(m+=1);let S=gd(e,d,m-d);c=S.text,d=S.charOffset,m=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,p=u<s;let C=r.actualOffset??y;h=Math.floor(C/a)+1,g=Math.max(h,Math.ceil(s/a))}else{let y=gd(e,t,n);c=y.text,d=y.charOffset,m=y.charOffset+y.charLength,l=y.byteOffset,u=y.byteOffset+y.byteLength,p=m<i;let b=r.actualOffset??d;h=Math.floor(b/a)+1,g=Math.max(h,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:p?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:h,totalPages:g}}function yd(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}var bd=f(()=>{"use strict";wb()});function LL(e){return e&&e.trim().length>0?e:AL}async function kb(e,t){return(await D.getSemanticBoundaryOffsets(e,LL(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function _L(e,t){let n=e.indexOf(`
13
+ `,t);return n===-1?void 0:n+1}function xa(e){let t=e.trimEnd().split(`
14
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function Ca(e,t,n){let r=_L(e,Math.max(0,t));return r===void 0?void 0:(await kb(e,n)).find(i=>i>=r&&i>t)}async function wa(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=await kb(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=vL?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var vL,AL,Rd=f(()=>{"use strict";Ee();vL=8e3,AL="__octocode_generic__.unknown"});function IL(){let e=Vn();return Math.min(e,8e3)}async function Sd(e,t,n){let r=e.content??"",o=n??IL();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await wa(r,t,o,i),c=Pa(r,t,s,{pageSize:o}),l;if(c.hasMore&&a==="char-limit"&&xa(c.paginatedContent)){let u=c.charOffset+c.charLength;l=await Ca(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function Pd(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}var Tb=f(()=>{"use strict";Sa();ae();bd();Rd()});import{ContentSanitizer as xd}from"@octocodeai/octocode-engine/contentSanitizer";function Ri(e,t){return{sourceChars:e,sourceBytes:t}}async function Eb(e,t,n,r,o,i,s,a,c=5,l,u,d,m="standard"){let p=e.length,h=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",y=g?"standard":"none",b;if(m==="symbols"){let K=D.extractSignatures(e,o);if(K===null){let I=ba(e,o);if(I!==null){let ye=xd.sanitizeContent(I,o),ke=[D.SIGNATURES_ONLY_HINT];return ye.hasSecrets&&ke.push(`Secrets detected and redacted: ${ye.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ye.content,contentView:"symbols",branch:r,totalLines:It(e),...Ri(p,h),isPartial:!1,signaturesExtracted:!0,hints:ke}}b=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(K!==null){let I=xd.sanitizeContent(K,o),ye=D.applyContentViewMinification(I.content,o),ke=[D.SIGNATURES_ONLY_HINT];return l&&ke.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),I.hasSecrets&&ke.push(`Secrets detected and redacted: ${I.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ye,contentView:"symbols",branch:r,totalLines:It(e),...Ri(p,h),isPartial:!1,signaturesExtracted:!0,hints:ke}}}let S=new Set,C=e,E=C.split(`
15
+ `),T=It(C),_=e,w,G,M=!1,A;if(i)_=e;else if(l){let K=d===!0,I;try{I=ya(E,l,c,u??!1,K)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:T,...Ri(p,h),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(I.matchCount===0){let vs=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${K?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${K?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:T,...Ri(p,h),matchNotFound:!0,searchedFor:l,hints:vs}}_=I.lines.join(`
16
+ `);let ye=I.matchRanges[0],ke=I.matchRanges[I.matchRanges.length-1];s=ye.start,a=ke.end,w=ye.start,G=ke.end,M=!0,I.matchRanges.length>1&&(A=I.matchRanges);let on=I.matchingLines.slice(0,5).join(", "),mo=I.matchingLines.length>5?` and ${I.matchingLines.length-5} more`:"";S.add(I.matchCount>1?`Found ${I.matchCount} occurrences of "${l}" on lines ${on}${mo} \u2014 all shown as ${I.matchRanges.length} slice${I.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${I.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let K=s||1,I=a||T;if(K<1||K>T)_=e,S.add(`Requested startLine ${K} is out of range for this ${T}-line file \u2014 returning the full file instead of a range.`);else if(I<K)_=e,S.add(`Requested range startLine=${K}, endLine=${I} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let ye=Math.max(1,K),ke=Math.min(T,I),on=E.slice(ye-1,ke);w=ye,G=ke,M=!0,_=on.join(`
17
+ `),I>T&&S.add(`Requested endLine ${I} adjusted to ${T} (file end)`)}}let q=xd.sanitizeContent(_,o);if(_=g?D.applyContentViewMinification(q.content,o):q.content,q.hasSecrets&&S.add(`Secrets detected and redacted: ${q.secretsDetected.join(", ")}`),q.warnings.length>0&&q.warnings.forEach(K=>S.add(K)),T>2e3&&m!=="symbols"&&!l&&!s&&!a&&!i){let K=Math.max(1,T-200);S.add(`Large file (${T} lines) \u2014 minify:"symbols" for an export index, or startLine=${K} for the tail.`)}let H=Array.from(S);return{owner:t,repo:n,path:o,content:_,contentView:y,branch:r,totalLines:T,...Ri(p,h),...M&&{startLine:w,endLine:G,isPartial:M},...A&&{matchRanges:A},...H.length>0&&{matchLocations:H},...(H.length>0||b)&&{warnings:[...b?[b]:[],...H]}}}var Ob=f(()=>{"use strict";Ee();Hr();fd();Ra();Tb()});async function vb(e,t,n){let r=await Ge(t),o=Oe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await ha(o,async({ifNoneMatch:g})=>{let y=await yi(e,t,{ifNoneMatch:g}),{etag:b,notModified:S,...C}=y;return{value:C,etag:b,notModified:S}},{shouldCache:g=>"data"in g&&!g.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await Eb(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...l}=a,u=e.charOffset??0,d=e.charLength,m=e.fullContent===!0&&u===0&&d===void 0,p=c||m?l:await Sd(l,u,d),h=(e.charOffset??0)>0;if(!e.noTimestamp&&!h)try{let g=await oe(t),y=await He(Oe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>Pd(g,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});y&&(p.lastModified=y.lastModified,p.lastModifiedBy=y.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:i.rawResponseChars}}var Ab=f(()=>{"use strict";Ae();ut();md();Ob()});function ML(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:DL(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function DL(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function Lb(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await vb(i,t);if(_t(s))return Xt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:ML(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s.data),...a?.length?{hints:a}:{}}}var _b=f(()=>{"use strict";Ab();Gr();ue();Ft();Ft()});function Si(e,t=HL){let n=e?bi(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Fb(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function Ib(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:GL}):""}var GL,HL,ka=f(()=>{"use strict";Ee();Hr();GL=2,HL=20});import{ContentSanitizer as Mb}from"@octocodeai/octocode-engine/contentSanitizer";function Cd(e){let t=Mb.sanitizeContent(e.title??""),n=e.body?Mb.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function Nb(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function Qr(e,t={}){let n=t.charOffset??0,r=t.charLength??QL,o=t.charLength??jL,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=Nb(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((h,g)=>{let y=h.commentType==="review_inline"?0:1,b=g.commentType==="review_inline"?0:1;return y-b}),c=a.filter(h=>h.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Db),d=u.map(h=>{let g=Nb(h.body,n,o,!t.includeFullCommentDetails);return{...h,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>u.length||d.some(h=>"body_pagination"in h)),p=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...m?[`PR comments are paginated/summarized to ${Db} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(h=>({id:0,name:h,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((h,g)=>h+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((h,g)=>h+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(h=>({filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,patch:h.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function Pi(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function xi(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?Fb(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?Ib(a.patch):a.patch}))}var QL,jL,Db,jr=f(()=>{"use strict";ka();Ee();Sa();QL=Vn(),jL=Math.round(Vn()/4),Db=3});function Br(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Gb(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Ta(e){let t=Gb(e);return t?t.discussion!==!1:!1}function Ea(e){let t=Gb(e);return t?t.reviewInline!==!1:!1}function Oa(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function va(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function wd(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:Br(e)||Ta(e)||Ea(e)||Oa(e)||va(e)}function kd(e){return!!e.content?.comments?.includeBots}function Aa(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
25
18
 
26
- `).trim()}async function Bh(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=B(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!Qh(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=D.minifyMarkdownCore(Sl(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:Rl.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"discussion"}}),p=[];return u>0&&p.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:U([],0)}}}async function $h(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Pl(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return U(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Rl.sanitizeContent(D.minifyMarkdownCore(Sl(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return U([],0)}}async function jh(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=B(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!Qh(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=D.minifyMarkdownCore(Sl(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:Rl.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"review_inline",path:f.path,line:f.line??f.original_line??void 0,...f.in_reply_to_id!=null?{in_reply_to_id:f.in_reply_to_id}:{}}}),p=[];return u>0&&p.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:U([],0)}}}async function Uh(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=bl(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=fo(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=B(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,ks(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),ks(t))){let p=await qh(l,u,e.number);p&&(s+=me(p)??0,p.files=ws(p.files,t),o.file_changes=p)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=Dh(t),c=Nh(t);if(a||c){let{owner:l,repo:u}=fo(t);if(l&&u){let d=zh(t),p=()=>Promise.resolve({comments:U([],0)}),[{comments:f,note:m},{comments:h,note:b}]=await Promise.all([a?Bh(n,l,u,e.number,d):p(),c?jh(n,l,u,e.number,d):p()]);o.comments=[...f,...h],s+=(me(f)??0)+(me(h)??0);let x=[m,b].filter(S=>typeof S=="string");x.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...x])}}if(Hh(t))try{let{owner:l,repo:u}=fo(t);if(l&&u){let d=await $h(n,l,u,e.number);s+=me(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(Gh(t))try{let{owner:l,repo:u}=fo(t);if(l&&u){let d=await Wh(l,u,e.number,t);d&&(s+=me(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return U(o,s)}async function Pl(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=B(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function qh(e,t,n,r){let o=await ge(r),{items:i,rawResponseChars:s}=await Pl(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U({total_count:i.length,files:i},s)}async function Gv(e,t,n,r){let o=await ge(r),{items:i,rawResponseChars:s}=await Pl(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U(i,s)}async function Hv(e,t,n,r){try{let i=await(await ge(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return U(i.data.files||[],i.data)}catch{return null}}async function Wh(e,t,n,r,o){let i=await Gv(e,t,n,o);if(!i)return null;let s=me(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await Promise.all(a.map(async l=>{let u=await Hv(e,t,l.sha,o),d=[];return u&&(s+=me(u)??0,d=ws(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return U(c,s)}async function Ts(e,t,n,r){let{prData:o,sanitizationWarnings:i}=bl(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,ks(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),ks(t))try{let d=await qh(a,c,e.number,r);d&&(s+=me(d)??0,d.files=ws(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=Dh(t),u=Nh(t);if(l||u){let d=zh(t),p=()=>Promise.resolve({comments:U([],0)}),[{comments:f,note:m},{comments:h,note:b}]=await Promise.all([l?Bh(n,a,c,e.number,d):p(),u?jh(n,a,c,e.number,d):p()]);o.comments=[...f,...h],s+=(me(f)??0)+(me(h)??0);let x=[m,b].filter(S=>typeof S=="string");x.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...x])}if(Hh(t))try{let d=await $h(n,a,c,e.number);s+=me(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(Gh(t))try{let d=await Wh(a,c,e.number,t,r);d&&(s+=me(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return U(o,s)}var Nv,Cl=y(()=>{"use strict";Ce();qe();xs();ue();Nv=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function zv(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function Vh(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:Ue.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:Ue.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ge(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Ts(a,e,i,t);return{pull_requests:[po(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:B(s.data)+(me(c)??0)}}catch(i){let s=ae(i);return zv(s,Ue.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var Kh=y(()=>{"use strict";Tt();qe();zt();nn();xs();Cl();ue()});function Yh(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Xh(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Qv(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function Bv(e,t){return We("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},t)}async function Jh(e,t,n){let r=Bv(e,n);return await Ve(r,async()=>await $v(e,t,n),{shouldCache:i=>!i.error})}async function $v(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Vh(e,t);let r=await ge(t);if(!nh(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await jv(r,e);let i=await Qv(r,e),s=th(i);if(!s)return{pull_requests:[],total_count:0,error:Ue.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),p=d.data.items?.filter(E=>!!E.pull_request)||[],f=await Promise.all(p.map(async E=>await Uh(E,i,r))),m=f.reduce((E,w)=>E+(me(w)??0),0),h=f.map(E=>po(E,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,x=Math.min(b,1e3),S=Math.min(Math.ceil(x/c),10),T=Math.min(l,Math.max(1,S)),L=T<S,_=Math.min(x,S*c);return{pull_requests:h,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:T,totalPages:S,perPage:c,totalMatches:x,reportedTotalMatches:b,reachableTotalMatches:_,totalMatchesKind:"reported",totalMatchesCapped:b>x,hasMore:L,...L?{nextPage:T+1}:{}},rawResponseChars:B(d.data)+m}}catch(r){if(Rn(r))return Xh(e);let o=ae(r);return Yh(o,Ue.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function jv(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async p=>await Ts(p,t,e))),c=a.reduce((p,f)=>p+(me(f)??0),0),l=a.map(p=>po(p,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:B(s.data)+c}}catch(n){if(Rn(n))return Xh(t);let r=ae(n);return Yh(r,Ue.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var Zh=y(()=>{"use strict";Se();Tt();qe();zt();ys();nn();ue();xs();Cl();Kh()});function Uv(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function qv(e,t,n=Te){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Uv(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function eg(e,t,n=Te){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Jh(s,t);return a.error?Qt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:qv(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??B(a)}}var tg=y(()=>{"use strict";Zh();ue();Et();Et()});var Pn,Es=y(()=>{"use strict";Pn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function vs(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var wl=y(()=>{"use strict"});function ng(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:F,...v}=e;return v}let r=t.itemsPerPage??Pn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,p=F=>{let v=F;d&&F.startsWith(d)&&(v=F.slice(d.length),v.startsWith("/")&&(v=v.slice(1)));let Q=v.lastIndexOf("/");return Q===-1?".":v.slice(0,Q)},f=F=>{let v=F.lastIndexOf("/");return v===-1?F:F.slice(v+1)};for(let F of l){let v=p(F.path);u[v]||(u[v]={files:[],folders:[]});let Q=f(F.path);F.type==="file"?u[v].files.push(Q):u[v].folders.push(Q)}for(let F of Object.keys(u)){let v=u[F];v&&(v.files.sort(),v.folders.sort())}let m=Object.create(null),h=Object.keys(u).sort((F,v)=>F==="."?-1:v==="."?1:F.localeCompare(v));for(let F of h){let v=u[F];v&&(m[F]=v)}let b=l.filter(F=>F.type==="file").length,x=l.filter(F=>F.type==="dir").length,S=n.filter(F=>F.type==="file").length,T=n.filter(F=>F.type==="dir").length,L=o<s,_={currentPage:o,totalPages:s,hasMore:L,...L?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},E=vs(_,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:x,allFiles:S,allFolders:T}),w,N=e._cachedFileSizeMap;if(N){let F=new Set(l.filter(G=>G.type==="file").map(G=>G.path)),v=e.path==="/"?"":e.path,Q=Object.create(null);for(let[G,K]of Object.entries(N))for(let[j,ve]of Object.entries(K)){let Oe=G==="."?v?`${v}/${j}`:j:v?`${v}/${G}/${j}`:`${G}/${j}`;F.has(Oe)&&(Q[G]||(Q[G]=Object.create(null)),Q[G][j]=ve)}Object.keys(Q).length>0&&(w=Q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:T,truncated:L,filtered:!0,originalCount:i},structure:m,...w!==void 0&&{fileSizeMap:w},...N!==void 0&&{_cachedFileSizeMap:N},pagination:_,hints:E,rawResponseChars:e.rawResponseChars}}var rg=y(()=>{"use strict";Es();wl()});import{RequestError as Vv}from"octokit";function og(e){return e instanceof Vv&&Kv.has(e.status)}function xl(e,t){try{Object.defineProperty(e,ig,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function kl(e){if(typeof e!="object"||e===null)return 0;let t=e[ig];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Tl(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return xl(U([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(m){if(og(m))throw m;return xl(U([],0),1)}let l=B(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(m=>m.type==="file"||m.type==="dir").map(m=>({name:m.name,path:m.path,type:m.type,size:"size"in m?m.size:void 0,download_url:"download_url"in m?m.download_url:void 0,url:m.url,html_url:m.html_url,git_url:m.git_url,sha:m.sha})),p=[...d],f=0;if(i<s){let m=d.filter(b=>b.type==="dir"),h=3;for(let b=0;b<m.length;b+=h){let x=m.slice(b,b+h),S=await Promise.allSettled(x.map(T=>Tl(e,t,n,r,T.path,i+1,s,a)));for(let T of S)if(T.status==="fulfilled"){let L=T.value;l+=me(L)??0,f+=kl(L),p.push(...L)}else{if(og(T.reason))throw T.reason;f+=1}}}return xl(U(p,l),f)}var ig,Kv,sg=y(()=>{"use strict";ue();ig=Symbol.for("octocode.recursiveFetchFailures"),Kv=new Set([401,403,429])});import{RequestError as Yv}from"octokit";async function Xv(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await it(t,n,i),s=a)}catch(c){let l=ae(c);return{error:ir.NOT_FOUND.message(t,n,l.error),status:l.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s,...a!==void 0?{repoDefaultBranch:a}:{}}}catch(c){if(!(c instanceof Yv&&c.status===404)){let u=ae(c);return{error:ir.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let l=ae(c);return{error:ir.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function Jv(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function Zv(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function ag(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function cg(e,t,n){let r=We("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await Ve(r,async()=>await eO({...e,itemsPerPage:e.itemsPerPage??Pn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?ng(o,e):o}async function eO(e,t){try{let n=await ge(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await Xv(n,r,o,c,i,t);if("error"in l)return l;let{data:u,workingBranch:d,repoDefaultBranch:p}=l,f=B(u),m=Array.isArray(u)?u:[u],h=Jv(m),b=0;if(a>1){let re=await Tl(n,r,o,d,c,1,a);b=kl(re),f+=me(re)??0,h=[...h,...re].filter((Sr,Fo,jS)=>jS.findIndex(US=>US.path===Sr.path)===Fo)}let x=h.filter(re=>re.type==="dir"?!ao(re.name):!cr(re.path));x.sort((re,Pt)=>{if(re.type!==Pt.type)return re.type==="dir"?-1:1;let Sr=re.path.split("/").length,Fo=Pt.path.split("/").length;return Sr!==Fo?Sr-Fo:re.path.localeCompare(Pt.path)});let S=e.itemsPerPage??Pn.ENTRIES_PER_PAGE,T=e.page??1,L=x.length,_=Math.max(1,Math.ceil(L/S)),E=(T-1)*S,w=Math.min(E+S,L),N=x.slice(E,w),F=Zv(N,c),v=e.includeSizes===!0?ag(x,c):void 0,Q=v!==void 0?ag(N,c):void 0,G=N.filter(re=>re.type==="file").length,K=N.filter(re=>re.type==="dir").length,j=x.filter(re=>re.type==="file").length,ve=x.filter(re=>re.type==="dir").length,Oe=T<_,Ut={currentPage:T,totalPages:_,hasMore:Oe,...Oe?{nextPage:T+1}:{},entriesPerPage:S,totalEntries:L},qt=vs(Ut,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:G,pageFolders:K,allFiles:j,allFolders:ve});return b>0&&qt.unshift(`Partial tree: ${b} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...p!==void 0&&{defaultBranch:p},path:c||"/",apiSource:!0,summary:{totalFiles:j,totalFolders:ve,truncated:Oe,filtered:!0,originalCount:x.length},structure:F,...Q!==void 0&&{fileSizeMap:Q},...v!==void 0&&{_cachedFileSizeMap:v},pagination:Ut,hints:qt,rawResponseChars:f,_cachedItems:x.map(re=>({path:re.path,type:re.type}))}}catch(n){let r=ae(n);return{error:ir.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var lg=y(()=>{"use strict";Es();qe();zt();nn();wl();co();Tt();ue();rg();sg()});function tO(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function ug(e,t,n=Te){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await cg(i,t);return"error"in s?Ss(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:tO(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??B(s)}}var dg=y(()=>{"use strict";lg();ue();Et();Et()});var pg,fg=y(()=>{"use strict";pg={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var Os,mg=y(()=>{"use strict";hh();Oh();tg();dg();zt();qe();fg();Et();Os=class{type="github";capabilities=pg.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await fh(t,this.authInfo,Te)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await vh(t,this.authInfo,Te)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await mh(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await eg(t,this.authInfo,Te)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await ug(t,this.authInfo,Te)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Te(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return it(n,r,this.authInfo)}handleError(t){let n=ae(t);return Qt(n)}}});import{createHash as rO}from"crypto";function hg(e){return Date.now()-e.createdAt<oO}function iO(){for(let[e,t]of vt.entries())hg(t)||vt.delete(e);if(vt.size>El){let e=[...vt.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=vt.size-El;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&vt.delete(r[0])}}}function sO(e){return e?rO("sha256").update(e).digest("hex").slice(0,16):"default"}function aO(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function cO(e,t){let n=aO(t?.baseUrl||"default"),r=sO(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function vl(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=cO(e,t),r=vt.get(n);if(r&&hg(r))return r.lastAccessedAt=Date.now(),r.provider;r&&vt.delete(n),vt.size>=El&&iO();let o=new Os({...t,type:e}),i=Date.now();return vt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function gg(){try{return vl("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
27
- `),[{provider:"github",ok:!1,error:t}]}}var oO,El,vt,Ol=y(()=>{"use strict";mg();oO=3600*1e3,El=20,vt=new Map});async function yg(e,t={}){if(!Array.isArray(e))throw new Error(Xr.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(Xr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(Xr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Zr.NOT_A_FUNCTION.message(l))));if(r<i.length)return lO(i,r,n,o);let s=i.map((c,l)=>bg(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function bg(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Zr.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function lO(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Zr.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await bg(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Rg=y(()=>{"use strict";Tt()});import{ContentSanitizer as uO}from"@octocodeai/octocode-engine/contentSanitizer";function dO(){try{return gt().output.format}catch{return"yaml"}}function ut(e){if(e==null)return e;if(typeof e=="string")return uO.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>ut(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ut(r);return t}return e}function wn(e,t){let n=Cn(e)??{},r=ut(n),o=dO(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ls(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Ls(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ls(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ls(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ls(n[o],t));return r}function mO(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>pO.has(r))||fO.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Cn(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>Cn(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(mO(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Cn(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var pO,fO,ur=y(()=>{"use strict";Ct();Ce();pO=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]),fO=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});function hO(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function Ll(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Ll(o,t,n+1);return}let r=e;for(let o of Al){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))Sg.has(o)||i&&typeof i=="object"&&Ll(i,t,n+1)}function As(e){let t=[];for(let i of e)Ll(i?.data,t,0);if(t.length===0)return;let n=hO(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return gO(e,r),n}function gO(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(Sg.has(s))continue;let a=i[s];typeof a=="string"?!Al.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function yO(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function bO(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function _s(e){let t=yO(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(RO.has(i))continue;let s=n[i];bO(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var Al,Sg,RO,_l=y(()=>{"use strict";Al=["path","uri"],Sg=new Set(["next","location"]);RO=new Set([...Al,"owner","repo","name","id"])});function wO(e,t,n){if(e<=1)return Pg;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(PO/o),s=Math.max(CO,Math.min(i,Pg));return n?Math.max(s,n):s}async function ce(e,t,n,r){let o=n.concurrency??SO,{results:i,errors:s}=await EO(e,t,o,n.minQueryTimeoutMs);return xO(n,i,s,e,r)}function xO(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(h=>{let b=h.result.status;c[h.queryIndex]={id:Is(h.originalQuery,h.queryIndex),...b!==void 0?{status:b}:{},data:vO(h.result)}}),n.forEach(h=>{let b=r[h.queryIndex];b&&(c[h.queryIndex]={id:Is(b,h.queryIndex),status:"error",data:{error:h.error}})});let l=c.filter(h=>h!==void 0);if(e.finalize){let h=e.finalize({queries:r,results:l,config:e}),b=Cg(h.text,o),x=wg(h.structuredContent,b.pagination);return xg(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:x,isError:h.isError??(l.length>0&&l.every(T=>T.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let h=As(u.results);h&&(u.base=h);let b=_s(u.results);b&&(u.shared=b)}let d=wn(u,a),p=Cg(d,o),f=wg(ut(Cn(u)??{}),p.pagination);return xg(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(h=>h.status==="error")}}function Il(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
28
- `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function kO(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Il(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function TO(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Il(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function Cg(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=Il(e,s,i),c=a<o,l=kO(e,s,i),u=TO(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
19
+ `).trim()}var La=f(()=>{"use strict"});function Kn(e){let t=e.toLowerCase();return t.endsWith("[bot]")||BL.has(t)}var BL,_a=f(()=>{"use strict";BL=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});async function Fa(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=j(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Td(e,t,n,r){let o=await oe(r),{items:i,rawResponseChars:s}=await Fa(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return W({total_count:i.length,files:i},s)}async function zL(e,t,n,r){let o=await oe(r),{items:i,rawResponseChars:s}=await Fa(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return W(i,s)}async function $L(e,t,n,r){try{let i=await(await oe(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return W(i.data.files||[],i.data)}catch{return null}}async function qL(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)break;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function Ed(e,t,n,r,o){let i=await zL(e,t,n,o);if(!i)return null;let s=le(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await qL(a,UL,async l=>{let u=await $L(e,t,l.sha,o),d=[];return u&&(s+=le(u)??0,d=xi(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}});return W(c,s)}var UL,Od=f(()=>{"use strict";Ae();jr();ue();UL=5});import{ContentSanitizer as vd}from"@octocodeai/octocode-engine/contentSanitizer";async function Ad(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=j(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!Kn(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(Aa(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:vd.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return u>0&&m.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:W(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:W([],0)}}}async function Ld(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Fa(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return W(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:vd.sanitizeContent(D.minifyMarkdownCore(Aa(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return W([],0)}}async function _d(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=j(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!Kn(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(Aa(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:vd.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return u>0&&m.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:W(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:W([],0)}}}var Hb=f(()=>{"use strict";Ee();_a();ue();La();Od()});async function Fd(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Cd(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&wd(t))try{let{owner:l,repo:u}=Pi(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=j(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Br(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Br(t))){let m=await Td(l,u,e.number);m&&(s+=le(m)??0,m.files=xi(m.files,t),o.file_changes=m)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=Ta(t),c=Ea(t);if(a||c){let{owner:l,repo:u}=Pi(t);if(l&&u){let d=kd(t),m=()=>Promise.resolve({comments:W([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([a?Ad(n,l,u,e.number,d):m(),c?_d(n,l,u,e.number,d):m()]);o.comments=[...p,...g],s+=(le(p)??0)+(le(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(va(t))try{let{owner:l,repo:u}=Pi(t);if(l&&u){let d=await Ld(n,l,u,e.number);s+=le(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(Oa(t))try{let{owner:l,repo:u}=Pi(t);if(l&&u){let d=await Ed(l,u,e.number,t);d&&(s+=le(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return W(o,s)}async function Ci(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Cd(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Br(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Br(t))try{let d=await Td(a,c,e.number,r);d&&(s+=le(d)??0,d.files=xi(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=Ta(t),u=Ea(t);if(l||u){let d=kd(t),m=()=>Promise.resolve({comments:W([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([l?Ad(n,a,c,e.number,d):m(),u?_d(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(le(p)??0)+(le(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(va(t))try{let d=await Ld(n,a,c,e.number);s+=le(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(Oa(t))try{let d=await Ed(a,c,e.number,t,r);d&&(s+=le(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return W(o,s)}var Qb=f(()=>{"use strict";jr();ue();La();Hb();Od()});var Ia=f(()=>{"use strict";La();Qb()});function WL(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function jb(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:We.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:We.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await oe(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Ci(a,e,i,t);return{pull_requests:[Qr(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:j(s.data)+(le(c)??0)}}catch(i){let s=te(i);return WL(s,We.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var Bb=f(()=>{"use strict";ct();Ae();it();ut();jr();Ia();ue()});function Id(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Md(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function zb(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await Ci(m,t,e))),c=a.reduce((m,p)=>m+(le(p)??0),0),l=a.map(m=>Qr(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:j(s.data)+c}}catch(n){if(Lt(n))return Md(t);let r=te(n);return Id(r,We.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var $b=f(()=>{"use strict";ae();ct();it();ue();jr();Ia()});async function VL(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function KL(e,t,n="anon"){return Oe("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function Ub(e,t,n){let r=await Ge(t),o=KL(e,n,r);return await He(o,async()=>await YL(e,t,n),{shouldCache:s=>!s.error})}async function YL(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await jb(e,t);let r=await oe(t);if(!Yu(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await zb(r,e);let i=await VL(r,e),s=Ku(i);if(!s)return{pull_requests:[],total_count:0,error:We.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),m=d.data.items?.filter(_=>!!_.pull_request)||[],p=await Promise.all(m.map(async _=>await Fd(_,i,r))),h=p.reduce((_,w)=>_+(le(w)??0),0),g=p.map(_=>Qr(_,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),y=d.data.total_count,b=Math.min(y,1e3),S=Math.min(Math.ceil(b/c),10),C=Math.min(l,Math.max(1,S)),E=C<S,T=Math.min(b,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:C,totalPages:S,perPage:c,totalMatches:b,reportedTotalMatches:y,reachableTotalMatches:T,totalMatchesKind:"reported",totalMatchesCapped:y>b,hasMore:E,...E?{nextPage:C+1}:{}},rawResponseChars:j(d.data)+h}}catch(r){if(Lt(r))return Md(e);let o=te(r);return Id(o,We.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var qb=f(()=>{"use strict";ae();ct();Ae();it();Ir();ut();ue();jr();Ia();Bb();$b()});function XL(e,t,n=_e){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...gi(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Wb(e,t,n=_e){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Ub(s,t);return a.error?Xt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:XL(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a)}}var Vb=f(()=>{"use strict";qb();ue();Ft();Ft();rd()});var Pn,wi=f(()=>{"use strict";Pn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function Ma(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Dd=f(()=>{"use strict"});function Kb(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:M,...A}=e;return A}let r=t.itemsPerPage??Pn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,m=M=>{let A=M;d&&M.startsWith(d)&&(A=M.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let q=A.lastIndexOf("/");return q===-1?".":A.slice(0,q)},p=M=>{let A=M.lastIndexOf("/");return A===-1?M:M.slice(A+1)};for(let M of l){let A=m(M.path);u[A]||(u[A]={files:[],folders:[]});let q=p(M.path);M.type==="file"?u[A].files.push(q):u[A].folders.push(q)}for(let M of Object.keys(u)){let A=u[M];A&&(A.files.sort(),A.folders.sort())}let h=Object.create(null),g=Object.keys(u).sort((M,A)=>M==="."?-1:A==="."?1:M.localeCompare(A));for(let M of g){let A=u[M];A&&(h[M]=A)}let y=l.filter(M=>M.type==="file").length,b=l.filter(M=>M.type==="dir").length,S=n.filter(M=>M.type==="file").length,C=n.filter(M=>M.type==="dir").length,E=o<s,T={currentPage:o,totalPages:s,hasMore:E,...E?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=Ma(T,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:y,pageFolders:b,allFiles:S,allFolders:C}),w,G=e._cachedFileSizeMap;if(G){let M=new Set(l.filter(H=>H.type==="file").map(H=>H.path)),A=e.path==="/"?"":e.path,q=Object.create(null);for(let[H,K]of Object.entries(G))for(let[I,ye]of Object.entries(K)){let ke=H==="."?A?`${A}/${I}`:I:A?`${A}/${H}/${I}`:`${H}/${I}`;M.has(ke)&&(q[H]||(q[H]=Object.create(null)),q[H][I]=ye)}Object.keys(q).length>0&&(w=q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:C,truncated:E,filtered:!0,originalCount:i},structure:h,...w!==void 0&&{fileSizeMap:w},...G!==void 0&&{_cachedFileSizeMap:G},pagination:T,hints:_,rawResponseChars:e.rawResponseChars}}var Yb=f(()=>{"use strict";wi();Dd()});import{RequestError as ZL}from"octokit";function Xb(e){return e instanceof ZL&&e_.has(e.status)}function Nd(e,t){try{Object.defineProperty(e,Jb,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function ki(e){if(typeof e!="object"||e===null)return 0;let t=e[Jb];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Ti(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Nd(W([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(h){if(Xb(h))throw h;return Nd(W([],0),1)}let l=j(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(h=>h.type==="file"||h.type==="dir").map(h=>({name:h.name,path:h.path,type:h.type,size:"size"in h?h.size:void 0,download_url:"download_url"in h?h.download_url:void 0,url:h.url,html_url:h.html_url,git_url:h.git_url,sha:h.sha})),m=[...d],p=0;if(i<s){let h=d.filter(y=>y.type==="dir"),g=3;for(let y=0;y<h.length;y+=g){let b=h.slice(y,y+g),S=await Promise.allSettled(b.map(C=>Ti(e,t,n,r,C.path,i+1,s,a)));for(let C of S)if(C.status==="fulfilled"){let E=C.value;l+=le(E)??0,p+=ki(E),m.push(...E)}else{if(Xb(C.reason))throw C.reason;p+=1}}}return Nd(W(m,l),p)}var Jb,e_,Zb=f(()=>{"use strict";ue();Jb=Symbol.for("octocode.recursiveFetchFailures"),e_=new Set([401,403,429])});import{RequestError as t_}from"octokit";function n_(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let l=a.lastIndexOf("/"),u=l===-1?a:a.slice(l+1);i.push({name:u,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function eR(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function tR(e,t){let{data:n}=await e.rest.repos.getBranch({owner:t.owner,repo:t.repo,branch:t.workingBranch}),r=n.commit.commit.tree.sha;if(!r)throw new Error(`Could not resolve tree SHA for ${t.owner}/${t.repo}@${t.workingBranch}`);let o;try{o=await e.rest.git.getTree({owner:t.owner,repo:t.repo,tree_sha:r,recursive:"true",...t.ifNoneMatch?{headers:{"If-None-Match":t.ifNoneMatch}}:{}})}catch(c){if(c instanceof t_&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=Dr(o.headers);return{items:n_(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:j(n)+j(i),...s?{etag:s}:{}}}var nR=f(()=>{"use strict";ue();Nr()});import{RequestError as rR}from"octokit";async function Gd(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Ve(t,n,i),a=c)}catch(l){let u=te(l);return{error:Rn.NOT_FOUND.message(t,n,u.error),status:u.status}}try{let l=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),u=Dr(l.headers);return{data:l.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...u?{etag:u}:{}}}catch(l){if(l instanceof rR&&l.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(l instanceof rR&&l.status===404)){let d=te(l);return{error:Rn.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let u=te(l);return{error:Rn.PATH_NOT_FOUND.message(r,t,n,a),status:u.status}}}function oR(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}var iR=f(()=>{"use strict";it();ct();Ae();Nr()});function r_(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function sR(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}function Da(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:l,includeSizes:u,extraHints:d=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!mi(I.name):!Mr(I.path));m.sort((I,ye)=>{if(I.type!==ye.type)return I.type==="dir"?-1:1;let ke=I.path.split("/").length,on=ye.path.split("/").length;return ke!==on?ke-on:I.path.localeCompare(ye.path)});let p=e.itemsPerPage??Pn.ENTRIES_PER_PAGE,h=e.page??1,g=m.length,y=Math.max(1,Math.ceil(g/p)),b=(h-1)*p,S=Math.min(b+p,g),C=m.slice(b,S),E=r_(C,i),T=u?sR(m,i):void 0,_=T!==void 0?sR(C,i):void 0,w=C.filter(I=>I.type==="file").length,G=C.filter(I=>I.type==="dir").length,M=m.filter(I=>I.type==="file").length,A=m.filter(I=>I.type==="dir").length,q=h<y,H={currentPage:h,totalPages:y,hasMore:q,...q?{nextPage:h+1}:{},entriesPerPage:p,totalEntries:g},K=Ma(H,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:w,pageFolders:G,allFiles:M,allFolders:A});a>0&&K.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let I of d)K.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:M,totalFolders:A,truncated:q,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:E,..._!==void 0&&{fileSizeMap:_},...T!==void 0&&{_cachedFileSizeMap:T},pagination:H,hints:K,rawResponseChars:l,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}var aR=f(()=>{"use strict";wi();Dd();fi()});async function Hd(e,t,n){let r=await Ge(t),o=Oe("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await ha(o,async({ifNoneMatch:s})=>{let a=await o_({...e,itemsPerPage:e.itemsPerPage??Pn.ENTRIES_PER_PAGE,page:e.page??1},t,s);return{value:a.result,etag:a.etag,notModified:a.notModified}},{shouldCache:s=>!("error"in s)});return!("error"in i)&&i.structure?Kb(i,e):i}async function o_(e,t,n){try{let r=await oe(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,l=a.replace(/^\/+|\/+$/g,"");if(c>1&&eR())return await i_(r,e,l,c,t,n);let u=await Gd(r,o,i,l,s,t,c===1?n:void 0);if("error"in u)return{result:u};if(u.notModified)return{result:{error:"not-modified",status:304},etag:u.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:h}=u,g=j(d),y=Array.isArray(d)?d:[d],b=oR(y),S=0;if(c>1){let C=await Ti(r,o,i,m,l,1,c);S=ki(C),g=le(C)??0,b=C}return{result:Da({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:l,depth:c,allItems:b,partialTreeFailures:S,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&h?{etag:h}:{}}}catch(r){let o=te(r);return{result:{error:Rn.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function i_(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,l,u;try{c?l=c:(u=await Ve(s,a,o),l=u)}catch(b){let S=te(b);return{result:{error:Rn.NOT_FOUND.message(s,a,S.error),status:S.status}}}let d;try{d=await tR(e,{owner:s,repo:a,workingBranch:l,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(b){let S=await Gd(e,s,a,n,l,o);if("error"in S)return{result:S};let C=await Ti(e,s,a,S.workingBranch,n,1,r);return{result:Da({owner:s,repo:a,workingBranch:S.workingBranch,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:C,partialTreeFailures:ki(C),incompleteTree:!1,rawResponseChars:le(C)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${b instanceof Error?b.message:String(b)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,h=d.rawResponseChars,g=d.truncated,y=[];if(g){y.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let b=await Ti(e,s,a,l,n,1,r);p=ki(b),h+=le(b)??0,m=[...m,...b].filter((C,E,T)=>T.findIndex(_=>_.path===C.path)===E)}catch{}}return{result:Da({owner:s,repo:a,workingBranch:l,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:h,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:y}),...d.etag&&!g?{etag:d.etag}:{}}}var cR=f(()=>{"use strict";wi();Ae();it();ut();ct();ue();Yb();Zb();nR();iR();aR()});var lR=f(()=>{"use strict";cR()});function s_(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function uR(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Hd(i,t);return"error"in s?ga(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:s_(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s)}}var dR=f(()=>{"use strict";lR();ue();Ft();Ft()});var pR,mR=f(()=>{"use strict";pR={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var Na,fR=f(()=>{"use strict";ib();_b();Vb();dR();it();Ae();mR();Ft();Na=class{type="github";capabilities=pR.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await rb(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Lb(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await ob(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Wb(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await uR(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=_e(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ve(n,r,this.authInfo)}handleError(t){let n=te(t);return Xt(n)}}});import{createHash as c_}from"crypto";function hR(e){return Date.now()-e.createdAt<l_}function u_(){for(let[e,t]of Mt.entries())hR(t)||Mt.delete(e);if(Mt.size>Qd){let e=[...Mt.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Mt.size-Qd;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Mt.delete(r[0])}}}function d_(e){return e?c_("sha256").update(e).digest("hex").slice(0,16):"default"}function p_(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function m_(e,t){let n=p_(t?.baseUrl||"default"),r=d_(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function jd(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=m_(e,t),r=Mt.get(n);if(r&&hR(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Mt.delete(n),Mt.size>=Qd&&u_();let o=new Na({...t,type:e}),i=Date.now();return Mt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function gR(){try{return jd("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
20
+ `),[{provider:"github",ok:!1,error:t}]}}var l_,Qd,Mt,Bd=f(()=>{"use strict";fR();l_=3600*1e3,Qd=20,Mt=new Map});async function yR(e,t={}){if(!Array.isArray(e))throw new Error(ti.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(ti.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(ti.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(ri.NOT_A_FUNCTION.message(l))));if(r<i.length)return f_(i,r,n,o);let s=i.map((c,l)=>bR(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function bR(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(ri.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function f_(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(ri.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await bR(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var RR=f(()=>{"use strict";ct()});function PR(e,t,n){if(e<=1)return SR;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(h_/o),s=Math.max(g_,Math.min(i,SR));return n?Math.max(s,n):s}async function xR(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await yR(s,{timeout:PR(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function Ei(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function Oi(e){let t=new Set;return e.map((n,r)=>{let o=Ei(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}var SR,h_,g_,zd=f(()=>{"use strict";RR();SR=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,h_=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,g_=5e3});import{ContentSanitizer as y_}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as b_}from"@octocodeai/config";function R_(){try{return b_().output.format}catch{return"yaml"}}function dt(e){if(e==null)return e;if(typeof e=="string")return y_.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>dt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=dt(r);return t}return e}function Xn(e,t){let n=Yn(e)??{},r=dt(n),o=R_(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ga(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Ga(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ga(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ga(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ga(n[o],t));return r}function x_(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>S_.has(r))||P_.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Yn(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>Yn(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(x_(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Yn(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var S_,P_,zr=f(()=>{"use strict";Ee();S_=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]),P_=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});function C_(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function $d(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)$d(o,t,n+1);return}let r=e;for(let o of Ud){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))CR.has(o)||i&&typeof i=="object"&&$d(i,t,n+1)}function Ha(e){let t=[];for(let i of e)$d(i?.data,t,0);if(t.length===0)return;let n=C_(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return w_(e,r),n}function w_(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(CR.has(s))continue;let a=i[s];typeof a=="string"?!Ud.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function k_(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function T_(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function Qa(e){let t=k_(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(E_.has(i))continue;let s=n[i];T_(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var Ud,CR,E_,qd=f(()=>{"use strict";Ud=["path","uri"],CR=new Set(["next","location"]);E_=new Set([...Ud,"owner","repo","name","id"])});function Wd(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
21
+ `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function O_(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Wd(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function v_(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Wd(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function Vd(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=Wd(e,s,i),c=a<o,l=O_(e,s,i),u=v_(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
29
22
  `:`# Response page ${l}/${u}.
30
- `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function wg(e,t){return t?{...e,responsePagination:t}:e}function xg(e,t,n,r){let o=t.reduce((i,s)=>i+(me(s.result)??B(s.result)),0)+n.reduce((i,s)=>i+B(s),0);try{nl(e,o,r)}catch{}}async function EO(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await yg(s,{timeout:wO(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function vO(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function Is(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var SO,Pg,PO,CO,He=y(()=>{"use strict";Gt();Rg();ur();ue();_l();SO=3,Pg=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,PO=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,CO=5e3});function Fe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:U(s,o.rawResponse)}function Fs(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return M(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Me(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return M(i,t,{toolName:r})}var ze=y(()=>{"use strict";Xa();ue()});async function Ke({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Me(o,t,r,e)}}var rn=y(()=>{"use strict";ze()});import{spawn as OO}from"child_process";function _O(e={},t=Fl){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function Bt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Fl,maxOutputSize:a=LO}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),p={cwd:o,env:_O(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=OO(e,t,p)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let m,h=setTimeout(()=>{if(!l.killed){l.killed=!0;try{f.kill("SIGTERM")}catch{}m=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},AO),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),b=()=>{clearTimeout(h),m!==void 0&&(clearTimeout(m),m=void 0)},x=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{f.kill("SIGKILL")}catch{}b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};f.stdout?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!x()&&l.stdoutChunks.push(T)}),f.stderr?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!x()&&l.stderrChunks.push(T)}),f.on("close",S=>{l.killed||(b(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),f.on("error",S=>{l.killed||(l.killed=!0,b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function Ds(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var Fl,Ms,kg,LO,AO,FW,mo=y(()=>{"use strict";Fl=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Ms=[...Fl,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],kg=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],LO=10*1024*1024,AO=5e3;FW=1*1024*1024});import{validateCommand as IO}from"@octocodeai/octocode-engine/commandValidator";async function dr(e,t=[],n={}){let r=IO(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Ds(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024,tolerateOutputLimit:l=!1}=n,u=await Bt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(u.outputLimitExceeded&&l)return{success:!0,code:u.exitCode,stdout:u.stdout,stderr:u.stderr,truncated:!0};if(u.error)throw u.error;return{success:u.success,code:u.exitCode,stdout:u.stdout,stderr:u.stderr}}var Ml=y(()=>{"use strict";mo()});function Rt(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function FO(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},u={command:"7z",args:i},d={command:"7zz",args:i},p={command:"aa",args:s};return Rt(Tg,e)?[p]:Rt(Gl,e)?[u,d,l,c,a]:Rt(Nl,e)?[l,u,d,c,a]:Rt(Dl,e)?[a,c,l,u,d]:[c,a,l,u,d]}function MO(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return Rt(Gl,e)?[s,a,o,r,n]:Rt(Nl,e)?[o,s,a,r,n]:Rt(Dl,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Hl(e){let t=[];for(let n of e){let r=await dr(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function DO(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
31
- `).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
32
- `)}async function Eg(e,t){let n=await Hl(FO(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?DO(n.stdout,n.commandUsed):n.stdout).split(`
33
- `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function vg(e,t){return Hl(MO(e,t))}function NO(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return Rt(Tg,e)?[c]:Rt(Gl,e)?[s,a,o,n,r]:Rt(Nl,e)?[o,s,a,n,r]:Rt(Dl,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Og(e,t){return Hl(NO(e,t))}var Dl,Nl,Gl,Tg,Lg=y(()=>{"use strict";Ml();Dl=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Nl=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Gl=[".dmg",".rar",".cpgz"],Tg=[".aar",".yaa"]});function QO(e){let t=e.toLowerCase();for(let{ext:n,format:r}of HO)if(t.endsWith(n))return r}async function BO(e){let t=await dr("file",["--mime-type","-b",e]);if(t.success)return zO[t.stdout.trim().toLowerCase()]}async function $O(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await dr(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await dr(r.command,r.args)).stderr,commandUsed:r.command}}async function Ag(e,t){let n;if(t!=="auto"?n=t:n=QO(e)??await BO(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=GO[n],o=await $O(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}var GO,HO,zO,_g=y(()=>{"use strict";Ml();GO={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},HO=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],zO={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"}});function Ig(e){try{return{success:!0,info:D.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function Fg(e,t,n,r=0){try{let o=D.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var Mg=y(()=>{"use strict";Ce()});import{promises as pr}from"fs";import{join as zl,basename as Ns,dirname as jO,resolve as Dg,sep as UO}from"node:path";import{securityRegistry as qO}from"@octocodeai/octocode-engine/registry";function Gg(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function KO(e){return zl(lt.unzip,`${Ns(e)}-${Gg()}`)}function YO(e,t){return zl(lt.binary,`${Ns(e)}-${t}-${Gg()}`)}function XO(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function Ql(e,t,n,r){let o=Dg(YO(e,t)),i=Dg(zl(o,XO(n)));if(!i.startsWith(o+UO)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await pr.mkdir(jO(i),{recursive:!0}),await pr.writeFile(i,r,"utf-8"),i}function ZO(){if(!Ng){try{qO.addAllowedCommands(JO)}catch{}Ng=!0}}function Bl(e,t,n){let r=D.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
34
- `):null}function $l(e,t,n,r){let s=Un(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function nL(e,t){let n=Ig(e);if(!n.success||!n.info)return M(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function rL(e,t){let n=t.verbose??!1,r=await Eg(e,n);if(!r.success)return M(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??eL,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,u=a?Math.ceil(s.length/a):1,d=a?c<u:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:u,hasMore:d,entriesPerPage:a}}}}async function oL(e,t){let n=t.archiveFile,r=await vg(e,n);if(!r.success)return M(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return M("Entry is empty",t);let i=await Ql(e,"extract",n,o);if(t.matchString){let c=Bl(o,t.matchString,t.matchStringContextLines??3);if(!c)return M(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=ct(),a=$l(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function iL(e,t){let n=await Ag(e,t.format??"auto");if(!n.success)return M(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return M("Decompressed file is empty",t);let o=await Ql(e,"decompress",`${Ns(e)}.decompressed.txt`,r);if(t.matchString){let a=Bl(r,t.matchString,t.matchStringContextLines??3);if(!a)return M(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=ct(),s=$l(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function sL(e,t){let n=t.minLength??tL,r=t.includeOffsets??!1,o=t.scanOffset??0,i=Fg(e,n,r,o);if(!i.success)return M(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
35
- `),a=s?await Ql(e,"strings",`${Ns(e)}.strings.txt`,s):void 0;if(t.matchString){let d=Bl(s,t.matchString,t.matchStringContextLines??3);if(!d)return M(`No lines match "${t.matchString}" in extracted strings`,t);s=d}let l=!!a&&t.charOffset===void 0&&t.charLength===void 0&&!t.matchString?Math.min(VO,ct()):ct(),u=$l(s,t.charOffset,t.charLength,l);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function aL(e,t){try{await pr.stat(e)}catch{return M(`File not found: ${e}`,t)}let n=KO(e);await pr.mkdir(n,{recursive:!0});let r=await Og(e,n);if(!r.success)return M(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await pr.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function Hg(e){ZO();let t=Be(e,WO);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await pr.stat(n)).isFile())return M(`Path is not a regular file: ${n}`,e)}catch{return M(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return nL(n,e);case"list":return rL(n,e);case"extract":return oL(n,e);case"decompress":return iL(n,e);case"strings":return sL(n,e);case"unpack":return aL(n,e);default:return M(`Unknown mode: ${String(e.mode)}`,e)}}var WO,VO,JO,Ng,eL,tL,zg=y(()=>{"use strict";ye();jr();Ft();Ce();mi();Fr();Lg();_g();Mg();WO=O.LOCAL_BINARY_INSPECT,VO=4e3;JO=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],Ng=!1;eL=1e3,tL=8});async function Qg(e){let{queries:t}=e;return ce(t||[],async n=>Ke({toolName:O.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Ne(nr,n);if(r.ok===!1)return r.error;let o=await Hg(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return U(o,s),o}}),{toolName:O.LOCAL_BINARY_INSPECT},e)}var Bg=y(()=>{"use strict";rs();ye();He();ze();ue();rn();zg()});function jl(e){return e.data!==void 0&&!e.error}var $g=y(()=>{"use strict"});import{maskSensitiveData as jg}from"@octocodeai/octocode-engine/mask";function cL(){return al().provider??sl()}function lL(e){let t=al(),n=t.provider??sl(),{baseUrl:r,token:o}=t;try{let i=vl(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=jg(s);throw new Ul(n,`Failed to initialize ${n} provider: ${a}`)}}function dt(e){let t;return()=>t??=lL(e)}function Gs(e,t){return e.capabilities[t]}async function on(e,t){let n=await t();return jl(n)?{ok:!0,response:n}:{ok:!1,result:Fs(n,e)}}async function Ug(e,t){let n=t??cL(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:jg(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)jl(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Ul,xn=y(()=>{"use strict";Ol();$g();no();ze();Ul=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});import{existsSync as yo,readFileSync as uL,writeFileSync as dL,mkdirSync as pL,rmSync as go,readdirSync as fL,statSync as mL}from"node:fs";import{join as pt}from"node:path";import{createHash as hL}from"node:crypto";function Vg(e){return pt(e,"tmp","clone")}function Kg(e){return pt(e,"tmp","tree")}function RL(e){return e?`__sp_${hL("sha256").update(e).digest("hex").substring(0,6)}`:""}function Yg(e,t,n,r,o){let i=`${r}${RL(o)}`;return pt(Vg(e),t,n,i)}function ql(e,t,n,r){return pt(Kg(e),t,n,r)}function SL(e){return typeof e=="object"&&e!==null}function PL(e){if(!SL(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),typeof e.commitSha=="string"&&e.commitSha.length===40&&(t.commitSha=e.commitSha),t}function Wl(e){let t=pt(e,Wg);if(!yo(t))return null;try{return PL(JSON.parse(uL(t,"utf-8")))}catch{return null}}function bo(e,t){try{dL(pt(e,Wg),JSON.stringify(t,null,2),"utf-8")}catch{}}function Xg(e){return Date.now()<new Date(e.expiresAt).getTime()}function Ro(e){let t=Wl(e);return t?Xg(t)?yo(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function CL(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return gL}function wL(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return yL}function xL(){let e=process.env.OCTOCODE_MAX_CLONES;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return Math.floor(t)}return bL}function So(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+CL()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function Tn(e){let t=pt(e,"..");try{yo(t)||pL(t,{recursive:!0,mode:448})}catch(n){throw new Error(`Failed to create clone parent directory '${t}': ${n instanceof Error?n.message:String(n)}`)}}function Hs(e){try{yo(e)&&go(e,{recursive:!0,force:!0})}catch{}}function ho(e){try{return mL(e).isDirectory()}catch{return!1}}function kn(e){try{return fL(e)}catch{return[]}}function*Jg(e){for(let t of kn(e)){let n=pt(e,t);if(ho(n))for(let r of kn(n)){let o=pt(n,r);if(ho(o))for(let i of kn(o)){let s=pt(o,i);ho(s)&&(yield s)}}}}function qg(e){for(let t of[...kn(e)]){let n=pt(e,t);if(ho(n)){for(let r of[...kn(n)]){let o=pt(n,r);if(ho(o)&&kn(o).length===0)try{go(o,{recursive:!0,force:!0})}catch{}}if(kn(n).length===0)try{go(n,{recursive:!0,force:!0})}catch{}}}}function kL(e){let t=0;for(let n of Jg(e))try{let r=Wl(n);(!r||!Xg(r))&&(go(n,{recursive:!0,force:!0}),t++)}catch{}return t}function TL(e){let t=[];for(let n of Jg(e)){let r=Wl(n);if(!r)continue;let o=Number.isNaN(Date.parse(r.clonedAt))?0:Date.parse(r.clonedAt);t.push({branchDir:n,clonedAtMs:o,sizeBytes:r.sizeBytes??fs(n)})}return t}function EL(e,t,n){let r=e.reduce((s,a)=>s+a.sizeBytes,0),o=e.length;if(r<=t&&o<=n)return 0;e.sort((s,a)=>s.clonedAtMs-a.clonedAtMs);let i=0;for(let s of e){if(r<=t&&o<=n)break;try{go(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Zg(e){if(!yo(e))return 0;let t=0;try{t+=kL(e)}catch{return t}qg(e);let n=EL(TL(e),wL(),xL());return t+=n,n>0&&qg(e),t}function ey(e){return Zg(Vg(e))}function Vl(e){return Zg(Kg(e))}var gL,wV,yL,bL,Wg,Kl=y(()=>{"use strict";Gt();gL=1440*60*1e3,wV=600*1e3,yL=2*1024*1024*1024,bL=50,Wg=".octocode-clone-meta.json"});import{existsSync as vL,mkdirSync as Yl,renameSync as OL,rmSync as LL}from"fs";import{join as Po}from"path";import{createHash as AL}from"crypto";async function oy(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await jL();let a=e.branch??await it(r,o,t),c=$r(),l=Yg(c,r,o,a,i);return DL(c,l,async()=>{let u=Ro(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};ey(c),Tn(l);let d=$L(t,n),p=GL(c,l);Hs(p);try{if(i){if(await BL(r,o,a,p,i,d),!vL(Po(p,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await QL(r,o,a,p,d);let f=So(r,o,a,"clone",i);return bo(p,f),HL(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw Hs(p),f}})}async function DL(e,t,n){Tn(t);let r=NL(e,t);Yl(Po(e,"tmp",ny),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Yl(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>IL)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await zL(FL)}try{return await n()}finally{LL(r,{recursive:!0,force:!0})}}function iy(e){return AL("sha256").update(e).digest("hex").slice(0,16)}function NL(e,t){return Po(e,"tmp",ny,iy(t))}function GL(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Po(e,"tmp",ML);return Yl(r,{recursive:!0,mode:448}),Po(r,`${iy(t)}-${n}`)}function HL(e,t){Hs(t),Tn(t),OL(e,t)}function zL(e){return new Promise(t=>setTimeout(t,e))}async function QL(e,t,n,r,o){let i=ay(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",sy(e,t),r),await Xl(i,ty,`full clone of ${e}/${t}`,o)}async function BL(e,t,n,r,o,i){let s=ay(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",sy(e,t),r),await Xl(s,ty,`sparse clone of ${e}/${t}`,i),await Xl(["-C",r,"sparse-checkout","set","--skip-checks","--",o],_L,`sparse-checkout set ${o}`,void 0)}function sy(e,t){return`https://github.com/${e}/${t}.git`}function ay(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function $L(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function jL(){try{if(!(await Bt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:ry,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 UL(e,t){let n=e;return t&&(n=n.replaceAll(t,"[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 Xl(e,t,n,r){let o=await Bt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:ry,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=UL(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var ty,_L,IL,FL,ny,ML,ry,cy=y(()=>{"use strict";Gt();qe();mo();Kl();ty=120*1e3,_L=30*1e3,IL=300*1e3,FL=100,ny="clone-locks",ML="clone-tmp",ry=[...Ms,"GIT_TERMINAL_PROMPT"]});async function ly(e){let{queries:t,authInfo:n}=e,r=dt(n);return ce(t,async(o,i)=>Ke({toolName:O.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Gs(s,"cloneRepo"))return Me(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",O.GITHUB_CLONE_REPO);let a;try{a=await oy(o,n,s.token)}catch(p){let f=p instanceof Error?p.message:String(p);return M(`Clone failed for ${o.owner}/${o.repo}: ${f}`,o)}let c=fs(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={localSearch:{tool:"localSearchCode",query:{path:a.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return Fe(o,d,!0,O.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:O.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}var uy=y(()=>{"use strict";Gt();ye();He();ze();rn();xn();cy()});import{writeFileSync as my,mkdirSync as Jl,existsSync as Co,rmSync as qL,readdirSync as WL,statSync as hy}from"node:fs";import{join as zs,dirname as gy,resolve as Zl,sep as eu}from"node:path";function py(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function XL(e){return Object.values(e).every(t=>t===0)}function fy(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 Ry(e,t,n,r,o,i=!1){let s=$r(),a=ql(s,e,t,r),c=Zl(zs(a,n));if(!c.startsWith(a+eu)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Ro(a);if(l.hit&&!i&&Co(c)){let v=tA(c,a),Q=py();return{localPath:c,repoRoot:a,files:v.files,fileCount:v.fileCount,totalSize:v.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:v.fileCount,eligibleFileCount:v.fileCount,savedFileCount:v.fileCount,skipped:Q,limits:dy,warnings:fy(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await ge(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:p}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(p))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=p,m=py(),h=[];for(let v of f){if(v.type!=="file"){m.nonFile+=1;continue}if(!v.download_url){m.missingDownloadUrl+=1;continue}if(v.size>by){m.oversized+=1;continue}let Q=oh(v.name,{lowercase:!0,leadingDot:!0});if(YL.has(Q)){m.binary+=1;continue}h.push(v)}m.fileLimit=Math.max(0,h.length-tu);let b=h.slice(0,tu),x=o?.token,S=await JL(b,VL,x);m.fetchFailed=b.length-S.length;let T=0,L=[];for(let v=0;v<S.length;v+=1){let{entry:Q,content:G}=S[v];if(T+G.length>yy){m.totalSizeLimit=S.length-v;break}T+=G.length,L.push({entry:Q,content:G})}Vl(s),Tn(a),Co(c)&&qL(c,{recursive:!0,force:!0}),Jl(c,{recursive:!0,mode:448});let _=[];for(let{entry:v,content:Q}of L){let G=Zl(zs(a,v.path));if(!G.startsWith(a+eu)){m.pathTraversal+=1;continue}let K=gy(G);Co(K)||Jl(K,{recursive:!0,mode:448}),my(G,Q,"utf-8"),_.push({path:v.path,size:Q.length,type:"file"})}let E=So(e,t,r,"treeFetch",void 0,void 0,d);bo(a,E);let w=XL(m),N=w,F=m.nonFile>0;return{localPath:c,repoRoot:a,files:_,fileCount:_.length,totalSize:T,complete:w,verified:N,...d?{commitSha:d}:{},...F?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:h.length,savedFileCount:_.length,skipped:m,limits:dy,warnings:fy(w,N),cached:!1,expiresAt:E.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function Sy(e,t,n,r,o,i=!1){let s=$r(),a=ql(s,e,t,r),c=Zl(zs(a,n));if(!c.startsWith(a+eu)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Ro(a);if(!i&&l.hit&&Co(c))return{localPath:c,repoRoot:a,path:n,size:nA(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await Ps({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let m="error"in u?u.error:void 0;throw new Error(m||`Failed to fetch ${e}/${t}/${n}`)}Vl(s),Tn(a);let d=gy(c);Co(d)||Jl(d,{recursive:!0,mode:448}),my(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=So(e,t,p,"treeFetch");return bo(a,f),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:p}}async function JL(e,t,n){let r=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),s=await Promise.allSettled(i.map(async a=>{let c=await eA(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function eA(e,t){try{let o=new URL(e);if(!ZL.has(o.hostname))throw new Error(`Blocked fetch to unexpected host: ${o.hostname}. Only GitHub download URLs are allowed.`)}catch(o){throw o instanceof TypeError?new Error(`Invalid download URL: ${e}`):o}let n=new AbortController,r=setTimeout(()=>n.abort(),KL);try{let o={"User-Agent":"octocode-mcp"};t&&(o.Authorization=`token ${t}`);let i=await fetch(e,{signal:n.signal,headers:o});if(!i.ok)throw new Error(`HTTP ${i.status} fetching ${e}`);return await i.text()}finally{clearTimeout(r)}}function tA(e,t){let n=[],r=0;function o(i){let s;try{s=WL(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=zs(i,a);try{let l=hy(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function nA(e){try{return hy(e).size}catch{return 0}}var tu,yy,by,VL,KL,YL,dy,ZL,Py=y(()=>{"use strict";Gt();qe();yl();Kl();co();tu=50,yy=5*1024*1024,by=300*1024,VL=5,KL=1e4,YL=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".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",".lock",".min.js",".min.css"]),dy={maxDirectoryFiles:tu,maxTotalSize:yy,maxFileSize:by};ZL=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function oA(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function Cy(e,t){return e&&t?`${e}/${t}`:void 0}function wy(e){return{keywords:e.keywords??[],projectId:Cy(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,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function xy(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function ky(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Ty(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=ky(a),u=`${c}/${l}`,d=s,p=o.get(u);if(p||(p={id:u,owner:c,repo:l,matches:[]},o.set(u,p)),n||!s.matches?.length){p.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let f=!0,m=!1;for(let h of s.matches){if(!h.context)continue;let b={path:s.path,value:oA(h.context)};h.positions?.length>0&&(b.matchIndices=h.positions.map(([x,S])=>({start:x,end:S,lineOffset:(h.context??"").substring(0,x).split(`
36
- `).length-1}))),r&&f&&d.url&&(b.url=d.url,f=!1),p.matches.push(b),m=!0}m||p.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.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,...xy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function Ey(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function vy(e){return e.map(t=>{let{owner:n,repo:r}=ky(t.fullPath);return{owner:n||"",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}}})}function iA(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Oy(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(iA),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Cy(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function sA(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function aA(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:sA(e)}}function Ly(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=aA(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...xy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function Ay(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,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function _y(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.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...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 Iy(e,t){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??Pn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Fy(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([p],[f])=>p==="."?-1:f==="."?1:p.localeCompare(f)).map(([p,f])=>({dir:p,files:f.files,folders:f.folders})),c=e.fileSizeMap,l={};if(c){for(let[p,f]of Object.entries(c))if(n[p]){let m=new Set(n[p].files);for(let[h,b]of Object.entries(f))if(m.has(h)){let x=p==="."?h:`${p}/${h}`;l[x]=b}}}let u=Object.values(n).reduce((p,f)=>(p.totalFiles+=f.files.length,p.totalFolders+=f.folders.length,p),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var fr=y(()=>{"use strict";Se();Es()});function Qs(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function cA(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:Qs(t.status),retryAfterSeconds:Qs(t.retryAfter),rateLimitRemaining:Qs(t.rateLimitRemaining),rateLimitReset:Qs(t.rateLimitReset)}}return{message:"Provider error"}}function Bs(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=cA(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function $s(e,t,n){let r=wn(e,[...t]);return{structuredContent:ut(Cn(e)??{}),text:r,isError:n}}var nu=y(()=>{"use strict";ur()});function js(e){return typeof e=="object"&&e!==null}function ft(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function My(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function St(e,t){return Ye(e[t])??0}function lA(e){if(js(e))return{nonFile:St(e,"nonFile"),missingDownloadUrl:St(e,"missingDownloadUrl"),oversized:St(e,"oversized"),binary:St(e,"binary"),fileLimit:St(e,"fileLimit"),fetchFailed:St(e,"fetchFailed"),totalSizeLimit:St(e,"totalSizeLimit"),pathTraversal:St(e,"pathTraversal")}}function uA(e){if(js(e))return{maxDirectoryFiles:St(e,"maxDirectoryFiles"),maxTotalSize:St(e,"maxTotalSize"),maxFileSize:St(e,"maxFileSize")}}function pA(e){if(!js(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of dA){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function fA(e,t){return`${e}/${t}`}function mA(e,t,n){let r=fA(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function hA(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function gA(e,t){let n=pA(e.pagination),r=hA(n,t);return{path:ft(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:ft(e.localPath),repoRoot:ft(e.repoRoot),...Ye(e.fileSize)!==void 0?{fileSize:Ye(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:Ye(e.totalLines),sourceChars:Ye(e.sourceChars),sourceBytes:Ye(e.sourceBytes),resolvedBranch:ft(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:Ye(e.startLine),endLine:Ye(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:ft(e.lastModified),lastModifiedBy:ft(e.lastModifiedBy),warnings:My(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:ft(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function yA(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(js).map(c=>({path:ft(c.path)??"",size:Ye(c.size)??0,type:ft(c.type)??"file"})),o=lA(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:ft(e.localPath)??"",repoRoot:ft(e.repoRoot),fileCount:Ye(e.fileCount)??r.length,totalSize:Ye(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ye(e.directoryEntryCount),eligibleFileCount:Ye(e.eligibleFileCount),savedFileCount:Ye(e.savedFileCount),skipped:o,limits:uA(e.limits),warnings:My(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:ft(e.resolvedBranch)}}function bA(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=mA(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(yA(c,o)),a.directories=u;return}let l=a.files??[];l.push(gA(c,o)),a.files=l}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function RA(e,t){return Bs(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function Dy(){return({queries:e,results:t})=>{let n=new Map;e.forEach((s,a)=>{n.set(Is(s,a),s)});let r=bA(t,n),o=RA(t,n),i={results:r};return o&&o.length>0&&(i.errors=o),$s(i,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],r.length===0&&!!(o&&o.length>0))}}var dA,Ny=y(()=>{"use strict";nu();He();dA=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function Gy(e){let{queries:t,authInfo:n}=e,r=dt(n);return ce(t,async(o,i)=>{try{let s=Ne(Kn,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?SA(a,n,c):PA(a,n,c)}catch(s){return Me(s,o,void 0,O.GITHUB_FETCH_CONTENT)}},{toolName:O.GITHUB_FETCH_CONTENT,finalize:Dy()},e)}async function SA(e,t,n){if(!Gs(n,"fetchDirectoryToDisk"))return Me(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",O.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return M("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await it(e.owner,e.repo,t),o=await Ry(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,skipped:o.skipped,limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return Fe(e,l,!0,O.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??B(o)})}async function PA(e,t,n){let r=await on(e,()=>n.provider.getFileContent(Ay(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await CA(e,t):void 0,i={..._y(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Fe(e,i,s,O.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function CA(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await it(e.owner,e.repo,t);return Sy(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var Hy=y(()=>{"use strict";ye();He();ze();Mi();Py();qe();ue();fr();xn();Ny()});function wA(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function xA(e,t){let n=wA(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function kA(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function TA(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function EA(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function zy(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function vA(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:zy(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:zy(r.get(i)),...s?{pagination:s}:{}}}})}function OA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function LA(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${OA(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function AA(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?EA(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:LA(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:_A(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function _A(e,t){return{...e,matches:t}}function Qy(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=kA(p);m.incompleteResults&&(i=!0),m.results.reduce((x,S)=>x+S.matches.length,0)===0&&o.push({id:p.id,...m.nonExistentScope?{nonExistentScope:!0}:{},...m.incompleteResults?{incompleteResults:!0}:{}});let b=m.results;n.push({id:p.id,groups:b}),m.pagination&&r.set(p.id,m.pagination)});let s=Array.from(new Set(e.flatMap(p=>{let f=p.keywords;return Array.isArray(f)?f.filter(m=>typeof m=="string"):[]}))),a=AA(TA(n),s),c=Bs(t),l=e.some(p=>p.concise===!0),u=vA(e,a,r);if(l)for(let p of u)p.data.files=p.data.files.map(f=>`${f.owner}/${f.repo}:${f.path}`);let d={results:u};return o.length>0&&(d.emptyQueries=o.map(({id:p,nonExistentScope:f,incompleteResults:m})=>({id:p,...f?{nonExistentScope:f}:{},...m?{incompleteResults:m}:{}}))),c.length>0&&(d.errors=c),i&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),o.length>0&&xA(o,e)&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding."]),$s(d,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],a.length===0&&c.length>0)}}var By=y(()=>{"use strict";nu()});function IA(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function FA(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 $y(e){let{queries:t}=e,n=dt(e.authInfo);return ce(t,async(r,o)=>{try{let i=FA(r);if(i)return M(i.error,r);if(!IA(r))return M("At least one search term or scope filter is required.",r);let s=n(),a=await on(r,()=>s.provider.searchCode(wy(r)));if(a.ok===!1)return a.result;let c=Ty(a.response.data,r);return Fe(r,c,c.results.length>0,O.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Me(i,r,void 0,O.GITHUB_SEARCH_CODE)}},{toolName:O.GITHUB_SEARCH_CODE,finalize:Qy()},e)}var jy=y(()=>{"use strict";ye();He();ze();fr();xn();By()});function MA(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function DA(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function NA(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Uy(e){let{content:t,reviewMode:n}=e,r=MA(t,n),o=DA(t,n),i=NA(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}var qy=y(()=>{"use strict"});function iu(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function qs(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function su(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function Vs(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Vy(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Ky(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function GA(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Ws(e,t,n){return GA({...Ky(e,t),...n})}function Wy(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Ws(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function ru(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Ws(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function HA(e,t,n){return{target:Ky(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function Us(e){return String(e.path??e.filename??"")}function zA(e,t){return{path:Us(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function QA(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function BA(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=QA(r,n.comments),i=iu(t),s=i?o.filter(l=>qs(l.body,i)):o,{items:a,pagination:c}=su(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=Vs(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:Vy(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function $A(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=iu(t);return{reviews:(o?r.filter(s=>qs(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Vs(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function jA(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=su(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function UA(e){return e.split(`
23
+ `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Kd(e,t){return t?{...e,responsePagination:t}:e}var wR=f(()=>{"use strict"});async function me(e,t,n,r){let o=n.concurrency??A_,{results:i,errors:s}=await xR(e,t,o,n.minQueryTimeoutMs);return L_(n,i,s,e,r)}function L_(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length),l=Oi(r);t.forEach(y=>{let b=y.result.status;c[y.queryIndex]={id:l[y.queryIndex]??Ei(y.originalQuery,y.queryIndex),...b!==void 0?{status:b}:{},data:__(y.result)}}),n.forEach(y=>{let b=r[y.queryIndex];b&&(c[y.queryIndex]={id:l[y.queryIndex]??Ei(b,y.queryIndex),status:"error",data:{error:y.error}})});let u=c.filter(y=>y!==void 0);if(e.finalize){let y=e.finalize({queries:r,results:u,config:e}),b=Vd(y.text,o),S=Kd(y.structuredContent,b.pagination);return kR(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:S,isError:y.isError??(u.length>0&&u.every(E=>E.status==="error"))}}let d={results:u};if(Array.isArray(d.results)){let y=Ha(d.results);y&&(d.base=y);let b=Qa(d.results);b&&(d.shared=b)}let m=Xn(d,a),p=Vd(m,o),h=Kd(dt(Yn(d)??{}),p.pagination);return kR(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:h,isError:u.length>0&&u.every(y=>y.status==="error")}}function kR(e,t,n,r){let o=t.reduce((i,s)=>i+(le(s.result)??j(s.result)),0)+n.reduce((i,s)=>i+j(s),0);try{Au(e,o,r)}catch{}}function __(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}var A_,TR=f(()=>{"use strict";At();zr();ue();qd();wR();zd();A_=3});var Xe=f(()=>{"use strict";zd();TR()});var U,ER,Jn=f(()=>{"use strict";U={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"},ER={[U.PATH_VALIDATION_FAILED]:{code:U.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[U.FILE_ACCESS_FAILED]:{code:U.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[U.FILE_READ_FAILED]:{code:U.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[U.FILE_TOO_LARGE]:{code:U.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[U.BINARY_FILE_UNSUPPORTED]:{code:U.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[U.NO_MATCHES]:{code:U.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[U.OUTPUT_TOO_LARGE]:{code:U.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[U.COMMAND_NOT_AVAILABLE]:{code:U.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[U.COMMAND_EXECUTION_FAILED]:{code:U.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[U.COMMAND_TIMEOUT]:{code:U.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[U.TOOL_EXECUTION_FAILED]:{code:U.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[U.LSP_SERVER_UNAVAILABLE]:{code:U.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function Yd(e){return e instanceof Qe}function OR(e,t=U.TOOL_EXECUTION_FAILED,n){if(Yd(e))return e;if(e instanceof Error)return new Qe(t,e.message,n,e);let r=String(e);return new Qe(t,r,n)}var Qe,ja=f(()=>{"use strict";Jn();Qe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=ER[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
24
+ Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}}});function F_(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function N(e,t,n={}){let{extra:r}=n,o={status:"error"};if(F_(e))o.error=e;else if(Yd(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=OR(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:W(o,n.rawResponse)}function st(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:N(i,t,{toolName:n.toolName})}}var Xd=f(()=>{"use strict";ja();ue()});function Ce(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:W(s,o.rawResponse)}function Ba(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return N(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ze(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return N(i,t,{toolName:r})}var De=f(()=>{"use strict";Xd();ue()});async function pt({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ze(o,t,r,e)}}var Zn=f(()=>{"use strict";De()});function Jd(e){return e.data!==void 0&&!e.error}var vR=f(()=>{"use strict"});import{maskSensitiveData as AR}from"@octocodeai/octocode-engine/mask";function I_(){return Nu().provider??Du()}function M_(e){let t=Nu(),n=t.provider??Du(),{baseUrl:r,token:o}=t;try{let i=jd(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=AR(s);throw new Zd(n,`Failed to initialize ${n} provider: ${a}`)}}function mt(e){let t;return()=>t??=M_(e)}function za(e,t){return e.capabilities[t]}async function Jt(e,t){let n=await t();return Jd(n)?{ok:!0,response:n}:{ok:!1,result:Ba(n,e)}}async function LR(e,t){let n=t??I_(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:AR(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Jd(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Zd,xn=f(()=>{"use strict";Bd();vR();si();De();Zd=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});function FR(e={},t=$a){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}var $a,vi,_R,ep=f(()=>{"use strict";$a=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],vi=[...$a,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],_R=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"]});import{spawn as D_}from"child_process";function er(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=$a,maxOutputSize:a=N_}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),m={cwd:o,env:FR(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=D_(e,t,m)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let h,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},G_),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),y=()=>{clearTimeout(g),h!==void 0&&(clearTimeout(h),h=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",S=>{if(l.killed)return;let C=S.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stdoutChunks.push(C)}),p.stderr?.on("data",S=>{if(l.killed)return;let C=S.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stderrChunks.push(C)}),p.on("close",S=>{l.killed||(y(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),p.on("error",S=>{l.killed||(l.killed=!0,y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function IR(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var N_,G_,J2,MR=f(()=>{"use strict";ep();N_=10*1024*1024,G_=5e3;J2=1*1024*1024});var Ua=f(()=>{"use strict";ep();MR()});import{join as qa}from"node:path";import{createHash as DR}from"node:crypto";function Wa(e){return qa(e,"tmp","clone")}function Va(e){return qa(e,"tmp","tree")}function H_(e){return e?`__sp_${DR("sha256").update(e).digest("hex").substring(0,6)}`:""}function NR(e){if(!/[\\/]/.test(e))return e;let t=DR("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function tp(e,t,n,r,o){let i=`${NR(r)}${H_(o)}`;return qa(Wa(e),t,n,i)}function Ai(e,t,n,r){return qa(Va(e),t,n,NR(r))}var np=f(()=>{"use strict"});import{existsSync as Fi,readFileSync as Q_,writeFileSync as j_,mkdirSync as B_,rmSync as _i,readdirSync as z_,statSync as $_}from"node:fs";import{join as Cn}from"node:path";function V_(e){return typeof e=="object"&&e!==null}function K_(e){if(!V_(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),typeof e.commitSha=="string"&&e.commitSha.length===40&&(t.commitSha=e.commitSha),t}function rp(e){let t=Cn(e,HR);if(!Fi(t))return null;try{return K_(JSON.parse(Q_(t,"utf-8")))}catch{return null}}function $r(e,t){try{j_(Cn(e,HR),JSON.stringify(t,null,2),"utf-8")}catch{}}function QR(e){return Date.now()<new Date(e.expiresAt).getTime()}function Ur(e){let t=rp(e);return t?QR(t)?Fi(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Y_(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return U_}function X_(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return q_}function J_(){let e=process.env.OCTOCODE_MAX_CLONES;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return Math.floor(t)}return W_}function qr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Y_()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function wn(e){let t=Cn(e,"..");try{Fi(t)||B_(t,{recursive:!0,mode:448})}catch(n){throw new Error(`Failed to create clone parent directory '${t}': ${n instanceof Error?n.message:String(n)}`)}}function Ka(e){try{Fi(e)&&_i(e,{recursive:!0,force:!0})}catch{}}function Li(e){try{return $_(e).isDirectory()}catch{return!1}}function tr(e){try{return z_(e)}catch{return[]}}function*jR(e){for(let t of tr(e)){let n=Cn(e,t);if(Li(n))for(let r of tr(n)){let o=Cn(n,r);if(Li(o))for(let i of tr(o)){let s=Cn(o,i);Li(s)&&(yield s)}}}}function GR(e){for(let t of[...tr(e)]){let n=Cn(e,t);if(Li(n)){for(let r of[...tr(n)]){let o=Cn(n,r);if(Li(o)&&tr(o).length===0)try{_i(o,{recursive:!0,force:!0})}catch{}}if(tr(n).length===0)try{_i(n,{recursive:!0,force:!0})}catch{}}}}function Z_(e){let t=0;for(let n of jR(e))try{let r=rp(n);(!r||!QR(r))&&(_i(n,{recursive:!0,force:!0}),t++)}catch{}return t}function eF(e){let t=[];for(let n of jR(e)){let r=rp(n);if(!r)continue;let o=Number.isNaN(Date.parse(r.clonedAt))?0:Date.parse(r.clonedAt);t.push({branchDir:n,clonedAtMs:o,sizeBytes:r.sizeBytes??ca(n)})}return t}function tF(e,t,n){let r=e.reduce((s,a)=>s+a.sizeBytes,0),o=e.length;if(r<=t&&o<=n)return 0;e.sort((s,a)=>s.clonedAtMs-a.clonedAtMs);let i=0;for(let s of e){if(r<=t&&o<=n)break;try{_i(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function BR(e){if(!Fi(e))return 0;let t=0;try{t+=Z_(e)}catch{return t}GR(e);let n=tF(eF(e),X_(),J_());return t+=n,n>0&&GR(e),t}function zR(e){return BR(Wa(e))}function Ya(e){return BR(Va(e))}var U_,d4,q_,W_,HR,Xa=f(()=>{"use strict";At();np();np();U_=1440*60*1e3,d4=600*1e3,q_=2*1024*1024*1024,W_=50,HR=".octocode-clone-meta.json"});import{existsSync as nF,mkdirSync as op,renameSync as rF,rmSync as oF}from"fs";import{join as Ii}from"path";import{createHash as iF}from"crypto";async function WR(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await bF();let a=e.branch??await Ve(r,o,t),c=Ar(),l=tp(c,r,o,a,i);return uF(c,l,async()=>{let u=Ur(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};zR(c),wn(l);let d=yF(t,n),m=pF(c,l);Ka(m);try{if(i){if(await gF(r,o,a,m,i,d),!nF(Ii(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await hF(r,o,a,m,d);let p=qr(r,o,a,"clone",i);return $r(m,p),mF(m,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw Ka(m),p}})}async function uF(e,t,n){wn(t);let r=dF(e,t);op(Ii(e,"tmp",UR),{recursive:!0,mode:448});let o=Date.now();for(;;)try{op(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>aF)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await fF(cF)}try{return await n()}finally{oF(r,{recursive:!0,force:!0})}}function VR(e){return iF("sha256").update(e).digest("hex").slice(0,16)}function dF(e,t){return Ii(e,"tmp",UR,VR(t))}function pF(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Ii(e,"tmp",lF);return op(r,{recursive:!0,mode:448}),Ii(r,`${VR(t)}-${n}`)}function mF(e,t){Ka(t),wn(t),rF(e,t)}function fF(e){return new Promise(t=>setTimeout(t,e))}async function hF(e,t,n,r,o){let i=YR(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",KR(e,t),r),await ip(i,$R,`full clone of ${e}/${t}`,o)}async function gF(e,t,n,r,o,i){let s=YR(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",KR(e,t),r),await ip(s,$R,`sparse clone of ${e}/${t}`,i),await ip(["-C",r,"sparse-checkout","set","--skip-checks","--",o],sF,`sparse-checkout set ${o}`,void 0)}function KR(e,t){return`https://github.com/${e}/${t}.git`}function YR(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function yF(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function bF(){try{if(!(await er("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:qR,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 RF(e,t){let n=e;return t&&(n=n.replaceAll(t,"[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 ip(e,t,n,r){let o=await er("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:qR,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=RF(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var $R,sF,aF,cF,UR,lF,qR,XR=f(()=>{"use strict";At();Ae();Ua();Xa();$R=120*1e3,sF=30*1e3,aF=300*1e3,cF=100,UR="clone-locks",lF="clone-tmp",qR=[...vi,"GIT_TERMINAL_PROMPT"]});async function JR(e){let{queries:t,authInfo:n}=e,r=mt(n);return me(t,async(o,i)=>pt({toolName:v.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!za(s,"cloneRepo"))return ze(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",v.GITHUB_CLONE_REPO);let a;try{a=await WR(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return N(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=ca(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return Ce(o,d,!0,v.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:v.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","location","error"]},e)}var ZR=f(()=>{"use strict";At();pe();Xe();De();Zn();xn();XR()});import{readdirSync as SF,statSync as eS}from"node:fs";import{join as PF}from"node:path";function cp(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function rS(e){return Object.values(e).every(t=>t===0)}function lp(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 oS(e,t,n){let r=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),s=await Promise.allSettled(i.map(async a=>{let c=await wF(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function wF(e,t){try{let o=new URL(e);if(!CF.has(o.hostname))throw new Error(`Blocked fetch to unexpected host: ${o.hostname}. Only GitHub download URLs are allowed.`)}catch(o){throw o instanceof TypeError?new Error(`Invalid download URL: ${e}`):o}let n=new AbortController,r=setTimeout(()=>n.abort(),xF);try{let o={"User-Agent":"octocode-mcp"};t&&(o.Authorization=`token ${t}`);let i=await fetch(e,{signal:n.signal,headers:o});if(!i.ok)throw new Error(`HTTP ${i.status} fetching ${e}`);return await i.text()}finally{clearTimeout(r)}}function iS(e,t){let n=[],r=0;function o(i){let s;try{s=SF(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=PF(i,a);try{let l=eS(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function sS(e){try{return eS(e).size}catch{return 0}}var Mi,Ja,sp,tS,xF,nS,ap,CF,Za=f(()=>{"use strict";Mi=50,Ja=5*1024*1024,sp=300*1024,tS=5,xF=1e4,nS=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".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",".lock",".min.js",".min.css"]),ap={maxDirectoryFiles:Mi,maxTotalSize:Ja,maxFileSize:sp};CF=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});import{writeFileSync as kF,mkdirSync as aS,existsSync as up,rmSync as TF}from"node:fs";import{join as cS,dirname as EF,resolve as lS,sep as uS}from"node:path";async function dp(e,t,n,r,o,i=!1){let s=Ar(),a=Ai(s,e,t,r),c=lS(cS(a,n));if(!c.startsWith(a+uS)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Ur(a);if(l.hit&&!i&&up(c)){let A=iS(c,a),q=cp();return{localPath:c,repoRoot:a,files:A.files,fileCount:A.fileCount,totalSize:A.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:A.fileCount,eligibleFileCount:A.fileCount,savedFileCount:A.fileCount,skipped:q,limits:ap,warnings:lp(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await oe(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let p=m,h=cp(),g=[];for(let A of p){if(A.type!=="file"){h.nonFile+=1;continue}if(!A.download_url){h.missingDownloadUrl+=1;continue}if(A.size>sp){h.oversized+=1;continue}let q=Wy(A.name,{lowercase:!0,leadingDot:!0});if(nS.has(q)){h.binary+=1;continue}g.push(A)}h.fileLimit=Math.max(0,g.length-Mi);let y=g.slice(0,Mi),b=o?.token,S=await oS(y,tS,b);h.fetchFailed=y.length-S.length;let C=0,E=[];for(let A=0;A<S.length;A+=1){let{entry:q,content:H}=S[A];if(C+H.length>Ja){h.totalSizeLimit=S.length-A;break}C+=H.length,E.push({entry:q,content:H})}Ya(s),wn(a),up(c)&&TF(c,{recursive:!0,force:!0}),aS(c,{recursive:!0,mode:448});let T=[];for(let{entry:A,content:q}of E){let H=lS(cS(a,A.path));if(!H.startsWith(a+uS)){h.pathTraversal+=1;continue}let K=EF(H);up(K)||aS(K,{recursive:!0,mode:448}),kF(H,q,"utf-8"),T.push({path:A.path,size:q.length,type:"file"})}let _=qr(e,t,r,"treeFetch",void 0,void 0,d);$r(a,_);let w=rS(h),G=w,M=h.nonFile>0;return{localPath:c,repoRoot:a,files:T,fileCount:T.length,totalSize:C,complete:w,verified:G,...d?{commitSha:d}:{},...M?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:T.length,skipped:h,limits:ap,warnings:lp(w,G),cached:!1,expiresAt:_.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}var dS=f(()=>{"use strict";At();Ae();Xa();fi();Za()});import{writeFileSync as OF,mkdirSync as vF,existsSync as pS}from"node:fs";import{join as AF,dirname as LF,resolve as _F,sep as FF}from"node:path";async function pp(e,t,n,r,o,i=!1){let s=Ar(),a=Ai(s,e,t,r),c=_F(AF(a,n));if(!c.startsWith(a+FF)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Ur(a);if(!i&&l.hit&&pS(c))return{localPath:c,repoRoot:a,path:n,size:sS(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await yi({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let h="error"in u?u.error:void 0;throw new Error(h||`Failed to fetch ${e}/${t}/${n}`)}Ya(s),wn(a);let d=LF(c);pS(d)||vF(d,{recursive:!0,mode:448}),OF(c,u.data.rawContent,"utf-8");let m=u.data.branch||r,p=qr(e,t,m,"treeFetch");return $r(a,p),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}var mS=f(()=>{"use strict";At();md();Xa();Za()});var fS=f(()=>{"use strict";Za();dS();mS()});function ec(e,t){return e&&t?`${e}/${t}`:void 0}function tc(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function nc(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}var rc=f(()=>{"use strict"});function MF(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function hS(e){return{keywords:e.keywords??[],projectId:ec(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,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function gS(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=tc(a),u=`${c}/${l}`,d=s,m=o.get(u);if(m||(m={id:u,owner:c,repo:l,matches:[]},o.set(u,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let p=!0,h=!1;for(let g of s.matches){if(!g.context)continue;let y={path:s.path,value:MF(g.context)};g.positions?.length>0&&(y.matchIndices=g.positions.map(([b,S])=>({start:b,end:S,lineOffset:(g.context??"").substring(0,b).split(`
25
+ `).length-1}))),r&&p&&d.url&&(y.url=d.url,p=!1),m.matches.push(y),h=!0}h||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.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,...nc(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}var yS=f(()=>{"use strict";ae();rc()});function bS(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function RS(e){return e.map(t=>{let{owner:n,repo:r}=tc(t.fullPath);return{owner:n||"",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}}})}var SS=f(()=>{"use strict";rc()});function oc(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}var mp=f(()=>{"use strict"});function PS(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(oc),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ec(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function DF(e,t){let n=[];t.some(o=>o.state==="APPROVED")&&n.push("approval"),t.some(o=>o.state==="CHANGES_REQUESTED")&&n.push("changes-requested");let r=e.filter(o=>!Kn(o.author??"")).map(o=>o.body.toLowerCase());return n.length===0&&r.some(o=>/\b(lgtm|looks good|approved|ship it)\b/.test(o))&&n.push("approval"),!n.includes("changes-requested")&&r.some(o=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(o))&&n.push("changes-requested"),r.some(o=>o.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function NF(e,t){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(i=>i.author))),r=e.map(i=>i.updatedAt||i.createdAt).filter(Boolean).sort().at(-1),o=e.filter(i=>i.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:o,discussionComments:e.length-o,commenters:n.slice(0,8),...r?{latestCommentAt:r}:{},themes:DF(e,t??[])}}function xS(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=NF(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...nc(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}var CS=f(()=>{"use strict";ae();mp();_a();rc()});function wS(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,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function kS(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.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...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}:{}}}var TS=f(()=>{"use strict"});function fp(e,t){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??Pn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function ES(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([m],[p])=>m==="."?-1:p==="."?1:m.localeCompare(p)).map(([m,p])=>({dir:m,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[m,p]of Object.entries(c))if(n[m]){let h=new Set(n[m].files);for(let[g,y]of Object.entries(p))if(h.has(g)){let b=m==="."?g:`${m}/${g}`;l[b]=y}}}let u=Object.values(n).reduce((m,p)=>(m.totalFiles+=p.files.length,m.totalFolders+=p.folders.length,m),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var OS=f(()=>{"use strict";wi()});var Wr=f(()=>{"use strict";yS();SS();CS();TS();OS()});function ic(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function GF(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:ic(t.status),retryAfterSeconds:ic(t.retryAfter),rateLimitRemaining:ic(t.rateLimitRemaining),rateLimitReset:ic(t.rateLimitReset)}}return{message:"Provider error"}}function sc(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=GF(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function ac(e,t,n){let r=Xn(e,[...t]);return{structuredContent:dt(Yn(e)??{}),text:r,isError:n}}var hp=f(()=>{"use strict";zr()});function cc(e){return typeof e=="object"&&e!==null}function ft(e){return typeof e=="string"&&e.length>0?e:void 0}function Je(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function vS(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function kt(e,t){return Je(e[t])??0}function HF(e){if(cc(e))return{nonFile:kt(e,"nonFile"),missingDownloadUrl:kt(e,"missingDownloadUrl"),oversized:kt(e,"oversized"),binary:kt(e,"binary"),fileLimit:kt(e,"fileLimit"),fetchFailed:kt(e,"fetchFailed"),totalSizeLimit:kt(e,"totalSizeLimit"),pathTraversal:kt(e,"pathTraversal")}}function QF(e){if(cc(e))return{maxDirectoryFiles:kt(e,"maxDirectoryFiles"),maxTotalSize:kt(e,"maxTotalSize"),maxFileSize:kt(e,"maxFileSize")}}function BF(e){if(!cc(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of jF){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function zF(e,t){return Ws("ghGetFileContent",{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,...t.minify!==void 0?{minify:t.minify}:{}},e)}function $F(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 localSearchCode or lspGetSemantics on it",confidence:"exact"}}function AS(e,t){let n=BF(e.pagination),r={...zF(n,t),cloneForSemantics:$F(t)};return{path:ft(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:ft(e.localPath),repoRoot:ft(e.repoRoot),...Je(e.fileSize)!==void 0?{fileSize:Je(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:Je(e.totalLines),sourceChars:Je(e.sourceChars),sourceBytes:Je(e.sourceBytes),resolvedBranch:ft(e.resolvedBranch),pagination:n,next:r,...e.isPartial===!0?{isPartial:!0}:{},startLine:Je(e.startLine),endLine:Je(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:ft(e.lastModified),lastModifiedBy:ft(e.lastModifiedBy),warnings:vS(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:ft(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function LS(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(cc).map(c=>({path:ft(c.path)??"",size:Je(c.size)??0,type:ft(c.type)??"file"})),o=HF(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:ft(e.localPath)??"",repoRoot:ft(e.repoRoot),fileCount:Je(e.fileCount)??r.length,totalSize:Je(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Je(e.directoryEntryCount),eligibleFileCount:Je(e.eligibleFileCount),savedFileCount:Je(e.savedFileCount),skipped:o,limits:QF(e.limits),warnings:vS(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:ft(e.resolvedBranch)}}var jF,_S=f(()=>{"use strict";Be();jF=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});function UF(e,t){return`${e}/${t}`}function qF(e,t,n){let r=UF(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function WF(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=qF(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(LS(c,o)),a.directories=u;return}let l=a.files??[];l.push(AS(c,o)),a.files=l}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function VF(e,t){return sc(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function FS(){return({queries:e,results:t})=>{let n=new Map,r=Oi(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=WF(t,n),i=VF(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),ac(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}var IS=f(()=>{"use strict";hp();Xe();_S()});async function MS(e){let{queries:t,authInfo:n}=e,r=mt(n);return me(t,async(o,i)=>{try{let s=st(Qn,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?KF(a,n,c):YF(a,n,c)}catch(s){return ze(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:FS()},e)}async function KF(e,t,n){if(!za(n,"fetchDirectoryToDisk"))return ze(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",v.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return N("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Ve(e.owner,e.repo,t),o=await dp(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return Ce(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??j(o)})}async function YF(e,t,n){let r=await Jt(e,()=>n.provider.getFileContent(wS(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await XF(e,t):void 0,i={...kS(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Ce(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function XF(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ve(e.owner,e.repo,t);return pp(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var DS=f(()=>{"use strict";pe();Xe();De();au();fS();Ae();ue();Wr();xn();IS()});function Di(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function NS(e,t){let n=Di(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function GS(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 JF(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function ZF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eI(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${ZF(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function tI(e,t){return{...e,matches:t}}function gp(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?JF(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:eI(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:tI(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}var lc=f(()=>{"use strict"});function QS(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function HS(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function jS(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:HS(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:HS(r.get(i)),...s?{pagination:s}:{}}}})}function BS(e,t,n){let r=Di(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),l=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!l)continue;let u=e.length===1?"getLines":`getLines:${i.id}`;o[u]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:l},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"heuristic"}}return Object.keys(o).length>0?o:void 0}var zS=f(()=>{"use strict";lc()});function yp(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Di(e);t.forEach((C,E)=>{if(C.status==="error")return;let T=GS(C);T.repoState&&s.push({id:C.id,state:T.repoState,query:a.get(C.id)}),T.incompleteResults&&(i=!0),T.results.reduce((G,M)=>G+M.matches.length,0)===0&&o.push({id:C.id,...T.nonExistentScope?{nonExistentScope:!0}:{},...T.incompleteResults?{incompleteResults:!0}:{}});let w=T.results;n.push({id:C.id,groups:w}),T.pagination&&r.set(C.id,T.pagination)});let c=Array.from(new Set(e.flatMap(C=>{let E=C.keywords;return Array.isArray(E)?E.filter(T=>typeof T=="string"):[]}))),l=gp(QS(n),c),u=sc(t),d=e.some(C=>C.concise===!0),m=jS(e,l,r),p=BS(m,e,c);if(d)for(let C of m)C.data.files=C.data.files.map(E=>`${E.owner}/${E.repo}:${E.path}`);let h={results:m,...p?{next:p}:{}};o.length>0&&(h.emptyQueries=o.map(({id:C,nonExistentScope:E,incompleteResults:T})=>({id:C,...E?{nonExistentScope:E}:{},...T?{incompleteResults:T}:{}}))),u.length>0&&(h.errors=u);let g=[],y=(C,E,T="warning")=>{h.warnings=[...h.warnings??[],E],g.push({level:T,code:C,message:E})};i&&y("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&NS(o,e)&&y("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let b=8,S=o.filter(({id:C,nonExistentScope:E,incompleteResults:T})=>{if(E||T)return!1;let _=a.get(C)?.keywords;return Array.isArray(_)&&_.length>b});S.length>0&&y("ghQueryPossiblyTooComplex",`Quer${S.length>1?"ies":"y"} ${S.map(C=>C.id).join(", ")} used more than ${b} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:C,state:E,query:T}of s)if(E.kind==="renamed"){let[_,w]=E.fullName.split("/");y("ghRepoRenamed",`Query ${C}: the repository was RENAMED to ${E.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let G=T?.keywords;h.next={...h.next??{},[`retryRenamed:${C}`]:{tool:"ghSearchCode",query:{owner:_,repo:w,...Array.isArray(G)?{keywords:G}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else E.kind==="archived"?y("ghRepoArchived",`Query ${C}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):y("ghRepoNotFound",`Query ${C}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`,"error");return g.length>0&&(h.diagnostics=g),ac(h,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],l.length===0&&u.length>0)}}var $S=f(()=>{"use strict";hp();lc();zS()});var US=f(()=>{"use strict";lc();$S()});function nI(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function rI(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 oI(e,t,n){try{let r=await oe(n),{data:o}=await r.rest.repos.get({owner:e,repo:t}),i=`${e}/${t}`.toLowerCase();return o.full_name&&o.full_name.toLowerCase()!==i?{kind:"renamed",fullName:o.full_name}:o.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function qS(e){let{queries:t}=e,n=mt(e.authInfo);return me(t,async(r,o)=>{try{let i=rI(r);if(i)return N(i.error,r);if(!nI(r))return N("At least one search term or scope filter is required.",r);let s=n(),a=await Jt(r,()=>s.provider.searchCode(hS(r)));if(a.ok===!1)return a.result;let c=gS(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let l=await oI(String(r.owner),String(r.repo),e.authInfo);l&&(c.repoState=l)}return Ce(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ze(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:yp()},e)}var WS=f(()=>{"use strict";pe();Xe();Ae();De();Wr();xn();US()});function Vr(e){return e?e.includes('rel="next"'):!1}async function sI(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}function VS(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function KS(e,t,n){let r=await Ge(t),o=Oe("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return He(o,()=>aI(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function aI(e,t){try{let n=await oe(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=Vr(i),a=o.data.map(u=>{let d=u.commit.author,m=u.commit.committer,p=m?.date??d?.date??"",h=u.commit.message,g=h.split(`
26
+ `)[0]??h,y=h.slice(g.length).trim(),b=y.length>500,S=y.length===0?g:`${g}
27
+ ${b?`${y.slice(0,500)}\u2026`:y}`,C=m?.name===d?.name&&m?.email===d?.email||u.committer?.login==="web-flow";return{sha:u.sha,date:p,...S===g?{}:{message:S},...b?{messageTruncated:!0}:{},messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...m&&!C?{committer:{name:m.name??"unknown",email:m.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await sI(a,iI,async(u,d)=>{try{let m=o.data[d]?.sha??u.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let h=e.path,g=p.data.files?.find(y=>y.filename===h||y.previous_filename===h);if(g){let y=g.patch!==void 0?VS(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...y!==void 0?{patch:y.patch,...y.patchPagination?{patchPagination:y.patchPagination}:{},diff:Si(y.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let h=e.path,g=(p.data.files??[]).filter(w=>!h||w.filename.startsWith(h)).map(w=>{let G=w.patch!==void 0?VS(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...G!==void 0?{patch:G.patch,...G.patchPagination?{patchPagination:G.patchPagination}:{},diff:Si(G.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),y=Math.max(1,e.filePage??1),b=Math.max(1,e.itemsPerPage??20),S=g.length,C=Math.max(1,Math.ceil(S/b)),E=Math.min(y,C),T=(E-1)*b,_=g.slice(T,T+b);return{...u,files:_,filesPagination:{currentPage:E,totalPages:C,itemsPerPage:b,totalFiles:S,hasMore:E<C,...E<C?{nextFilePage:E+1}:{}}}}}catch{}return u});return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return te(n)}}var iI,uc=f(()=>{"use strict";Ae();it();ka();ut();iI=5});async function YS(e,t,n){let r=await Ge(t),o=Oe("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,auth:r},n);return He(o,()=>cI(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function cI(e,t){try{let n=await oe(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},url:c.html_url})),a=Vr(r.headers.link);return{data:{type:"releases",owner:e.owner,repo:e.repo,releases:s,...i?{latest:{tagName:i.tag_name,...i.published_at?{publishedAt:i.published_at}:{}}}:{},pagination:{currentPage:e.page,perPage:e.perPage,hasMore:a,...a?{nextPage:e.page+1}:{}}},status:200}}catch(n){return te(n)}}var XS=f(()=>{"use strict";Ae();it();uc();ut()});async function JS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for releases mode.",e);let o=r.perPage!==void 0&&r.perPage!==bp?r.perPage:r.limit!==void 0&&r.limit!==30?r.limit:r.perPage??bp,i=await YS({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:Number(o)||bp},n);if(_t(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=i.data.releases.length>0||i.data.latest!==void 0,a=i.data.pagination?.nextPage,c={...i.data,...a!==void 0?{next:{nextPage:{tool:"ghHistoryResearch",query:{type:"releases",owner:r.owner,repo:r.repo,page:a,perPage:o},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return Ce(e,c,s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var bp,ZS=f(()=>{"use strict";pe();De();XS();Gr();ae();bp=30});function Dt(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function Rp(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(oc),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function eP(e,t,n){if(!n&&!t)return{text:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{text:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function dc(e){return e.pull_request!=null}function lI(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function pc(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:lI(e.labels),created_at:e.created_at??"",updated_at:e.updated_at??"",...e.closed_at?{closed_at:e.closed_at}:{},url:e.html_url??""}}function Kr(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function Sp(e,t,n="anon"){return Oe("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:Rp(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,locked:e.locked,visibility:e.visibility,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}var mc=f(()=>{"use strict";mp();ut()});import{ContentSanitizer as tP}from"@octocodeai/octocode-engine/contentSanitizer";async function nP(e,t){let n=Dt(e.owner),r=Dt(e.repo),o=e.issueNumber;if(!n||!r||o==null)return Kr("owner, repo, and issueNumber are required for issue detail mode.");let i=await oe(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(dc(s.data))return Kr(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,l=e.content?.comments?.includeBots===!0,u=pc(s.data),d={};if(a){let m=tP.sanitizeContent(s.data.body??"").content,p=eP(m,e.charOffset,e.charLength);u.body=p.text,p.pagination&&(d.body=p.pagination)}if(c){let m=Math.max(1,e.commentPage??1),p=Math.max(1,e.itemsPerPage??30),h=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=l?h.data:h.data.filter(b=>!Kn(b.user?.login??""));u.comments=g.map(b=>({id:String(b.id),user:b.user?.login??"unknown",body:tP.sanitizeContent(b.body??"").content,created_at:b.created_at??"",updated_at:b.updated_at??"",commentType:"discussion"}));let y=Vr(h.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:u.comments.length,hasMore:y,...y?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(u.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[u],total_count:1},status:200}}async function rP(e,t,n){let r=Dt(t.owner)??"",o=Dt(t.repo)??"",i=await oe(n),s=Ju(e),a=Math.min(t.limit??30,100),c=t.page??1,l=t.sort&&t.sort!=="best-match"?t.sort:void 0,u=await i.rest.search.issuesAndPullRequests({q:s,sort:l,order:t.order||"desc",per_page:a,page:c}),d=(u.data.items??[]).filter(h=>!dc(h)).map(h=>pc(h)),m=u.data.total_count??d.length,p=c*a<m&&d.length===a;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?d.map(h=>`#${h.number} ${h.title}`):d,total_count:m,effectiveQuery:s,...u.data.incomplete_results?{incomplete_results:!0}:{},pagination:{currentPage:c,perPage:a,hasMore:p,...p?{nextPage:c+1}:{},totalMatches:m,reportedTotalMatches:m,totalMatchesKind:"reported"}},status:200}}async function oP(e,t){let n=Dt(e.owner),r=Dt(e.repo);if(!n||!r)return Kr("owner and repo are required for issues mode.");let o=await oe(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),l=c.data.filter(d=>!dc(d)).map(d=>pc(d)),u=Vr(c.headers.link);return{data:{type:"issues",owner:n,repo:r,issues:e.concise?l.map(d=>`#${d.number} ${d.title}`):l,total_count:l.length,pagination:{currentPage:s,perPage:i,hasMore:u,...u?{nextPage:s+1}:{}}},status:200}}var iP=f(()=>{"use strict";Ae();_a();uc();Ir();ae();mc()});async function Pp(e,t,n){let r=await Ge(t),o=Sp(e,n,r);return He(o,()=>uI(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function uI(e,t){try{if(e.state==="merged")return Kr('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await nP(e,t);let n={...e,query:Rp(e)};return Zu(n)?await rP(n,e,t):await oP(e,t)}catch(n){return Lt(n)?{data:{type:"issues",owner:Dt(e.owner)??"",repo:Dt(e.repo)??"",issues:[],total_count:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:te(n)}}var sP=f(()=>{"use strict";Ae();it();Ir();ut();ae();mc();iP()});var aP=f(()=>{"use strict";mc();sP()});async function cP(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await Pp({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,involves:r.involves,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,interactions:r.interactions,locked:r.locked,visibility:r.visibility,"no-assignee":r["no-assignee"],"no-label":r["no-label"],"no-milestone":r["no-milestone"],"no-project":r["no-project"],match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(_t(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let u=a[0];if(typeof u=="number")return u;if(typeof u=="string"){let d=u.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(u&&typeof u=="object"&&typeof u.number=="number")return u.number})(),l={};return o==null&&c!=null&&(l.readIssue={tool:"ghHistoryResearch",query:{type:"issues",owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"heuristic"}),l.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"heuristic"},Ce(e,{...i.data,next:l},s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var lP=f(()=>{"use strict";pe();De();aP();Gr()});async function uP(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for commits mode.",e);let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return N("path is required when querying a specific file in commits mode.",e);let s=await KS({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,page:Number(r.page)||1,perPage:Number(r.perPage)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof r.itemsPerPage=="number"?r.itemsPerPage:void 0,includeDiff:!!r.includeDiff,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);if(_t(s))return N(s,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:a}=s.data,c=a.length>0,l=a.map(d=>d.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),u={...s.data,...l?{next:{prDetail:{tool:"ghHistoryResearch",query:{type:"prs",owner:r.owner,repo:r.repo,prNumber:Number(l)},why:`Open PR #${l} referenced by the first commit for review context`,confidence:"heuristic"}}}:{}};return Ce(e,u,c,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:s.rawResponseChars})}var dP=f(()=>{"use strict";pe();De();uc();Gr()});function dI(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function pI(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function mI(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function pP(e){let{content:t,reviewMode:n}=e,r=dI(t,n),o=pI(t,n),i=mI(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}var mP=f(()=>{"use strict"});function Ni(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Yr(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Gi(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function nr(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function fc(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function xp(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function fI(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Hi(e,t,n){return fI({...xp(e,t),...n})}function Cp(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Hi(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function hc(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Hi(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Xr(e){return typeof e=="object"&&e!==null}function gc(e){if(Xr(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function yc(e){if(Xr(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}var Qi=f(()=>{"use strict";ae()});function hI(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function fP(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=hI(r,n.comments),i=Ni(t),s=i?o.filter(l=>Yr(l.body,i)):o,{items:a,pagination:c}=Gi(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=nr(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:fc(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function hP(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Ni(t);return{reviews:(o?r.filter(s=>Yr(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=nr(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function gP(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Gi(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}var yP=f(()=>{"use strict";ae();Qi()});function bc(e){return String(e.path??e.filename??"")}function gI(e,t){return{path:bc(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function yI(e){return e.split(`
37
28
  `).filter(t=>{if(!t.startsWith("+"))return!0;let n=t.slice(1).trim();return n!==""&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")}).map(t=>t.startsWith("+")?"+"+t.slice(1).replace(/\s*\/\/.*$/,"").trimEnd():t).join(`
38
- `)}function qA(e){return e.replace(/\n{3,}/g,`
29
+ `)}function bP(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(bc(p))):o,a=Ni(t),c=a?s.filter(p=>Yr(bc(p),a)||Yr(p.patch,a)):s,{items:l,pagination:u}=Gi(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=l.map(p=>{let h=gI(p,!1);if(!d||typeof p.patch!="string")return h;let g=r&&!a?yI(p.patch):p.patch,y=nr(g,t.charOffset??0,t.charLength??12e3);return{...h,patch:y?.content??"",diff:Si(y?.content),...y?{patchPagination:y.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(bc).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}var RP=f(()=>{"use strict";ae();ka();Qi()});function rr(e,t){return{...e,content:t}}function bI(e,t){return{...e,...t}}function SP(e,t,n,r){let o=xp(e,t);return{target:o,...n.body?{}:{getBody:rr(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:rr(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:rr(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:rr(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:rr(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:rr(o,{reviews:!0})},...n.commits?{}:{getCommits:rr(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:bI(o,{reviewMode:"full"})}}}var PP=f(()=>{"use strict";Qi()});function RI(e){return e.replace(/\n{3,}/g,`
39
30
 
40
- `)}function WA(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(f=>i.includes(Us(f))):o,a=iu(t),c=a?s.filter(f=>qs(Us(f),a)||qs(f.patch,a)):s,{items:l,pagination:u}=su(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=zA(f,!1);if(!d||typeof f.patch!="string")return m;let h=r&&!a?UA(f.patch):f.patch,b=Vs(h,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:uo(b?.content),...b?{patchPagination:b.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(Us).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function wo(e){return typeof e=="object"&&e!==null}function ou(e){if(wo(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function au(e){if(wo(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function VA(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function KA(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!wo(n))continue;let r=au(n.patchPagination);if(r?.hasMore)return r}}function YA(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!wo(n))continue;let r=au(n.bodyPagination);if(r?.hasMore)return r}}function XA(e,t,n,r){let o={},i=au(e.bodyPagination),s=ou(e.filePagination),a=ou(e.commentPagination),c=ou(e.commitPagination),l=KA(e),u=YA(e),d=VA(n);i&&(o.body={...i,nextQuery:Wy(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:ru(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:ru(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:Ws(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:ru(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Wy(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return wo(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?Ws(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function JA(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Yy(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?qA(s):s,c=n.body?Vs(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,p=t.prNumber!==void 0||t.verbose===!0,m={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...p?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...p?{updatedAt:e.updatedAt}:{},...p||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...p&&!c?{bodyPreview:Vy(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:HA(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...WA(e,t,n,r),...BA(e,t,n),...$A(e,t,n),...jA(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},h=XA(m,t,n,i);return JA(m),h&&(m.contentPagination=h),m}var Xy=y(()=>{"use strict";Se();Cs()});function ZA(e){return e?e.includes('rel="next"'):!1}function Jy(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function Zy(e,t){try{let n=await ge(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=ZA(i),a=o.data.map(u=>{let d=u.commit.author,p=u.commit.committer,f=p?.date??d?.date??"",m=u.commit.message,h=m.split(`
41
- `)[0]??m;return{sha:u.sha,date:f,message:m,messageHeadline:h,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...p?{committer:{name:p.name??"unknown",email:p.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await Promise.all(a.map(async(u,d)=>{try{let p=o.data[d]?.sha??u.sha,f=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:p});if(e.type==="file"&&e.path){let m=e.path,h=f.data.files?.find(b=>b.filename===m||b.previous_filename===m);if(h){let b=h.patch!==void 0?Jy(h.patch,e.charOffset,e.charLength):void 0;return{...u,additions:h.additions,deletions:h.deletions,status:h.status,...b!==void 0?{patch:b.patch,...b.patchPagination?{patchPagination:b.patchPagination}:{},diff:uo(b.patch)}:{},...h.previous_filename?{previousFilename:h.previous_filename}:{}}}}else{let m=e.path,h=(f.data.files??[]).filter(w=>!m||w.filename.startsWith(m)).map(w=>{let N=w.patch!==void 0?Jy(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...N!==void 0?{patch:N.patch,...N.patchPagination?{patchPagination:N.patchPagination}:{},diff:uo(N.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),x=Math.max(1,e.itemsPerPage??20),S=h.length,T=Math.max(1,Math.ceil(S/x)),L=Math.min(b,T),_=(L-1)*x,E=h.slice(_,_+x);return{...u,files:E,filesPagination:{currentPage:L,totalPages:T,itemsPerPage:x,totalFiles:S,hasMore:L<T,...L<T?{nextFilePage:L+1}:{}}}}}catch{}return u}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return ae(n)}}var eb=y(()=>{"use strict";qe();zt();Cs()});async function tb(e){let{queries:t,authInfo:n}=e,r=dt(n);return ce(t,async(o,i)=>{try{let s=Ne(Xn,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let E=s.data;if(!E.owner||!E.repo)return M("owner and repo are required for commits mode.",o);let w=E.path,N=w&&!w.endsWith("/")?"file":"repo";if(N==="file"&&!w)return M("path is required when querying a specific file in commits mode.",o);let F=await Zy({type:N,owner:E.owner,repo:E.repo,path:w,branch:E.branch,since:E.since,until:E.until,author:E.author,page:Number(E.page)||1,perPage:Number(E.perPage)||30,filePage:typeof E.filePage=="number"?E.filePage:void 0,itemsPerPage:typeof E.itemsPerPage=="number"?E.itemsPerPage:void 0,includeDiff:!!E.includeDiff,charOffset:typeof E.charOffset=="number"?E.charOffset:void 0,charLength:typeof E.charLength=="number"?E.charLength:void 0},n);if(lr(F))return M(F,o,{toolName:O.GITHUB_SEARCH_PULL_REQUESTS});let{commits:v}=F.data,Q=v.length>0;return Fe(o,F.data,Q,O.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:F.rawResponseChars})}let a=r(),c={...s.data},l=Uy(c),u=c.prNumber!==void 0;if(u||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return M("At least one valid search parameter, filter, or PR number is required.",o);let p=await on(c,()=>a.provider.searchPullRequests(Oy(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:h}=Ly(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete h.pagination;let b=!u&&(!!o.content||!!o.reviewMode),x={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},S=c.minify==="standard",T=u,L=m.map(E=>Yy(E,c,b?x:l,S,T));h.pull_requests=L,!u&&c.concise===!0&&(h.pull_requests=L.map(E=>{let w=E;return`#${w.number} ${w.title}`}));let _=L.length>0;return Fe(c,h,_,O.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return Me(s,o,void 0,O.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:O.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var nb=y(()=>{"use strict";Hi();ye();He();ze();fr();xn();qy();Xy();eb();Rs()});function rb(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var ob=y(()=>{"use strict"});function e_(e){let t=e,n={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,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,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function t_(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(e_)}}}function ab(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function cb(e){return!!(e.keywords&&e.keywords.length>0)}function n_(e){return!!(cb(e)||ab(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function ib(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function r_(e){let t=ab(e),n=cb(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:ib(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:ib(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function o_(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function i_(e,t){return[...e].sort((n,r)=>{let o=s_(n,r,t.sort);if(o!==0)return o;let i=sb(r,t)-sb(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:cu(n).localeCompare(cu(r))})}function s_(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return rb(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function sb(e,t){let n=a_(t),r=cu(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function a_(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function cu(e){return`${e.owner}/${e.repo}`}function c_(e){return{currentPage:e.currentPage,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 l_(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function u_(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function d_(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??B(n.response.data??n.response)),0)}async function lb(e){let{queries:t,authInfo:n}=e,r=dt(n);return ce(t,async(o,i)=>{try{if(!n_(o))return M("At least one repository search term or filter is required.",o);let s=r(),a=r_(o),{successes:c,failures:l}=await Ug(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(Ey(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?Fs(w.response,o):Me(new Error("Repository search produced no provider results"),o,void 0,O.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=i_(o_(u.flatMap(w=>vy(w.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,h=u.length===1?u[0]:void 0,x=u.length>1?u_(u,f.length):h?.response.data.pagination,S=x?c_(x):void 0,T=m.length>0,L=t_({repositories:m,pagination:S},o),_=l_(d),E=_?{...L.data,warnings:_}:L.data;return Fe(o,E,T,O.GITHUB_SEARCH_REPOSITORIES,{rawResponse:d_([...u,...d])})}catch(s){return Me(s,o,void 0,O.GITHUB_SEARCH_REPOSITORIES)}},{toolName:O.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var ub=y(()=>{"use strict";ye();He();ob();ze();fr();xn();ue()});function p_(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n: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 n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function f_(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&ao(o))continue;let i=r.files.filter(a=>!cr(a)),s=r.folders.filter(a=>!ao(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function db(e){let{queries:t,authInfo:n}=e,r=dt(n);return ce(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await on(o,()=>s.provider.getRepoStructure(Iy(o,c)));if(l.ok===!1)return p_(l.result,o);let u=f_(l.response.data.structure),d=Object.keys(u).length>0,p=Fy(l.response.data,o,u,c);return Fe(o,p,d,O.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return Me(s,o,"Failed to explore repository structure",O.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:O.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var pb=y(()=>{"use strict";ye();He();co();ze();fr();xn()});import{existsSync as fb}from"fs";import{delimiter as m_,dirname as h_,join as mb}from"path";function hb(){return process.platform==="win32"?"npm.cmd":"npm"}function g_(){let e=h_(process.execPath);return mb(e,hb())}function y_(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function b_(){let e=(process.env.PATH??"").split(m_).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...y_()])]}function R_(){let e=g_();if(fb(e))return{command:process.execPath,argsPrefix:[e]};let t=hb();for(let n of b_()){let r=mb(n,t);if(fb(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function Ks(e,t,n={}){if(!S_.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Ds(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=R_(),c=await Bt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:P_});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var S_,P_,gb=y(()=>{"use strict";mo();S_=["view","search","ping","config","whoami"],P_=[...Ms,...kg]});function ko(e){try{return new URL(e).host||e}catch{return e}}function yb(e,t=Date.now()){let n=xo.get(ko(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<lu)throw new uu(ko(e),lu-r);n.state="half-open"}}function du(e){let t=xo.get(ko(e));t&&(t.failures=0,t.state="closed")}function bb(e,t=Date.now()){let n=ko(e),r=xo.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=C_&&(r.state="open",r.openedAt=t)),xo.set(n,r)}function Rb(e,t=Date.now()){let n=xo.get(ko(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<lu:!1}var xo,C_,lu,uu,pu=y(()=>{"use strict";xo=new Map,C_=5,lu=3e4;uu=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});function Sb(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function x_(e,t,n,r){e&&tn({limit_type:"primary",retry_after_seconds:Sb(r),api_method:t,api_url:n,provider:e})}function k_(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Jr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Bm(r),e.status===429&&x_(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function T_(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=Sb(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function sn(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=w_,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let b=e.includes("?")?"&":"?";d=`${e}${b}version=${encodeURIComponent(bn)}`}let p={"User-Agent":`Octocode-MCP/${bn}`,...i},f=globalThis.fetch;if(!f)throw new Error(Jr.FETCH_NOT_AVAILABLE.message);yb(d);let m,h=n+1;for(let b=1;b<=h;b++){if(c?.aborted)throw new Error("Request aborted");try{let x=await f(d,{method:s,headers:p,signal:c});if(!x.ok)throw k_(x,s,d,u,l);if(x.status===204)return du(d),null;let S=await x.json();return du(d),S}catch(x){let S=x;if(c?.aborted||x instanceof Error&&x.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw x;if(m=x instanceof Error?x:new Error(String(x)),b===h)break;let T=T_(b,r,o,S);await new Promise(L=>setTimeout(L,T))}}throw bb(d),new Error(Jr.FETCH_FAILED_AFTER_RETRIES.message(h,m?.message||""))}var w_,Pb=y(()=>{"use strict";ms();Tt();hs();pu();w_=6e4});import{z as A}from"zod";var Ys,E_,Cb,v_,wb=y(()=>{"use strict";Ys=A.looseObject({name:A.string(),version:A.string(),repository:A.union([A.string(),A.object({url:A.string().optional(),type:A.string().optional(),directory:A.string().optional()})]).optional(),main:A.string().optional(),module:A.string().optional(),type:A.string().optional(),exports:A.unknown().optional(),types:A.string().optional(),typings:A.string().optional(),description:A.string().optional(),keywords:A.array(A.string()).optional(),license:A.union([A.string(),A.object({type:A.string().optional()})]).optional(),homepage:A.string().optional(),author:A.union([A.string(),A.object({name:A.string().optional(),email:A.string().optional(),url:A.string().optional()})]).optional(),maintainers:A.array(A.object({name:A.string().optional(),email:A.string().optional()})).optional(),engines:A.record(A.string(),A.string()).optional(),dependencies:A.record(A.string(),A.string()).optional(),devDependencies:A.record(A.string(),A.string()).optional(),peerDependencies:A.record(A.string(),A.string()).optional(),time:A.record(A.string(),A.string().optional()).optional()}),E_=A.looseObject({package:A.looseObject({name:A.string().nullish(),version:A.string().nullish(),description:A.string().nullish(),links:A.looseObject({npm:A.string().nullish(),homepage:A.string().nullish(),repository:A.string().nullish()}).nullish()}),score:A.looseObject({final:A.number().nullish(),detail:A.looseObject({quality:A.number().nullish(),popularity:A.number().nullish(),maintenance:A.number().nullish()}).nullish()}).nullish()}),Cb=A.looseObject({objects:A.array(E_),total:A.union([A.number(),A.string()]).optional()}),v_=A.union([A.string(),A.boolean(),A.number(),A.null(),A.record(A.string(),A.unknown())])});async function Ob(){if(Xs)return Xs;try{let e=await Ks("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return Xs=t,t}}catch{}return Xs=Js,Js}function En(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function st(e){return e===void 0?0:B(e)}async function Lb(e){try{let t=`${L_}/${encodeURIComponent(e)}`,n=await sn(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:st(n)}}catch{return{rawResponseChars:0}}}function Zs(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Ab(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function A_(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function __(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function xb(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function kb(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function I_(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function fu(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=En(e.repository):(e.repository.url&&(r=En(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:I_(e),...o?{repositoryDirectory:o}:{},...xb(e.exports)?{exports:xb(e.exports)}:{},...kb(e.bin,e.name)?{bin:kb(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function F_(e){return typeof e.links?.repository=="string"?En(e.links.repository):typeof e.repository=="string"?En(e.repository):typeof e.repository?.url=="string"?En(e.repository.url):null}function M_(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:F_(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function _b(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function Ib(e){try{let t=await Ob(),n=_b(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await sn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=st(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await sn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:st(i)}}catch{return{rawResponseChars:0}}}async function mu(e,t,n){let[r,o]=await Promise.all([Lb(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Ib(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function ea(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function D_(e,t){try{let n=await Ks("view",[e,"--json"],{timeout:O_});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...ea(c)?{}:{errorDetail:c},rawResponseChars:st(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=st(o),s=Ys.safeParse(o);return s.success?{pkg:fu(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...ea(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function N_(e,t){try{let n=await Ob(),r=_b(e),o=`${n}/${r}/latest`,i;try{i=await sn(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=st(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=Ys.safeParse(i);return a.success?{pkg:fu(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...ea(r)?{}:{errorDetail:r},rawResponseChars:0}}}function G_(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Fb(e,t){let n=0,r;for(let o of G_(e)){let i;try{i=await sn(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);ea(l)||(r=l);continue}if(n+=st(i),!i||typeof i!="object")continue;let s=Ys.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:fu(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function hu(e,t=!1){let[n,r]=await Promise.allSettled([D_(e,t),N_(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?mu(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function H_(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await hu(e,t);if(!r){if(o){let s=Ab(o);if(s&&n){let a=await Fb(e,t);if(a.pkg){let c=await mu(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function z_(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ks("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:st(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=st(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((m,h)=>{let b=m?.score?.final??0;return(h?.score?.final??0)-b}).slice(r,r+t),d=await Promise.all(u.map(async m=>{if(!m||typeof m!="object")return null;let h=m;if(!h.name)return null;if(n){let b=await hu(h.name,!0);if(b.pkg)return b}return{pkg:M_(h),rawResponseChars:0}})),p=d.map(m=>m?.pkg).filter(m=>!!m),f=d.reduce((m,h)=>m+(h?.rawResponseChars??0),0);return{packages:p,totalFound:a.length,rawResponseChars:c+f}}async function Q_(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Js}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await sn(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(m){return{error:`NPM registry search failed: ${m instanceof Error?m.message:String(m)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=st(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Cb.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(h=>h.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((m,h)=>{let b=m.score?.final??0;return(h.score?.final??0)-b}).map(m=>m.package).filter(m=>typeof m.name=="string"&&m.name.length>0).slice(0,t),d=await Promise.all(u.map(async m=>{if(n){let h=await hu(m.name,!0);if(h.pkg)return h}return{pkg:{name:m.name,npmUrl:(m.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(m.name)}`,repoUrl:m.links?.repository&&typeof m.links.repository=="string"?En(m.links.repository):null,version:m.version??"unknown",source:"registry",...m.description?{description:m.description}:{},...m.links?.homepage?{homepage:m.links.homepage}:{}},rawResponseChars:0}})),p=d.map(m=>m.pkg).filter(m=>!!m),f=d.reduce((m,h)=>m+h.rawResponseChars,0);return{packages:p,totalFound:__(c.data.total,p.length),rawResponseChars:a+f}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Tb(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await sn(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:st(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:st(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?En(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:st(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Eb(e,t,n,r=0){try{let o=await z_(e,t,n,r);if(!("error"in o))return o}catch{}return Q_(e,t,n,r)}async function vb(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):Lb(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Ib(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function Mb(e,t,n,r=0){let o=We("npm-search",{name:e,limit:t,metadata:n,from:r});return Ve(o,async()=>{if(Rb(Js)){if(r===0&&t===1&&Zs(e)){let u=await Fb(e,n);if(u.pkg){let d=await mu(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await Tb(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Zs(e)){let l=await H_(e,n,t===1);if("error"in l){if(!Ab(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Eb(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return vb(s);let a=A_(e);if(a!==e){let l=await Eb(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return vb(l)}let c=await Tb(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}var Js,O_,Xs,L_,Db=y(()=>{"use strict";gb();Pb();nn();pu();wb();ue();Js="https://registry.npmjs.org",O_=3e3,Xs=null;L_="https://api.npmjs.org/downloads/point/last-week"});async function Nb(e){let t=Zs(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Mb(e.name,n,!0,r)}var Gb=y(()=>{"use strict";Db()});function B_(e){return"error"in e}function ta(e){return"npmUrl"in e}function $_(e){return ta(e)&&e.path?e.path:e.name}function j_(e){return ta(e)?e.repoUrl:e.repository}function U_(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function q_(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function Hb(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function zb(e,t){let n=Hb(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function W_(e){let t=$_(e),n=q_(j_(e)),r={name:t};ta(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=U_(ta(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=zb(n,o);return i&&(r.next=i),r}function V_(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=Hb(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:zb(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...p}=i;return{...p,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function K_(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function Qb(e){return ce(e.queries,async t=>{try{if(!t.packageName)return M("Package name is required for package search",t);let n=await Nb({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(B_(n))return M(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(W_),i=o.length>0,s=r.length>1||n.totalFound>1,a=K_(t,n.totalFound,o.length,s),l={...V_(o),pagination:a};return Fe(t,l,i,O.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return M(n,t,{toolName:O.PACKAGE_SEARCH})}},{toolName:O.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var Bb=y(()=>{"use strict";Gb();He();ze();ye()});async function $b(e){let{queries:t}=e;return ce(t||[],async n=>Ke({toolName:O.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Ne(Jn,n);return r.ok===!1?r.error:await Si(r.data)}}),{toolName:O.LOCAL_FETCH_CONTENT,finalize:Y_()},e)}function Y_(){return({results:e})=>{let t={results:X_(e)},n=As(t.results);n&&(t.base=n);let r=_s(t.results);return r&&(t.shared=r),{structuredContent:ut(t),text:J_(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function X_(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function J_(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=wn({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(wn({shared:e.shared},["shared"]).trimEnd()),t.join(`
31
+ `)}function SI(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function PI(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Xr(n))continue;let r=yc(n.patchPagination);if(r?.hasMore)return r}}function xI(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Xr(n))continue;let r=yc(n.bodyPagination);if(r?.hasMore)return r}}function CI(e,t,n,r){let o={},i=yc(e.bodyPagination),s=gc(e.filePagination),a=gc(e.commentPagination),c=gc(e.commitPagination),l=PI(e),u=xI(e),d=SI(n);i&&(o.body={...i,nextQuery:Cp(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:hc(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:hc(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:Hi(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:hc(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Cp(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return Xr(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Hi(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function wI(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function xP(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?RI(s):s,c=n.body?nr(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,p=bP(e,t,n,r),h=Array.isArray(p.changedFiles)?p.changedFiles.find(S=>S.path)?.path:void 0,y={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:fc(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:SP(t,i,n,h)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...p,...fP(e,t,n),...hP(e,t,n),...gP(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},b=CI(y,t,n,i);return wI(y),b&&(y.contentPagination=b),y}var CP=f(()=>{"use strict";yP();RP();PP();Qi()});async function wP(e,t,n){let r=n(),o={...t},i=pP(o),s=o.prNumber!==void 0;if(s||(o.content=void 0,o.reviewMode=void 0),!(o.keywordsToSearch?.length||o.owner||o.repo||o.author||o.assignee||o.prNumber&&o.owner&&o.repo))return N("At least one valid search parameter, filter, or PR number is required.",e);let c=await Jt(o,()=>r.provider.searchPullRequests(PS(o)));if(c.ok===!1)return c.result;let l=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:u,resultData:d}=xS(c.response.data,{includeFileChanges:l});o.prNumber!==void 0&&delete d.pagination;let m=!s&&(!!e.content||!!e.reviewMode),p={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},h=o.minify==="standard",g=!0,y=u.map(S=>xP(S,o,m?p:i,h,g));d.pull_requests=y,!s&&o.concise===!0&&(d.pull_requests=y.map(S=>{let C=S;return`#${C.number} ${C.title}`}));let b=y.length>0;return Ce(o,d,b,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}var kP=f(()=>{"use strict";pe();De();Wr();xn();mP();CP()});async function TP(e){let{queries:t,authInfo:n}=e,r=mt(n);return me(t,async(o,i)=>{try{let s=st(jn,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?JS(o,s.data,n):a==="issues"?cP(o,s.data,n):a==="commits"?uP(o,s.data,n):wP(o,s.data,r)}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","total_count","error"]},e)}var EP=f(()=>{"use strict";pe();Xe();De();xn();ZS();lP();dP();kP();cu()});function vP(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function AP(e){return!!(e.keywords&&e.keywords.length>0)}function LP(e){return!!(AP(e)||vP(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function OP(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function _P(e){let t=vP(e),n=AP(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:OP(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:OP(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}var FP=f(()=>{"use strict"});function IP(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var MP=f(()=>{"use strict"});function NP(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function GP(e,t){return[...e].sort((n,r)=>{let o=kI(n,r,t.sort);if(o!==0)return o;let i=DP(r,t)-DP(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:wp(n).localeCompare(wp(r))})}function kI(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return IP(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function DP(e,t){let n=TI(t),r=wp(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function TI(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function wp(e){return`${e.owner}/${e.repo}`}var HP=f(()=>{"use strict";MP()});function kp(e){return{currentPage:e.currentPage,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 Tp(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function Ep(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function QP(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??j(n.response.data??n.response)),0)}var Op=f(()=>{"use strict";ue()});function EI(e){let t=e,n={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(n).filter(([,r])=>r!==void 0))}function OI(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"heuristic"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"heuristic"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(EI),...o?{next:o}:{}}}}async function jP(e){let{queries:t,authInfo:n}=e,r=mt(n);return me(t,async(o,i)=>{try{if(!LP(o))return N("At least one repository search term or filter is required.",o);let s=r(),a=_P(o),{successes:c,failures:l}=await LR(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(bS(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?Ba(w.response,o):ze(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=GP(NP(u.flatMap(w=>RS(w.response.data.repositories))),o),h=m!=null?p.slice(0,m):p,g=u.length===1?u[0]:void 0,b=u.length>1?Ep(u,p.length):g?.response.data.pagination,S=b?kp(b):void 0,C=h.length>0,E=OI({repositories:h,pagination:S},o),T=Tp(d),_=T?{...E.data,warnings:T}:E.data;return Ce(o,_,C,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:QP([...u,...d])})}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var BP=f(()=>{"use strict";pe();Xe();De();Wr();xn();FP();HP();Op();Op()});function vI(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n: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 n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function AI(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&mi(o))continue;let i=r.files.filter(a=>!Mr(a)),s=r.folders.filter(a=>!mi(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function zP(e){let{queries:t,authInfo:n}=e,r=mt(n);return me(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,l=c??await s.provider.resolveDefaultBranch(a),u=await Jt(o,()=>s.provider.getRepoStructure(fp(o,l))),d=l,m;if(u.ok===!1&&c){let C=u.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let T=await s.provider.resolveDefaultBranch(a);if(T!==c){let _=await Jt(o,()=>s.provider.getRepoStructure(fp(o,T)));_.ok!==!1&&(u=_,d=T,m=`Branch/ref '${c}' was not found. Showing '${T}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(u.ok===!1)return vI(u.result,o);let p=AI(u.response.data.structure),h=Object.keys(p).length>0,g=ES(u.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let b=g.structure?.find(C=>(C.files?.length??0)>0),S=b?b.dir==="."?b.files[0]:`${b.dir}/${b.files[0]}`:void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...o.branch?{branch:o.branch}:{}},why:"Read the first listed file",confidence:"heuristic"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...o.branch?{branch:o.branch}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},Ce(o,g,h,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return ze(s,o,"Failed to explore repository structure",v.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:v.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var $P=f(()=>{"use strict";pe();Xe();fi();De();Wr();xn()});import{existsSync as UP}from"fs";import{delimiter as LI,dirname as _I,join as qP}from"path";function WP(){return process.platform==="win32"?"npm.cmd":"npm"}function FI(){let e=_I(process.execPath);return qP(e,WP())}function II(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function MI(){let e=(process.env.PATH??"").split(LI).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...II()])]}function DI(){let e=FI();if(UP(e))return{command:process.execPath,argsPrefix:[e]};let t=WP();for(let n of MI()){let r=qP(n,t);if(UP(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function or(e,t,n={}){if(!NI.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=IR(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=DI(),c=await er(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:GI});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var NI,GI,ji=f(()=>{"use strict";Ua();NI=["view","search","ping","config","whoami"],GI=[...vi,..._R]});async function Sc(){if(Rc)return Rc;try{let e=await or("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return Rc=t,t}}catch{}return Rc=Jr,Jr}var Jr,Rc,Bi=f(()=>{"use strict";ji();Jr="https://registry.npmjs.org",Rc=null});function $i(e){try{return new URL(e).host||e}catch{return e}}function VP(e,t=Date.now()){let n=zi.get($i(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<vp)throw new Ap($i(e),vp-r);n.state="half-open"}}function Lp(e){let t=zi.get($i(e));t&&(t.failures=0,t.state="closed")}function KP(e,t=Date.now()){let n=$i(e),r=zi.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=HI&&(r.state="open",r.openedAt=t)),zi.set(n,r)}function YP(e,t=Date.now()){let n=zi.get($i(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<vp:!1}var zi,HI,vp,Ap,_p=f(()=>{"use strict";zi=new Map,HI=5,vp=3e4;Ap=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});import{z as L}from"zod";var Pc,QI,XP,jI,xc=f(()=>{"use strict";Pc=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),QI=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),XP=L.looseObject({objects:L.array(QI),total:L.union([L.number(),L.string()]).optional()}),jI=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});function JP(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function zI(e,t,n,r){e&&Sn({limit_type:"primary",retry_after_seconds:JP(r),api_method:t,api_url:n,provider:e})}function $I(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(ni.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Oy(r),e.status===429&&zI(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function UI(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=JP(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Nt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=BI,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let y=e.includes("?")?"&":"?";d=`${e}${y}version=${encodeURIComponent(Wn)}`}let m={"User-Agent":`Octocode-MCP/${Wn}`,...i},p=globalThis.fetch;if(!p)throw new Error(ni.FETCH_NOT_AVAILABLE.message);VP(d);let h,g=n+1;for(let y=1;y<=g;y++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(d,{method:s,headers:m,signal:c});if(!b.ok)throw $I(b,s,d,u,l);if(b.status===204)return Lp(d),null;let S=await b.json();return Lp(d),S}catch(b){let S=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw b;if(h=b instanceof Error?b:new Error(String(b)),y===g)break;let C=UI(y,r,o,S);await new Promise(E=>setTimeout(E,C))}}throw KP(d),new Error(ni.FETCH_FAILED_AFTER_RETRIES.message(g,h?.message||""))}var BI,Cc=f(()=>{"use strict";la();ct();da();_p();BI=6e4});function kn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function Ke(e){return e===void 0?0:j(e)}async function wc(e){try{let t=`${qI}/${encodeURIComponent(e)}`,n=await Nt(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Ke(n)}}catch{return{rawResponseChars:0}}}function ZP(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function ex(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function WI(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function kc(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=kn(e.repository):(e.repository.url&&(r=kn(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:WI(e),...o?{repositoryDirectory:o}:{},...ZP(e.exports)?{exports:ZP(e.exports)}:{},...ex(e.bin,e.name)?{bin:ex(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function VI(e){return typeof e.links?.repository=="string"?kn(e.links.repository):typeof e.repository=="string"?kn(e.repository):typeof e.repository?.url=="string"?kn(e.repository.url):null}function tx(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:VI(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function Fp(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function nx(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}var qI,Ip=f(()=>{"use strict";Cc();ue();qI="https://api.npmjs.org/downloads/point/last-week"});function Mp(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}async function Dp(e){try{let t=await Sc(),n=Fp(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Nt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ke(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Nt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ke(i)}}catch{return{rawResponseChars:0}}}async function Ec(e,t,n){let[r,o]=await Promise.all([wc(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Dp(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function Tc(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function YI(e,t){try{let n=await or("view",[e,"--json"],{timeout:KI});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...Tc(c)?{}:{errorDetail:c},rawResponseChars:Ke(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Ke(o),s=Pc.safeParse(o);return s.success?{pkg:kc(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...Tc(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function XI(e,t){try{let n=await Sc(),r=Fp(e),o=`${n}/${r}/latest`,i;try{i=await Nt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Ke(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=Pc.safeParse(i);return a.success?{pkg:kc(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...Tc(r)?{}:{errorDetail:r},rawResponseChars:0}}}function JI(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Np(e,t){let n=0,r;for(let o of JI(e)){let i;try{i=await Nt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);Tc(l)||(r=l);continue}if(n+=Ke(i),!i||typeof i!="object")continue;let s=Pc.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:kc(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Oc(e,t=!1){let[n,r]=await Promise.allSettled([YI(e,t),XI(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?Ec(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function rx(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Oc(e,t);if(!r){if(o){let s=Mp(o);if(s&&n){let a=await Np(e,t);if(a.pkg){let c=await Ec(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}var KI,Gp=f(()=>{"use strict";ji();Cc();xc();Bi();Ip();KI=3e3});async function ZI(e,t,n,r=0){let o=Math.max(t+r,t),i=await or("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Ke(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Ke(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((h,g)=>{let y=h?.score?.final??0;return(g?.score?.final??0)-y}).slice(r,r+t),d=await Promise.all(u.map(async h=>{if(!h||typeof h!="object")return null;let g=h;if(!g.name)return null;if(n){let y=await Oc(g.name,!0);if(y.pkg)return y}return{pkg:tx(g),rawResponseChars:0}})),m=d.map(h=>h?.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function e0(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Jr}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Nt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(h){return{error:`NPM registry search failed: ${h instanceof Error?h.message:String(h)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ke(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=XP.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((h,g)=>{let y=h.score?.final??0;return(g.score?.final??0)-y}).map(h=>h.package).filter(h=>typeof h.name=="string"&&h.name.length>0).slice(0,t),d=await Promise.all(u.map(async h=>{if(n){let g=await Oc(h.name,!0);if(g.pkg)return g}return{pkg:{name:h.name,npmUrl:(h.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(h.name)}`,repoUrl:h.links?.repository&&typeof h.links.repository=="string"?kn(h.links.repository):null,version:h.version??"unknown",source:"registry",...h.description?{description:h.description}:{},...h.links?.homepage?{homepage:h.links.homepage}:{}},rawResponseChars:0}})),m=d.map(h=>h.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+g.rawResponseChars,0);return{packages:m,totalFound:nx(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Hp(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await Nt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Ke(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ke(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?kn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Ke(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Qp(e,t,n,r=0){try{let o=await ZI(e,t,n,r);if(!("error"in o))return o}catch{}return e0(e,t,n,r)}async function jp(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):wc(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Dp(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}var ox=f(()=>{"use strict";ji();Cc();xc();Bi();Ip();Gp()});function Ui(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function ix(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function Bp(e,t,n,r=0){let o=Oe("npm-search",{name:e,limit:t,metadata:n,from:r});return He(o,async()=>{if(YP(Jr)){if(r===0&&t===1&&Ui(e)){let u=await Np(e,n);if(u.pkg){let d=await Ec(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await Hp(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Ui(e)){let l=await rx(e,n,t===1);if("error"in l){if(!Mp(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Qp(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return jp(s);let a=ix(e);if(a!==e){let l=await Qp(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return jp(l)}let c=await Hp(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}var sx=f(()=>{"use strict";ji();ut();_p();xc();Bi();Gp();ox()});var ax=f(()=>{"use strict";Bi();sx()});async function cx(e){let t=Ui(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Bp(e.name,n,!0,r)}var lx=f(()=>{"use strict";ax()});function n0(e){return"error"in e}function vc(e){return"npmUrl"in e}function r0(e){return vc(e)&&e.path?e.path:e.name}function o0(e){return vc(e)?e.repoUrl:e.repository}function i0(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function s0(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function zp(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function ux(e,t){let n=zp(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghHistoryResearch",query:{type:"releases",owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function a0(e){let t=r0(e),n=s0(o0(e)),r={name:t};vc(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=i0(vc(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=ux(n,o);if(i&&(r.next=i),r.version&&zp(n)){let s=`npm version ${r.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.`;r.warnings=[s],r.diagnostics=[{level:"warning",code:"npmRepoTagDivergence",message:s}]}return r}function c0(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=zp(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:ux(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function l0(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function dx(e){return me(e.queries,async t=>{try{if(!t.packageName)return N("Package name is required for package search",t);let n=await cx({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(n0(n))return N(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(a0),i=o.length>0,s=r.length>1||n.totalFound>1,a=l0(t,n.totalFound,o.length,s),l={...c0(o),pagination:a};return Ce(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return N(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var px=f(()=>{"use strict";lx();Xe();De();pe()});import{redactPath as qi}from"@octocodeai/octocode-engine/pathUtils";var mx=f(()=>{"use strict"});var ht,Ac=f(()=>{"use strict";ja();Jn();mx();ht={pathValidationFailed:(e,t,n)=>new Qe(U.PATH_VALIDATION_FAILED,t||`Path validation failed: ${qi(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=qi(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Qe(U.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Qe(U.FILE_READ_FAILED,`Failed to read file: ${qi(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Qe(U.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Qe(U.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${qi(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Qe(U.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Qe(U.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new Qe(U.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Qe(U.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});import fx from"path";import{pathValidator as hx}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as gx}from"@octocodeai/config";function u0(e=gx().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&hx.addAllowedRoot(t)}function gt(e,t){if(!e.path?.trim()){let s=ht.pathValidationFailed("","path is required");return{isValid:!1,errorResult:N(s,e,{toolName:t})}}u0();let n=process.env.WORKSPACE_ROOT?.trim()||gx().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=fx.isAbsolute(r)?r:fx.resolve(n,r),i=hx.validate(o);if(!i.isValid){let s=ht.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:N(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}var Zt=f(()=>{"use strict";Ac();Xd()});var Gt,Wi=f(()=>{"use strict";Gt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function yx(e,t){return n=>t}var bx=f(()=>{"use strict"});import{open as d0,readFile as p0,stat as m0}from"fs/promises";function $p(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Up(e,t,n){return{...e,...$p(t,n)}}function Rx(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))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(t&&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(t&&r)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&&r)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 o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function Sx(e,t){try{return{fileStats:await m0(t)}}catch(n){let r=ht.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Px(e,t){return t>Gt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function xx(e,t,n){let r=ht.fileTooLarge(e.path,n,Gt.LARGE_FILE_THRESHOLD_KB);return N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function Cx(e,t){let n=ht.binaryFileUnsupported(e.path);return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function wx(e){let n=Buffer.alloc(8192),r;try{r=await d0(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(yx("binary sample handle close",void 0))}}async function kx(e,t){try{return{content:await p0(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?ht.fileAccessFailed(e.path,r):ht.fileReadFailed(e.path,r);return{errorResult:N(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Tx(e,t){return{status:"empty",errorCode:U.NO_MATCHES,totalLines:t}}var Lc=f(()=>{"use strict";Wi();pe();Zt();Ac();Jn();bx()});function f0(e,t,n){let r=ya(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Tx(e,n)};let o=r.lines.join(`
32
+ `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(l=m.start,u=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function h0(e){return e.startLine!==void 0&&e.endLine!==void 0}function g0(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:U.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \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:U.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
33
+ `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function Ex(e,t,n){let r=t.split(`
34
+ `),o=It(t);return e.matchString?f0(e,r,o):h0(e)?g0(e,r,o):{resultContent:t,isPartial:!1}}var Ox=f(()=>{"use strict";fd();Hr();Jn();Lc()});async function vx(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",d=s;if(s!==void 0){let g=await wa(e,l,s,r);u=g.chunkMode,d=g.length}let m=Pa(e,l,d,s!==void 0?{pageSize:s}:void 0),p;if(m.hasMore&&u==="char-limit"&&xa(m.paginatedContent)){let g=m.charOffset+m.charLength;p=await Ca(e,g,r)}let h=Ws("localGetFileContent",{path:r,charLength:s??m.charLength,minify:t.minify},m);return{windowedContent:m.paginatedContent,pagination:m,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:p,next:h,showPagination:s!==void 0||i>0||a}}async function Ax(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=await vx(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,contentView:s,...d&&{isPartial:d},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...yd(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}async function qp(e,t,n,r,o,i,s){let a=await vx(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...$p(r,o),...a.showPagination&&{pagination:{...yd(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function Lx(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}var _x=f(()=>{"use strict";Ee();bd();Rd();Be();Lc()});import{ContentSanitizer as y0}from"@octocodeai/octocode-engine/contentSanitizer";async function _c(e){let t=Vn();try{let n=gt(e,v.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=Rx(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await Sx(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await wx(o))return W(Cx(e,o),c);if(Px(e,l))return W(xx(e,o,l),c);let{content:u,errorResult:d}=await kx(e,o);if(d||u===void 0)return d;let m=y0.sanitizeContent(u,i),p=m.content,h=p.length,g=Buffer.byteLength(p,"utf-8"),y=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,b=e.minify,S=b==="standard"||b==="symbols",C=S?"standard":"none",E;if(b==="symbols"){let M=D.extractSignatures(p,i);if(M===null){let A=ba(p,i);if(A!==null)return W(await qp(e,A,It(p),h,g,y,t),h);E=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(M!==null){let A=It(p),q=D.applyContentViewMinification(M,i);return W(await qp(e,q,A,h,g,y,t),h)}}let T=It(p),_=Ex(e,p,t),w=M=>{let A=[...E?[E]:[],...y?[y]:[]];if(A.length===0)return M;let q=M.warnings??[];return{...M,warnings:[...q,...A]}};if(_.earlyResult){let M=_.earlyResult.content,A=S&&typeof M=="string"?{..._.earlyResult,content:D.applyContentViewMinification(M,i)}:_.earlyResult;return W(Up(w(Wp(Lx(A,C),e,T)),h,g),h)}let G=await Ax(e,_,s,T,t,S,C);return W(Up(w(Wp(G,e,T)),h,g),h)}catch(n){return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT})}}function Wp(e,t,n){return e}var Fc=f(()=>{"use strict";Ee();Hr();Sa();pe();Zt();ue();Ra();Lc();Ox();_x()});async function Fx(e){let{queries:t}=e;return me(t||[],async n=>pt({toolName:v.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=st(Bn,n);return r.ok===!1?r.error:await _c(r.data)}}),{toolName:v.LOCAL_FETCH_CONTENT,finalize:b0()},e)}function b0(){return({results:e})=>{let t={results:R0(e)},n=Ha(t.results);n&&(t.base=n);let r=Qa(t.results);return r&&(t.shared=r),{structuredContent:dt(t),text:S0(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function R0(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function S0(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=Xn({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Xn({shared:e.shared},["shared"]).trimEnd()),t.join(`
42
35
  `).trimEnd()+`
43
- `}var jb=y(()=>{"use strict";ye();He();ur();_l();Pi();Wi();ze();rn();Pi()});async function Ub(e){let{queries:t}=e;return ce(t||[],async n=>Ke({toolName:O.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Ne(Zn,n);return r.ok===!1?r.error:await jn(r.data)}}),{toolName:O.LOCAL_FIND_FILES},e)}var qb=y(()=>{"use strict";Ki();ye();He();ui();ze();rn();ui()});async function Wb(e){let{queries:t}=e;return ce(t||[],async n=>Ke({toolName:O.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Ne(Kt,n);return r.ok===!1?r.error:await kt(r.data)}}),{toolName:O.LOCAL_RIPGREP},e)}var Vb=y(()=>{"use strict";vr();ye();He();ci();ze();rn();si()});async function Kb(e){let{queries:t}=e;return ce(t||[],async n=>Ke({toolName:O.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Ne(er,n);return r.ok===!1?r.error:await di(r.data)}}),{toolName:O.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var Yb=y(()=>{"use strict";Xi();ye();He();pi();ze();rn();pi()});import{safeReadFile as Z_}from"@octocodeai/octocode-engine/lsp/validation";function To(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Jb(e,t,n){if(t<=0)return e;let r=await Z_(e.uri);if(!r)return e;let o=_r(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
44
- `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function eI(e,t){return Promise.all(e.map(async n=>({...n,from:await Jb(n.from,t,n.fromRanges)})))}async function tI(e,t){return Promise.all(e.map(async n=>({...n,to:await Jb(n.to,t)})))}async function gu(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Xb};try{let i=await e.getIncomingCalls(t),s=o>0?await eI(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=To(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),gu(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function yu(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Xb};try{let i=await e.getOutgoingCalls(t),s=o>0?await tI(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=To(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),yu(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var Xb,Zb=y(()=>{"use strict";Ir();Xb={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function rI(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function eR(e,t){if(t===void 0||t==="progressIdle")return e;let n=rI(e);if(!n||!nI.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,warnings:[...e.warnings??[],r]}}var nI,tR=y(()=>{"use strict";nI=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as oI,stat as iI}from"node:fs/promises";import{SymbolResolver as sI,SymbolResolutionError as aI}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as na}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function bu(e,t){let n=e.uri,r=Be({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await iI(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:na.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:na.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await oI(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:na.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function nR(e,t){let n=await bu(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 sI({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:cI(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof aI)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:na.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function cI(e){return{start:e,end:{line:e.line,character:e.character}}}var rR=y(()=>{"use strict";Ft()});import Ot from"node:path";import{readFile as lI}from"node:fs/promises";import{fileURLToPath as uI}from"node:url";import{acquirePooledClient as oa,isLanguageServerAvailable as ia,unavailableHintFor as dI}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as pI}from"@octocodeai/octocode-engine/lsp/config";import{resolveImportAliasDefinitions as fI}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Pu}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function mI(e){return Ru||(Ru=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),Ru.has(Ot.extname(e).toLowerCase())}function vn(e,t){let n=pI(e),r=dI(n,void 0);throw new _e(z.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function gI(e,t){let n=e.startsWith("file://")?uI(e):e;return Ot.isAbsolute(n)?n:Ot.resolve(t,n)}function cR(){return[...D.getSupportedJsTsExtensions(),...hI]}function yI(){return cR().map(e=>`**/*.${e}`)}async function RI(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:yI(),excludeDir:[...bI],maxSnippetChars:1})).files[0]?.path}catch{return}}async function SI(e,t){if(e.uri)return gI(e.uri,t);let n=await RI(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:cR(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function PI(e){return e instanceof Error?e.message:String(e)}function CI(e,t){if(!mI(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}async function uR(e){return ce(e.queries||[],async t=>Ke({toolName:rt,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await GI(t);return kI(TI(t,n))}}),{toolName:rt,minQueryTimeoutMs:3e4},e)}function kI(e){return U(e,B(e))}function TI(e,t){return e.format!=="compact"||!EI(t)?t:vI(t)}function EI(e){return On(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&On(e.payload)}function vI(e){return{...e,format:"compact",payload:OI(e.payload)}}function OI(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(oR)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(AI)}:{locations:(e.locations??[]).map(oR)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:dR(e.root)}:{},direction:e.direction,calls:e.calls.map(_I),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(LI)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function LI(e){if(!On(e))return String(e);let t=Xe(e,"line"),n=Xe(e,"character"),r=Xe(e,"endLine"),o=jt(e,"kind"),i=jt(e,"name"),s=Xe(e,"childCount"),a=jt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function oR(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${fR(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function AI(e){if(!On(e))return String(e);let t=jt(e,"uri"),n=Xe(e,"firstLine"),r=Xe(e,"firstCharacter"),o=Xe(e,"count"),i=pR(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function _I(e){if(!On(e))return String(e);let t=jt(e,"direction"),n=dR(e.item),r=pR(e,"ranges").map(II).join(","),o=Xe(e,"rangeCount"),i=Xe(e,"rangeSampleCount"),s=jt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${fR(s,180)}`:""].filter(Boolean).join(" ")}function dR(e){if(!On(e))return String(e);let t=jt(e,"name"),n=jt(e,"kind"),r=jt(e,"uri"),o=Xe(e,"line"),i=Xe(e,"endLine"),s=Xe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function II(e){return On(e)?`${Xe(e,"line")}:${Xe(e,"character")}`:String(e)}function On(e){return typeof e=="object"&&e!==null}function jt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Xe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function pR(e,t){let n=e[t];return Array.isArray(n)?n:[]}function fR(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}async function NI(e,t,n){if(typeof e.openDocument=="function")try{let r=Ot.extname(t.uri).slice(1),o=iR.includes(r)?iR:[r],i=await kt({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:MI,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=Ot.isAbsolute(a)?a:Ot.join(n,a);if(Ot.resolve(c)!==Ot.resolve(t.uri))try{let l=await lI(c,"utf-8");if(l.length>DI)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function GI(e){if(e.type==="documentSymbols")return zI(e);if(e.type==="workspaceSymbol")return jI(e);if(e.type==="diagnostic")return WI(e);let t=await nR(e,rt);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return rF(e,a)}let n=e.workspaceRoot??await Pu(t.value.uri);await ia(t.value.uri,n)||vn(t.value.uri,e.type);let o=await oa(n,t.value.uri);o||vn(t.value.uri,e.type),FI.has(e.type)&&await NI(o,t.value,n);let i=o.getReadiness?.(),s=await HI(e,t.value,o);return eR(s,i)}async function HI(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?Su(e,t,"definition","definitionProvider",await fI({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):$t(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?Su(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):$t(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?Su(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):$t(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?QI(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):$t(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?BI(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):$t(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?$I(e,t,n):$t(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?qI(e,t,n):$t(e.type,t,"typeHierarchyProvider unsupported",!0)}}async function zI(e){let t=await bu(e,rt);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Pu(t.value.uri),r=await ia(t.value.uri,n),o=r?await oa(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=CI(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let b=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(b)?b:[],a="lsp"}else{let b=Jp(t.value.content,t.value.uri);b&&(s=b,a="markdown")}let l=a!==void 0;!l&&!r&&vn(t.value.uri,"documentSymbols");let u=YI(s),d=ZI(s),{pageItems:p,pagination:f}=Ln(u,e.page??1,e.itemsPerPage??sa),m=eF(u,b=>b.kind),h=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:p.length,topLevelSymbols:d,kinds:m},payload:{kind:"documentSymbols",symbols:p,...h?{empty:h}:{}},pagination:f}}function Su(e,t,n,r,o){let i=o.length>0,s=o.map(_c),{pageItems:a,pagination:c}=Ln(s,e.page??1,e.itemsPerPage??lR);return{type:e.type,uri:t.uri,resolvedSymbol:mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function QI(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?oF(r):void 0,i=o??r.map(_c),{pageItems:s,pagination:a}=Ln(i,e.page??1,e.itemsPerPage??lR),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function BI(e,t,n){let r=iF(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function $I(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return $t(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await gu(n,o,i,new Set([To(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await yu(n,o,i,new Set([To(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),p=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],f=p.map(S=>S.direction==="incoming"?tF(S,e.contextLines??0):nF(S,e.contextLines??0)),{pageItems:m,pagination:h}=Ln(f,e.page??1,e.itemsPerPage??wI),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",x=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Cu(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:x,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:h}}async function jI(e){let t=e.symbolName??"",n=Ot.resolve(e.workspaceRoot??process.cwd()),r=await SI(e,n);await ia(r,n)||vn(r,"workspaceSymbol");let i=await oa(n,r);if(i||vn(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{Ot.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${PI(u)}`}}}let a=UI(s),{pageItems:c,pagination:l}=Ln(a,e.page??1,e.itemsPerPage??sa);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function UI(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,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:ra(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function qI(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return $t(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=Ln(s,e.page??1,e.itemsPerPage??sa);return{type:e.type,uri:t.uri,resolvedSymbol:mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}async function WI(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Pu(t):process.cwd());await ia(t,n)||vn(t,"diagnostic");let o=await oa(n,t);if(o||vn(t,"diagnostic"),!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,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 i=await o.getDiagnostics(t),s=VI(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Ln(s,e.page??1,e.itemsPerPage??sa);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function VI(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>KI(r))}return[]}function KI(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}:{}}]:[]}function Ln(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function YI(e){let t=[];for(let n of e)mR(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function mR(e,t,n){if(!e||typeof e!="object")return;let r=e,o=JI(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:ra(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)&&XI.has(ra(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)mR(s,t,i)}}function JI(e){if(sR(e.range))return e.range;let t=e.location;return t&&sR(t.range)?t.range:void 0}function sR(e){if(!e||typeof e!="object")return!1;let t=e;return aR(t.start)&&aR(t.end)}function aR(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function ZI(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function eF(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function tF(e,t){let n=hR(e.fromRanges);return{direction:"incoming",item:Cu(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...gR(e.from,t)}}function nF(e,t){let n=hR(e.fromRanges);return{direction:"outgoing",item:Cu(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...gR(e.to,t)}}function Cu(e){return{name:e.name,kind:ra(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 hR(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=xI))break}return n}function gR(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function ra(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"}}function yR(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 rF(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:yR(e.type,t),reason:t}}}function $t(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:mn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:yR(e,n),reason:n}}}function oF(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 iF(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=>sF(r)).join(`
45
- `).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 sF(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 Ru,hI,bI,sa,lR,wI,xI,FI,MI,DI,iR,XI,bR=y(()=>{"use strict";ci();He();ue();rn();Yo();Gn();Zb();Gr();tR();rR();Ce();Ri();hI=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];bI=[".git","node_modules","dist","out","coverage","target"];sa=40,lR=40,wI=10,xI=8;FI=new Set(["references","callers","callees","callHierarchy","implementation"]),MI=12,DI=512*1024,iR=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];XI=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});async function SR(e){let t=aF(e),n=un.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(wu(),wR)),o=await r(n.data,{authInfo:e.authInfo});return cF(o)}function aF(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function cF(e){let t=lF(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function lF(e){return Ju(e)?{results:e.children.map(t=>RR(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:PR(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[RR(e,e.queryId??"oqlSearch-1")]}}function RR(e,t){let n=PR(e);return{id:e.queryId??t,...dF(e),data:n}}function PR(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||uF(d,u)){let{why:p,confidence:f,...m}=l;s[c]=m,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function uF(e,t){return e.why===t.why&&e.confidence===t.confidence}function dF(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var CR=y(()=>{"use strict";In();At()});var xu,xR=y(()=>{"use strict";ye();xu={hasTool(e){return ac(e)},getDescription(e){return sc[e]??""},getToolName(e){return O[e]??String(e)}}});function pF(e,t){return t.getToolName(e)}function mt(e,t,n){let r=pF(t,e);return{...n,name:r,description:ku(r,e)}}function fF(e=xu){let t=mt(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Di,inputSchema:Ni,executionFn:$y,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=mt(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Kn,inputSchema:Fi,executionFn:Gy,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=mt(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Bi,inputSchema:$i,executionFn:db,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=mt(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:zi,inputSchema:Qi,executionFn:lb,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=mt(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Xn,inputSchema:Gi,executionFn:tb,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=mt(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ji,inputSchema:Ui,executionFn:Qb,security:"remote",requiresServerRuntime:!0}}),a=mt(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Hr,inputSchema:Ii,executionFn:ly,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=mt(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Kt,inputSchema:ri,executionFn:Wb,security:"basic"}}),l=mt(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:er,inputSchema:Yi,executionFn:Kb,security:"basic"}}),u=mt(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Zn,inputSchema:Vi,executionFn:Ub,security:"basic"}}),d=mt(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Jn,inputSchema:qi,executionFn:$b,security:"basic"}}),p={name:rt,description:ku(rt,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:es,inputSchema:ts,executionFn:uR,security:"basic",requiresServerRuntime:!0}},f=mt(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:nr,inputSchema:ns,executionFn:Qg,security:"basic"}}),m={name:Vn,description:ku(Vn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:No,inputSchema:un,executionFn:SR,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},h=[t,n,r,o,i,s,a,c,l,u,d,p,f,...Nr()?[m]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:p,LOCAL_BINARY_INSPECT:f,OQL_SEARCH:m,ALL_TOOLS:h}}var ku,Qe,xY,kY,TY,EY,vY,OY,LY,AY,_Y,IY,FY,MY,DY,NY,kR,TR=y(()=>{"use strict";Ic();Mi();Fc();Hi();Mc();Dc();Nc();Wi();Ki();vr();Xi();Hc();rs();In();Bg();uy();Hy();jy();nb();ub();pb();Bb();jb();qb();Vb();Yb();bR();CR();Gr();_i();xR();ku=(e,t=xu)=>t.getDescription(e);Qe=fF(),xY=Qe.GITHUB_SEARCH_CODE,kY=Qe.GITHUB_FETCH_CONTENT,TY=Qe.GITHUB_VIEW_REPO_STRUCTURE,EY=Qe.GITHUB_SEARCH_REPOSITORIES,vY=Qe.GITHUB_SEARCH_PULL_REQUESTS,OY=Qe.PACKAGE_SEARCH,LY=Qe.GITHUB_CLONE_REPO,AY=Qe.LOCAL_RIPGREP,_Y=Qe.LOCAL_VIEW_STRUCTURE,IY=Qe.LOCAL_FIND_FILES,FY=Qe.LOCAL_FETCH_CONTENT,MY=Qe.LSP_GET_SEMANTIC_CONTENT,DY=Qe.LOCAL_BINARY_INSPECT,NY=Qe.OQL_SEARCH,kR=Qe.ALL_TOOLS});import{ContentSanitizer as mF}from"@octocodeai/octocode-engine/security";function Eu(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:ut(t.structuredContent)}}catch{}return gF(t)?yF(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=mF.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function gF(e){return oc()==="mcp"&&process.env[hF]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function yF(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:bF(e.structuredContent)},...t]}}function bF(e){let t=["structuredContent available"];if(Tu(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=RF(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Tu(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function RF(e){let t=0,n=0;for(let r of e)Tu(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Tu(e){return typeof e=="object"&&e!==null}function vu(e,t){let n=PF(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
46
- message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:SF,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Eu(r)}catch{return r}}function PF(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:CF(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function CF(e){try{return JSON.stringify(e)}catch{return}}var hF,SF,ER=y(()=>{"use strict";ur();Ct();hF="OCTOCODE_MCP_FULL_TEXT";SF="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as wF,withBasicSecurityValidation as xF}from"@octocodeai/octocode-engine/security";function vR(e,t){let n=wF(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function OR(e,t){let n=xF(r=>e(r),t);return(r,o)=>n(r,o)}var LR=y(()=>{"use strict"});function TF(e){let t=e;return n=>t(n)}function EF(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:TF(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function OF(e){return vF.find(t=>t.name===e)}async function Ou(e,t){let n=OF(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=LF(n,t);return await AF(n),_F(n),await IF(n,r)}catch(r){return vu(n.name,r)}}function LF(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function AF(e){e.requiresServerRuntime&&(aa||(aa=kF().catch(t=>{throw aa=null,t})),await aa),e.requiresProviders&&(ca||(ca=gg().then(()=>{}).catch(t=>{throw ca=null,t})),await ca)}function _F(e){if(!e.isLocal&&!e.isClone)return;let t=gt();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function IF(e,t){try{let n=e.security==="remote"?await FF(e,t):await MF(e,t);return Eu(n)}catch(n){return vu(e.name,n)}}async function FF(e,t){return vR(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function MF(e,t){return OR(e.execute,e.name)(t)}var aa,ca,kF,vF,AR=y(()=>{"use strict";no();Ol();Ct();TR();ER();LR();zc();aa=null,ca=null,kF=Hm;vF=kR.map(EF)});var _R=y(()=>{"use strict";zc();AR()});function Ee(e,t){return Ou(e,{queries:[{...DF,...t}]})}function an(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function mr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Eo(e){return typeof e=="string"?e:void 0}var DF,vo=y(()=>{"use strict";_R();DF={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function MR(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function Oo(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function DR(e){return e.structuredContent?.results?.[0]?.status}function NF(e,t){return e>0?[]:[P("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function NR(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function IR(...e){return e.map(NR).filter(Boolean).join("/")}function GF(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function FR(e){return NR(e).split("/").filter(Boolean).length}function HF(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function zF(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function QF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function BF(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(QF).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function $F(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(HF).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!BF(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(zF(o.path)))}function GR(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function jF(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function UF(e){return typeof e=="string"?[]:e.matches??[]}async function HR(e){switch(e.target){case"content":return VF(e);case"structure":return KF(e);case"files":return qF(e);default:return WF(e)}}async function qF(e){let t=wr(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Ee("ghSearchCode",t.query),r=Oo(n),o=new Set,i=[];for(let a of r?.files??[]){let c=GR(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Ae(e),path:c,entryType:"file"}))}let s=Dt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...la(n,i.length,"ghSearchCode"),...i.length>0?[P("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Ae(e)}]}}function Ae(e){return e.from??{kind:"github"}}async function WF(e){let t=wr(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Ee("ghSearchCode",t.query),r=Oo(n),o=[];for(let s of r?.files??[]){let a=GR(s),c=jF(s),l=UF(s);if(l.length===0){o.push({kind:"code",source:Ae(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Ae(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=wc(Dt(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...la(n,o.length,"ghSearchCode"),...o.length>0?[P("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Ae(e)}]}}async function VF(e){let{owner:t,repo:n}=MR(Ae(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=YF(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:et(e.scope)??"",type:"file",minify:o,...Ae(e).kind==="github"&&Ae(e).ref?{branch:Ae(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Ee("ghGetFileContent",s),c=Oo(a),l=o==="none"?"exact":o==="symbols"?"symbols":"compact",u=c?.pagination,d=c?.results??c?.files??[],p=d.map(m=>{let h=m.pagination??u,b=typeof h?.charOffset=="number",x={...m.startLine!==void 0?{startLine:m.startLine}:{},...m.endLine!==void 0?{endLine:m.endLine}:{},...b?{charOffset:h.charOffset,...typeof h.charLength=="number"?{charLength:h.charLength}:{}}:{}};return{kind:"content",source:Ae(e),path:m.path,content:m.content,contentView:l,...Object.keys(x).length?{range:x}:{}}}),f=u??d.find(m=>m.pagination)?.pagination;return{results:p,...f?.hasMore!==void 0?{pagination:{hasMore:!!f.hasMore,...f.currentPage!==void 0?{currentPage:f.currentPage}:{},...f.totalPages!==void 0?{totalPages:f.totalPages}:{},...f.charLength!==void 0?{itemsPerPage:f.charLength}:{},...f.totalChars!==void 0?{totalItems:f.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...la(a,p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Ae(e)}]}}async function KF(e){let{owner:t,repo:n}=MR(Ae(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:et(e.scope)??"",...Ae(e).kind==="github"&&Ae(e).ref?{branch:Ae(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Ee("ghViewRepoStructure",r),i=Oo(o),s=[],a=et(e.scope);for(let u of GF(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=IR(a,d,p);s.push({kind:"tree",source:Ae(e),path:f,entryType:"directory",depth:FR(f)})}for(let p of u.files??[]){let f=IR(a,d,p);s.push({kind:"tree",source:Ae(e),path:f,entryType:"file",depth:FR(f)})}}let c=$F(s,e),l=Dt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...la(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Ae(e)}]}}function YF(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function hr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function XF(e){if(DR(e)==="error"){let r=Oo(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:hr(o.status),retryAfterSeconds:hr(o.retryAfter),rateLimitRemaining:hr(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:hr(n.status),retryAfterSeconds:hr(n.retryAfterSeconds),rateLimitRemaining:hr(n.rateLimitRemaining)}}function JF(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return P("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?P("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):P("invalidQuery",e.message,{backend:t})}function ZF(e,t){let n=XF(e);return n?[JF(n,t)]:DR(e)==="empty"?[P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function la(e,t,n){let r=ZF(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...NF(t,n)]}var zR=y(()=>{"use strict";vo();Ci();xc();Ze();Ha();Cr()});import QR from"node:path";function BR(e){return[...new Set(e)]}function jR(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function UR(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!QR.isAbsolute(r.localPath)?QR.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function qR(e){if(e.from?.kind!=="github")return Dr(e);let t=e.from,{owner:n,repo:r}=jR(t);if(!n||!r)return{results:[],diagnostics:[P("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=et(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await Ee("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=UR(s);if(u==="error"||!a)return{results:[],diagnostics:[P("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},p={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:BR([...d.excludeDir??[],".git"]),exclude:BR([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await Dr(p);return{...f,diagnostics:[...f.diagnostics,...c?[P("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...f.provenance]}}async function WR(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[$R(f,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[P("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=jR(t);if(!n||!r)return{results:[],diagnostics:[P("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:et(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await Ee("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=UR(a);if(d==="error"||!c)return{results:[],diagnostics:[P("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let p=!i;return{results:[$R(c,t,t.ref,p,l)],diagnostics:l?[P("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function $R(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var VR=y(()=>{"use strict";vo();Ac();Ze();Cr()});import{builtinModules as e0}from"node:module";import we from"node:path";import{readFile as ua,readdir as t0}from"node:fs/promises";async function da(e){let t=we.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=i0(r,e.intent,e.facets),i=s0(o,e.facets),s=a0(o,i),a=g0();if(n==="plan")return c0({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:YR([],[],a)});let c=await l0(t,e.maxFiles??5e3),l=await u0(c.filter(w=>w.endsWith(n0))),u=await m0(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),p=YR(u,d,a);await O0(u);let f=new Set(l.map(w=>w.name).filter(tS)),m=R0(u),h=S0(t,l,u),b=P0(h,m),x=u.filter(w=>!b.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=C0(t,l,u,f),T=await x0(u),L=E0(T,u,b),_=L.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,E=L.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:h.length,reachableFiles:b.size,unusedFiles:x.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:L.length,candidateUnusedExports:_,transitiveDeadExports:E,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,N)=>w+N.declarations.length,0),nativeGraphCalls:d.reduce((w,N)=>w+N.calls.length,0)},manifests:l.map(w=>({manifest:An(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(N=>An(t,N)),dependencyCount:[...w.deps.keys()].length})),files:x,dependencies:S,symbols:L,graphFacts:d,graphCapabilities:p,caveats:["This is a smart research flow with native AST graph facts where available plus heuristic cross-file reachability. LSP references should be used before destructive cleanup.","Graph capability coverage is explicit: tree-sitter/OXC facts are syntax inventory, not semantic deletion proof.","Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function i0(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function s0(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function a0(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["localSearchCode structural","lspGetSemantics documentSymbols"],produces:["symbols","lineHints"],evidence:"proof"},{id:"reference-proof",purpose:"Use references grouped by file to separate direct, external, and transitive retention.",tools:["lspGetSemantics references","localSearchCode"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"proof"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function c0(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}async function l0(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await t0(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(r0.has(s.name))continue;await r(we.join(o,s.name));continue}s.isFile()&&n.push(we.join(o,s.name))}}return await r(e),n}async function u0(e){return(await Promise.all(e.map(async n=>d0(n)))).filter(n=>n!==null)}async function d0(e){let t=await p0(e);if(!t)return null;let n=we.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=I0(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:eS(t.name),deps:r,entrypoints:f0(n,t)}}async function p0(e){try{let t=JSON.parse(await ua(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function f0(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=eS(t[o]);i&&n.add(we.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(we.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(we.resolve(e,o));JR(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(we.resolve(e,o));return[...n]}function JR(e,t,n){if(typeof t=="string"){n.add(we.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))JR(e,r,n)}async function m0(e,t){let n=_u(),r=t.filter(i=>n.has(we.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await ua(i,"utf8").catch(()=>""),a=we.extname(i).toLowerCase(),c=h0(s,i,An(e,i)),l=M0(c?c.imports.map(u=>u.specifier):b0(s));return{path:i,rel:An(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!ZR(u)).map(_0).filter(tS).filter(u=>!o0.has(u)),...c?{graphFacts:c}:{}}}))}function h0(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??we.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(F0):[]}}catch{return}}function _u(){if(Lo)return Lo;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Lo=new Set(e.length>0?e:KR)}catch{Lo=new Set(KR)}return Lo}function g0(){if(Ao)return Ao;try{let e=JSON.parse(D.getGraphFactCapabilities());Ao=Array.isArray(e)?e.filter(y0):[]}catch{Ao=[]}return Ao}function y0(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function YR(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[..._u()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=XR(e,l=>l.language),s=XR(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function XR(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function b0(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function R0(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,we.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??we.dirname(o.path);for(let a of o.imports){if(!ZR(a))continue;let c=A0(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function S0(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=Au(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let s=Au(we.resolve(e,i),r);s&&o.add(s)}return[...o]}function P0(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function C0(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=w0(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:An(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:An(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:An(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function w0(e,t){return t.filter(r=>e.startsWith(`${r.dir}${we.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function x0(e){return(await Promise.all(e.map(async n=>{let r=k0(n);if(r.length>0)return r;let o=await ua(n.path,"utf8").catch(()=>"");return T0(n.rel,o)}))).flat()}function k0(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function T0(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:L0(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function E0(e,t,n){let r=new Map(t.map(o=>[o.rel,o]));return e.map(o=>{let i=t.filter(u=>u.rel!==o.file&&v0(u.path,o.symbol)),s=i.filter(u=>n.has(u.path)),a=r.get(o.file),c=a?n.has(a.path):!1,l=s.length>0?"reachable":i.length>0?"transitive-dead":c?"candidate-unused-export":"unused-export";return{symbol:o.symbol,kind:o.kind,file:o.file,line:o.line,evidenceSource:o.evidenceSource,directRefs:i.length,externalRefs:s.length,retainedBy:i.map(u=>u.rel),verdict:l}})}function v0(e,t){return Lu.get(e)?.has(t)??!1}async function O0(e){Lu.clear(),await Promise.all(e.map(async t=>{let n=await ua(t.path,"utf8").catch(()=>"");Lu.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function L0(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function A0(e,t,n){return Au(we.resolve(e,t),n)}function Au(e,t){let n=_u(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(we.join(e,`index${o}`));return r.find(o=>t.has(o))}function ZR(e){return e.startsWith("./")||e.startsWith("../")}function _0(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function I0(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function eS(e){return typeof e=="string"&&e.trim()?e:void 0}function tS(e){return typeof e=="string"&&e.length>0}function F0(e){return typeof e=="string"}function M0(e){return[...new Set(e)]}function An(e,t){return we.relative(e,t)||we.basename(t)}var KR,n0,r0,o0,Lo,Ao,Lu,Iu=y(()=>{"use strict";Ce();KR=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],n0="package.json",r0=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),o0=new Set(e0.flatMap(e=>[e,`node:${e}`]));Lu=new Map});import Fu from"node:path";function pa(e){let t=e.root,n=[...e.symbols.map(a=>D0(t,a)),...e.files.map(a=>z0(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>Q0(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let o={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},i=0,s=0;for(let a of n)o[a.verdict]+=1,i+=a.why.length,s+=a.retainedBy.length+(a.retains?.length??0);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function D0(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=N0(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:"references",source:"ripgrep",confidence:"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:G0(r),next:H0(e,t)}}function N0(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function G0(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via reference scan; likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable references found, but the scan is token-based. Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only referenced from unreachable code. Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function H0(e,t){let n=Fu.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"exact"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function z0(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:Fu.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:Fu.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function Q0(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var Mu=y(()=>{"use strict"});import nS from"node:path";function yr(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??B0),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function rS(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function iS(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:rS(e.relation),verdicts:rS(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function $0(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function gr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function Gu(e,t){if(!$0(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>gr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>gr(i.relation,t)),o=e.why.some(i=>gr(i.claim,t));return n||r||o}function Du(e,t){e.set(t.id,t)}function j0(e,t,n){gr(t.claim,n)&&e.set(t.id,t)}function Nu(e,t,n,r){gr(n.relation,r)&&(Du(e,n.from),Du(e,n.to),t.set(n.id,n))}function U0(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function sS(e,t,n,r,o,i){let s=t.filter(h=>Gu(h,r)),a=yr(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,p=new Map,f={},m={};for(let h of s)f[h.verdict]=(f[h.verdict]??0)+1,m[h.proofStatus]=(m[h.proofStatus]??0)+1;for(let h of c){if(Du(l,h.subject),r.includeFacts)for(let b of h.why)j0(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of h.retainedBy)Nu(l,u,b,r);if(r.direction!=="incoming")for(let b of h.retains??[])Nu(l,u,b,r)}for(let b of h.missingProof)p.set(U0(b),b)}return r.includeEdges&&W0(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:p.size,byVerdict:f,proofStatus:m},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...p.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function Hu(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function aS(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}function W0(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=V0(a.relation);if(!gr(c,i))continue;let l=oS(a.from,e,a.line),u=oS(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||Nu(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function V0(e){let t=e.trim();return q0.has(t)?t:"references"}function oS(e,t,n){let r=K0(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function K0(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:nS.isAbsolute(o)?nS.relative(t,o):o,name:i}}var B0,q0,zu=y(()=>{"use strict";B0=25;q0=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});import fa from"node:path";function Bu(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function lS(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function uS(e,t,n,r,o){let i=n.filter(l=>Gu(l,r)),s=yr(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await X0(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(P(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(P("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),Y0(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(P("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function Y0(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function X0(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=fa.isAbsolute(t.subject.uri)?t.subject.uri:fa.resolve(e,t.subject.uri);try{let i=await Ee("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=J0(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=an(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:Eo(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,p=mr(a?.totalReferences)??mr(u?.totalReferences)??mr(a?.referenceCount)??mr(u?.referenceCount)??mr(d?.totalItems)??cS(u)??cS(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:Z0(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function J0(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function cS(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function Z0(e,t){let n=new Set;return Qu(e,n,t),[...n].slice(0,25)}function Qu(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)Qu(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&eM(i)&&t.add(fa.isAbsolute(i)?fa.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])Qu(r[o],t,n)}function eM(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var dS=y(()=>{"use strict";vo();Ze();zu()});import{statSync as tM}from"node:fs";import le from"node:path";function pS(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}function bS(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function nM(e,t){if(!t||le.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?le.join(n.base,t):t}function rM(e,t,n){let r=t??n??".";if(!e)return r;if(le.isAbsolute(e))return e;if(n&&le.isAbsolute(n))return le.resolve(n,e);if(t&&le.isAbsolute(t)){let o=ju(t)?t:le.dirname(t);return le.resolve(o,e)}return e}function fS(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function SS(e){if(!e)return[];for(let t of RS){let n=e[t];if(Array.isArray(n))return n}return[e]}function iM(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function sM(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))oM.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function _o(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=uM(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function PS(e){return e==="plan"||e==="prove"?e:"analyze"}function aM(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;CS.includes(o)&&t.add(o)}return t.size>0?t:void 0}function cM(e,t){let n=aM(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of CS){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=yr(e,u.length);o[l]=u.slice(d,p),o[`${l}Page`]=f,s=f.itemsPerPage,a=Math.max(a,f.totalPages??1),f.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function lM(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function mS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function uM(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??br(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:br(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??br(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??br(t);case"artifact":return n("localPath")??n("path");case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:br(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return br(t)}function br(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function $u(e,t){let{status:n,data:r}=an(e);return n==="error"?[P("invalidQuery",bS(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function ju(e){try{let t=le.isAbsolute(e)?e:le.resolve(e);return tM(t).isDirectory()}catch{return!1}}function ma(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function cn(e){return e.params??{}}function dM(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function Uu(e,t){let n={...cn(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}function ha(e,t,n,r){let{data:o,status:i}=an(e),s=$u(e,n),a=i==="error"?[]:SS(o);a.length===0&&!s.some(p=>p.code==="zeroMatches"||p.severity==="error")&&s.push(P("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=Dt(c,l),d=t==="package"?iM(o):void 0;return{results:_o(a,t,r,sM(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function hS(){return P("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function pM(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(P("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(P("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push(hS()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push(hS());let i=e?.pagination;return i?.hasMore&&n.push(P("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:wS(i,t)})),n}function wS(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function fM(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:wS(n,t)}}async function mM(e){let{owner:t}=ma(e.from),n=Uu(e,"limit"),r=typeof n.language=="string"?n.language:dM(e),o=Ma(r);o&&(n.language=o);let i=await Ee("ghSearchRepos",{...t?{owner:t}:{},...n}),s=ha(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&hM(n)&&s.diagnostics.push(P("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function hM(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function gM(e){let t=await Ee("npmSearch",{...Uu(e)});return ha(t,"package","npmSearch",e.from??{kind:"npm"})}async function gS(e){let{owner:t,repo:n}=ma(e.from),r=e.target==="commits",o=r?void 0:RM(e),i=r?yM(e):void 0,s=Uu(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await Ee("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=ha(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?PM(c,o):i?bM(c,i):c}function yM(e){let t=cn(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function bM(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),p=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,p)+(p<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(P("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(P("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function RM(e){let t=cn(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function SM(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
47
- `)}function PM(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=SM(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(P("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(P("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}async function CM(e){let t=cn(e),{owner:n,repo:r}=ma(e.from),o=Mn(t);if(o.kind==="prPatch"){let i=await Ee("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return ha(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?wM(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):xM(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[P("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function wM(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[P("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=f=>({results:[],diagnostics:[P("invalidQuery",f,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=ju(r)?r:le.dirname(r),s=le.isAbsolute(t.path)?le.relative(i,t.path):t.path;if(!s||s.startsWith("..")||s.startsWith("-"))return o(`params.path must resolve inside from.path for a local ref diff (got "${t.path}").`);if(!yS.test(t.baseRef)||!yS.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(le.sep).join("/")}`,c=f=>Bt("git",["-C",i,"show",`${f}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let f=l.success?u:l,m=l.success?t.headRef:t.baseRef;return o(`git show ${m}:${a} failed: ${f.stderr.trim().split(`
48
- `)[0]||f.error?.message||`exit ${f.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=xS(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[P("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function xM(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[P("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=p=>Ee("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:p,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=pS(i),c=pS(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(p=>p.status==="error"||typeof p.content!="string");if(l){let p=bS(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[P("invalidQuery",p,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=xS(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[P("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function xS(e,t){let n=e===""?[]:e.split(`
36
+ `}var Ix=f(()=>{"use strict";pe();Xe();zr();qd();Fc();lu();De();Zn();Fc()});function Zr(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 Vi(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[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 r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var Ic=f(()=>{"use strict"});function Mx(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+Vi(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Zr(r)})`}function Dx(e,t){let n=e.length,r=t.itemsPerPage||Gt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function Mc(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} 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`]}var Vp=f(()=>{"use strict";Wi();Ic()});function C0(e,t){let n=t??x0,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function ir(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=gt(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:C0(i.path,i.excludeDir)},{warnings:a,query:c}=O0(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,m=u.wasCapped,p=u.entries.map(K=>w0(K,r)),h=e.sortBy||"modified";k0(p,h,r);let g=p.slice(0,l),y=T0(g,t,n),b=y.length,S=e.itemsPerPage||20,C=e.page||1,E=Math.max(1,Math.ceil(b/S)),T=(C-1)*S,_=Math.min(T+S,b),G=y.slice(T,_),M=[...u.warnings,...Mc(u)],A=[...a,...M],q=C<E,H={...b===0?{status:"empty"}:{},path:i.path,files:G,pagination:{currentPage:C,totalPages:E,filesPerPage:S,totalFiles:b,hasMore:q,...q?{nextPage:C+1}:{},...m||d>b?{totalFilesFound:d}:{}},...q?{next:{nextPage:qs(v.LOCAL_FIND_FILES,{...i,page:C+1},"Continue to the next page of matched files.")}}:{},...A.length>0&&{warnings:A}};return W(Nx(H,e,{totalFiles:b}),u.entries.reduce((K,I)=>K+I.path.length,0))}catch(o){return N(o,e,{toolName:v.LOCAL_FIND_FILES})}}function w0(e,t){let n={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 t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function Nx(e,t,n){return e}function k0(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function T0(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(t?o.size=r.size:o.sizeFormatted=Zr(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function O0(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!E0.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var x0,E0,Ki=f(()=>{"use strict";Zt();Ic();Ee();pe();ae();ue();Be();Vp();x0=[];E0=/^\d+[hdwm]$/});async function Gx(e){let{queries:t}=e;return me(t||[],async n=>pt({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=st(zn,n);return r.ok===!1?r.error:await ir(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var Hx=f(()=>{"use strict";du();pe();Xe();Ki();De();Zn();Ki()});function Ji(e){return Dc.exec(e)?.[1]?.toLowerCase()??""}function D0(e){let t=Ji(e);if(!t)return!1;for(let n of M0)if(Yi[n].extensions.includes(t))return!0;return!1}function Zp(e,t,n){if(n&&n!=="auto")return Yi[n];let r=Ji(e),o=(t??"").toLowerCase();for(let i of Kp){let s=Yi[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Kp){let s=Yi[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Yi.generic}function Nc(e){return v0.test(e)?"generated":L0.test(e)?"fixture":A0.test(e)?"test":F0.test(e)?"config":_0.test(e)?"docs":!Xi.test(e)&&(I0.test(e)||D0(e))?"source":"unknown"}function em(e){if(!e)return!1;if(Xi.test(e))return!0;let t=Nc(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Kp,de,Yp,Xp,Qx,Yi,Jp,Xi,v0,A0,L0,_0,F0,I0,M0,Dc,Gc=f(()=>{"use strict";Kp=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],de={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Yp=2e3,Xp=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Qx={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Yi={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Qx},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Qx},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},Jp=/^\s*#{1,6}\s/,Xi=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,v0=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,A0=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,L0=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,_0=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,F0=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,I0=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,M0=new Set(["typescript","javascript","rust","python","go","java","scala"]),Dc=/\.([a-z0-9]+)$/i});function tm(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(jx),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Yp,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(jx);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=sm(i,n),l=i.map(d=>{try{return{file:d,s:am(d,n,c)}}catch{return{file:d,s:N0()}}});l.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function N0(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function jx(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function Zi(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Hc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nm(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function rm(e,t,n){if(e.indexOf(`
37
+ `)<0)return e;let o=e.split(`
38
+ `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function om(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Xp.test(e))return"comment";let o=G0(e,t,r);if(o<0)return"code";let i=H0(e);return i>=0&&o>i?"comment":Bx(e,o)?"string":"code"}function G0(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function H0(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function Bx(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}var im=f(()=>{"use strict";Gc();cm()});function Q0(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function j0(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function B0(e,t,n,r,o){if(!e||e.length===0)return 0;let i=nm(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=rm(l,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Hc(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=de.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=de.exactCaseInsensitive,m.push("case-insensitive match")):u.includes(r)&&(d+=de.substring,m.push("substring match")));let p=c.kind;if(p)d+=z0(p,m);else{let h=om(u,r,t.id,n.caseSensitive);h!=="code"?(d+=de.commentOrStringPenalty,m.push(h==="comment"?"comment match (weak)":"string literal (weak)")):(Zi(t.declaration,u)&&(d+=de.declarationLine,m.push("declaration line")),Zi(t.export,u)&&(d+=de.exportLine,m.push("export/public line")),Zi(t.import,u)&&(d+=de.importLine,m.push("import line")),t.id==="markdown"&&Jp.test(u)&&(d+=de.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&$0(u,r)&&(d+=de.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function z0(e,t){switch(e){case"declaration":return t.push("AST: declaration"),de.declarationLine;case"export":return t.push("AST: export/public"),de.exportLine;case"configKey":return t.push("AST: config key"),de.configKeyLine;case"heading":return t.push("AST: heading"),de.headingLine;case"import":return t.push("AST: import"),de.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),de.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function $0(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function U0(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(Dc,"").includes(l))&&(s+=de.pathSegmentToken,i.push("query token in path"))}let a=Ji(e);return r.extensions.includes(a)&&t.langType&&(s+=de.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=de.sourceDir,i.push("source file")),s}function q0(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),de.lowSignalPathPenalty):0}function W0(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*de.matchCountScale,r=Math.min(n,de.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function sm(e,t){let n=j0(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>V0(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function V0(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Hc(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function K0(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*de.rareQueryTokenScale,de.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function am(e,t,n){let r=Zp(e.path,t.langType,t.profileOverride),o=Nc(e.path),i=Q0(t.keyword),s=[],a=0;return a+=B0(e.matches,r,t,i,s),a+=U0(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=de.pathUnderQuery,s.push("under requested subtree")),a+=q0(o,t,s),Xi.test(e.path)&&!t.explicitLowSignal&&(a+=de.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=W0(e.matchCount??0,s),a+=K0(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var cm=f(()=>{"use strict";Gc();im()});var zx=f(()=>{"use strict";Gc();cm();im()});function $x(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=J0(i);s.fetch={tool:"localGetFileContent",query:lm({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"heuristic":"exact"};let a=Z0(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:lm({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:lm({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function J0(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-8),endLine:n+8}}function Z0(e,t,n){if(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)return;if(n==="structural")return eM(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.onlyMatching){let o=um(e?.value);return o?{symbol:o}:void 0}let r=um(t.keywords);return r?{symbol:r}:void 0}function eM(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=um(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function um(e){if(typeof e!="string")return;let t=e.trim();if(X0.test(t)&&!Y0.has(t))return t}function lm(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Y0,X0,dm=f(()=>{"use strict";Y0=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),X0=/^[A-Za-z_$][A-Za-z0-9_$]*$/});async function Qc(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=tm(e,s,tM(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),m=!!(t.countLinesPerFile||t.countMatchesPerFile),p=d||m,h=c.reduce((H,K)=>H+(K.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??h:h,y=t,b=Math.min(y.itemsPerPage||Gt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=y.page||1,C=Math.max(1,Math.ceil(u/b)),E=(S-1)*b,T=Math.min(E+b,u),_=c.slice(E,T),w=y.maxMatchesPerFile||Gt.DEFAULT_MATCHES_PER_PAGE,G=_.map(H=>{let K=H.matches?.length??0,I=Math.ceil(K/w),ye=Math.max(1,y.matchPage||1),ke=(ye-1)*w,on=Math.min(ke+w,K),mo=p?void 0:H.matches?.slice(ke,on),vs=mo?.length,fo=l?.get(H.path);return{path:H.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:H.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:H.matchCount||1}:{totalMatchRows:K,...vs!==void 0?{returnedMatchRows:vs}:{}},...mo!==void 0&&{matches:mo},...fo?{ranking:{score:fo.score,profile:fo.profile,pathRole:fo.pathRole,reasons:fo.reasons}}:{},pagination:!p&&K>w?{currentPage:ye,totalPages:I,matchesPerPage:w,totalMatches:K,hasMore:ye<I,...ye<I?{nextMatchPage:ye+1}:{}}:void 0}}),M=G.filter(H=>H.pagination?.hasMore),A=$x(G,t,n,{isFileListMode:p,currentPage:S,totalFilePages:C,matchPage:y.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:M.length>0}),q={searchEngine:n,...o?{stats:o}:{},files:G,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<C,...S<C?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return Ux(q,t,{totalMatches:g,totalFiles:u})}function Ux(e,t,n){return e}function tM(e){let t=e.rankingProfile,n=!!(e.include?.length||em(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var qx=f(()=>{"use strict";Wi();zx();dm()});var jc=f(()=>{"use strict";qx();dm()});function Wx(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&nM(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&rM(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function nM(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function rM(e){return/\(\?[=!<]/.test(e)}var Vx=f(()=>{"use strict";Ee()});import{validateRipgrepQuery as oM}from"@octocodeai/octocode-core/schemas/runtime";function iM(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function sM(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:iM(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function aM(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function Kx(e){let t=[],n=oM(e);if(!n.isValid)return N(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=Wt.safeParse(e);if(!r.success){let g=r.error.issues.map(y=>y.message);return N(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return N(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=gt(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Wx({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return N(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(sM(a))}catch(g){return N(g instanceof Error?g:new Error(String(g)),o,{toolName:v.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(y=>{let b={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(b.count=y.count),y.kind!==void 0&&(b.kind=y.kind),y.scoreHint!==void 0&&(b.scoreHint=y.scoreHint),b})})),m=aM(d),p={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return W({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...l]},m);!a.filesOnly&&m>Gt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let h=await Qc(d,o,"rg",[...t,...l],p);return W(h,m)}var Yx=f(()=>{"use strict";Zt();Vs();Wi();pe();jc();Vx();ue();Ee()});import{readFile as cM,stat as lM}from"node:fs/promises";function mM(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function Jx(e){return e.include?.length?e.include:Wl(e.langType)}async function fM(e){try{return(await lM(e)).isFile()}catch{return!1}}async function hM(e,t){let n=await cM(e,"utf8"),r=await D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Zx(e){let t=gt(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await fM(t.sanitizedPath)?await hM(t.sanitizedPath,e):await D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...Jx(e)?{include:Jx(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Xx.length?{excludeDir:Xx}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??uM,maxFileBytes:dM})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return N(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:v.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(pM+mM(e.pattern)),await Qc(r,e,"structural",i,o)}var Xx,uM,dM,pM,eC=f(()=>{"use strict";Ee();Zt();pe();Vl();jc();Xx=[],uM=2e3,dM=1e6,pM="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function gM(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function yt(e){let t=gM(e);if(t.mode==="structural")return await Zx(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Kx(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:U.OUTPUT_TOO_LARGE}:N(n,t,{toolName:v.LOCAL_RIPGREP})}}var eo=f(()=>{"use strict";Zt();Jn();pe();Yx();eC()});async function tC(e){let{queries:t}=e;return me(t||[],async n=>pt({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=st(Wt,n);return r.ok===!1?r.error:await yt(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var nC=f(()=>{"use strict";Vs();pe();Xe();eo();De();Zn();jc()});function RM(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function rC(e,t){let n=e[t];return n===void 0?!1:yM.has(n)||n==="{"&&xM(e,t)}function SM(e,t,n){let r=n.pop()??!1,o=rC(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?iC(e,t+1):t+1})}function PM(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:iC(e,t)})}function oC(e){if(e.length>bM)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=RM(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=SM(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(rC(e,r)){let i=PM(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function xM(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function iC(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var yM,bM,sC=f(()=>{"use strict";yM=new Set(["+","*","?"]),bM=1e3});function aC(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!oC(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function cC(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function lC(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var uC=f(()=>{"use strict";sC()});async function Bc(e){try{let t=gt(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return CM(e,t.sanitizedPath,n)}catch(t){let n=ht.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function CM(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=kM(e),s=r&&e.limit&&!wM(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:TM(e),limit:s})}catch(C){return vM(C,e,t)}let c=a.entries.map(C=>EM(C,n,e.details??!1)),l=aC(c,e),u=e.sortBy??"name";l=l.sort((C,E)=>{let T=0;switch(u){case"size":{let _=C.sizeBytes??(C.size?Vi(C.size):0),w=E.sizeBytes??(E.size?Vi(E.size):0);T=_-w;break}case"time":n&&C.modified&&E.modified?T=C.modified.localeCompare(E.modified):T=C.name.localeCompare(E.name);break;case"extension":T=(C.extension||"").localeCompare(E.extension||"");break;default:T=C.name.localeCompare(E.name);break}return e.reverse?-T:T}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:m,pagination:p}=Dx(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(C=>({...lC(C),path:C.path??`${t.replace(/\/$/,"")}/${C.name}`}))}:{path:t,...cC(m)},y=[...a.warnings,...Mc({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],b=d===0,S=Mx(l);return W(dC({...b?{status:"empty"}:{},...g,summary:S,...p.hasMore||p.totalPages>1?{pagination:p}:{},...p.hasMore?{next:{nextPage:qs(v.LOCAL_VIEW_STRUCTURE,{...e,page:p.currentPage+1},"Continue to the next page of directory entries.")}}:{},...y.length>0&&{warnings:y}},e),a.entries.reduce((C,E)=>C+E.path.length,0))}function wM(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function kM(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function TM(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function EM(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:Zr(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=OM(e.permissions)),o}function OM(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function vM(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=ht.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return N(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function dC(e,t){return e}var zc=f(()=>{"use strict";Ic();pe();Zt();Ac();uC();Vp();ue();Ee();Be()});async function pC(e){let{queries:t}=e;return me(t||[],async n=>pt({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=st($n,n);return r.ok===!1?r.error:await Bc(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var mC=f(()=>{"use strict";mu();pe();Xe();zc();De();Zn();zc()});function LM(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function fC(e,t){if(t===void 0||t==="progressIdle")return e;let n=LM(e);if(!n||!AM.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,warnings:[...e.warnings??[],r]}}var AM,hC=f(()=>{"use strict";AM=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as _M,stat as FM}from"node:fs/promises";import{SymbolResolver as IM,SymbolResolutionError as MM}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as $c}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function pm(e,t){let n=e.uri,r=gt({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await FM(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:$c.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:$c.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await _M(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:$c.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function gC(e,t){let n=await pm(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 IM({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:DM(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof MM)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:$c.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function DM(e){return{start:e,end:{line:e.line,character:e.character}}}var mm=f(()=>{"use strict";Zt()});function hm(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 gm(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:hm(e.type,t),reason:t}}}function bt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:qt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:hm(e,n),reason:n}}}function Rt(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}var Tn,Uc,fm,qc=f(()=>{"use strict";vt();Tn=40,Uc=40,fm=10});function es(e,t,n,r,o){let i=o.length>0,s=o.map(iu),{pageItems:a,pagination:c}=Rt(s,e.page??1,e.itemsPerPage??Uc);return{type:e.type,uri:t.uri,resolvedSymbol:qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function ym(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?yC(r):void 0,i=o??r.map(iu),{pageItems:s,pagination:a}=Rt(i,e.page??1,e.itemsPerPage??Uc),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function bm(e,t,n){let r=bC(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function yC(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 bC(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=>RC(r)).join(`
39
+ `).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 RC(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 SC=f(()=>{"use strict";vt();qc()});import{safeReadFile as NM}from"@octocodeai/octocode-engine/lsp/validation";function ts(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function xC(e,t,n){if(t<=0)return e;let r=await NM(e.uri);if(!r)return e;let o=bi(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
40
+ `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function GM(e,t){return Promise.all(e.map(async n=>({...n,from:await xC(n.from,t,n.fromRanges)})))}async function HM(e,t){return Promise.all(e.map(async n=>({...n,to:await xC(n.to,t)})))}async function Rm(e,t,n,r,o){if(n<=0||!e)return{calls:[],...PC};try{let i=await e.getIncomingCalls(t),s=o>0?await GM(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=ts(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Rm(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function Sm(e,t,n,r,o){if(n<=0||!e)return{calls:[],...PC};try{let i=await e.getOutgoingCalls(t),s=o>0?await HM(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=ts(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Sm(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var PC,CC=f(()=>{"use strict";Hr();PC={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function kC(e){return W(e,j(e))}function TC(e,t){return e.format!=="compact"||!OC(t)?t:jM(t)}function EC(e){if(!OC(e))return e;let n=e.payload.locations?.[0],r=n?.displayRange?.startLine;if(!n?.uri||typeof r!="number")return e;let o=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri;return{...e,next:{readSite:{tool:"localGetFileContent",query:{path:o,startLine:Math.max(1,r-3),endLine:(n.displayRange?.endLine??r)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}function OC(e){return sr(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&sr(e.payload)}function jM(e){return{...e,format:"compact",payload:BM(e.payload)}}function BM(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(wC)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map($M)}:{locations:(e.locations??[]).map(wC)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:vC(e.root)}:{},direction:e.direction,calls:e.calls.map(UM),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(zM)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function zM(e){if(!sr(e))return String(e);let t=Ze(e,"line"),n=Ze(e,"character"),r=Ze(e,"endLine"),o=en(e,"kind"),i=en(e,"name"),s=Ze(e,"childCount"),a=en(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function wC(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${LC(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function $M(e){if(!sr(e))return String(e);let t=en(e,"uri"),n=Ze(e,"firstLine"),r=Ze(e,"firstCharacter"),o=Ze(e,"count"),i=AC(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function UM(e){if(!sr(e))return String(e);let t=en(e,"direction"),n=vC(e.item),r=AC(e,"ranges").map(qM).join(","),o=Ze(e,"rangeCount"),i=Ze(e,"rangeSampleCount"),s=en(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${LC(s,180)}`:""].filter(Boolean).join(" ")}function vC(e){if(!sr(e))return String(e);let t=en(e,"name"),n=en(e,"kind"),r=en(e,"uri"),o=Ze(e,"line"),i=Ze(e,"endLine"),s=Ze(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function qM(e){return sr(e)?`${Ze(e,"line")}:${Ze(e,"character")}`:String(e)}function sr(e){return typeof e=="object"&&e!==null}function en(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ze(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function AC(e,t){let n=e[t];return Array.isArray(n)?n:[]}function LC(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 _C(e,t){let n=IC(e.fromRanges);return{direction:"incoming",item:Wc(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...MC(e.from,t)}}function FC(e,t){let n=IC(e.fromRanges);return{direction:"outgoing",item:Wc(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...MC(e.to,t)}}function Wc(e){return{name:e.name,kind:to(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 IC(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=QM))break}return n}function MC(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function to(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"}}var QM,ns=f(()=>{"use strict";ue();QM=8});async function Pm(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return bt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await Rm(n,o,i,new Set([ts(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Sm(n,o,i,new Set([ts(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),m=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],p=m.map(S=>S.direction==="incoming"?_C(S,e.contextLines??0):FC(S,e.contextLines??0)),{pageItems:h,pagination:g}=Rt(p,e.page??1,e.itemsPerPage??fm),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Wc(o),direction:y,calls:h,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function xm(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return bt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=Rt(s,e.page??1,e.itemsPerPage??Tn);return{type:e.type,uri:t.uri,resolvedSymbol:qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}var DC=f(()=>{"use strict";CC();vt();ns();qc()});var rs=f(()=>{"use strict";qc();SC();DC()});import os from"node:path";import{readFile as WM}from"node:fs/promises";import{resolveImportAliasDefinitions as VM}from"@octocodeai/octocode-engine/lsp/resolver";async function HC(e,t,n){if(typeof e.openDocument=="function")try{let r=os.extname(t.uri).slice(1),o=NC.includes(r)?NC:[r],i=await yt({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:KM,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=os.isAbsolute(a)?a:os.join(n,a);if(os.resolve(c)!==os.resolve(t.uri))try{let l=await WM(c,"utf-8");if(l.length>YM)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function QC(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?es(e,t,"definition","definitionProvider",await VM({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):bt(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?es(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):bt(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?es(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):bt(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?ym(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):bt(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?bm(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):bt(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?Pm(e,t,n):bt(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?xm(e,t,n):bt(e.type,t,"typeHierarchyProvider unsupported",!0)}}var GC,KM,YM,NC,jC=f(()=>{"use strict";eo();rs();GC=new Set(["references","callers","callees","callHierarchy","implementation"]),KM=12,YM=512*1024,NC=["ts","tsx","mts","cts","js","jsx","mjs","cjs"]});import wm from"node:path";import{fileURLToPath as XM}from"node:url";import{unavailableHintFor as JM}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as ZM}from"@octocodeai/octocode-engine/lsp/config";function BC(e){return Cm||(Cm=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),Cm.has(wm.extname(e).toLowerCase())}function Tt(e,t){let n=ZM(e),r=JM(n,void 0);throw new Qe(U.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function zC(e,t){let n=e.startsWith("file://")?XM(e):e;return wm.isAbsolute(n)?n:wm.resolve(t,n)}function km(){return[...D.getSupportedJsTsExtensions(),...eD]}function $C(){return km().map(e=>`**/*.${e}`)}async function UC(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:$C(),excludeDir:[...tD],maxSnippetChars:1})).files[0]?.path}catch{return}}async function Tm(e,t){if(e.uri)return zC(e.uri,t);let n=await UC(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:km(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function Em(e){return e instanceof Error?e.message:String(e)}function Om(e,t){if(!BC(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var Cm,eD,tD,Vc=f(()=>{"use strict";ja();Jn();Ee();eD=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];tD=[".git","node_modules","dist","out","coverage","target"]});import{acquirePooledClient as nD,isLanguageServerAvailable as rD}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as oD}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Lm(e){let t=await pm(e,je);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await oD(t.value.uri),r=await rD(t.value.uri,n),o=r?await nD(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Om(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let y=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(y)?y:[],a="lsp"}else{let y=Rb(t.value.content,t.value.uri);y&&(s=y,a="markdown")}let l=a!==void 0;!l&&!r&&Tt(t.value.uri,"documentSymbols");let u=qC(s),d=VC(s),{pageItems:m,pagination:p}=Rt(u,e.page??1,e.itemsPerPage??Tn),h=KC(u,y=>y.kind),g=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:m.length,topLevelSymbols:d,kinds:h},payload:{kind:"documentSymbols",symbols:m,...g?{empty:g}:{}},pagination:p}}function qC(e){let t=[];for(let n of e)_m(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function _m(e,t,n){if(!e||typeof e!="object")return;let r=e,o=WC(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:to(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)&&iD.has(to(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)_m(s,t,i)}}function WC(e){if(vm(e.range))return e.range;let t=e.location;return t&&vm(t.range)?t.range:void 0}function vm(e){if(!e||typeof e!="object")return!1;let t=e;return Am(t.start)&&Am(t.end)}function Am(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function VC(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function KC(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}var iD,YC=f(()=>{"use strict";Ra();vt();mm();rs();ns();Vc();iD=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});import XC from"node:path";import{acquirePooledClient as JC,isLanguageServerAvailable as ZC}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as sD}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Fm(e){let t=e.symbolName??"",n=XC.resolve(e.workspaceRoot??process.cwd()),r=await Tm(e,n);await ZC(r,n)||Tt(r,"workspaceSymbol");let i=await JC(n,r);if(i||Tt(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{XC.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${Em(u)}`}}}let a=ew(s),{pageItems:c,pagination:l}=Rt(a,e.page??1,e.itemsPerPage??Tn);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function ew(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,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:to(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function Im(e){let t=e.uri??"",n=e.workspaceRoot??(t?await sD(t):process.cwd());await ZC(t,n)||Tt(t,"diagnostic");let o=await JC(n,t);if(o||Tt(t,"diagnostic"),!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,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 i=await o.getDiagnostics(t),s=tw(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Rt(s,e.page??1,e.itemsPerPage??Tn);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function tw(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>nw(r))}return[]}function nw(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 rw=f(()=>{"use strict";rs();ns();Vc()});var ow=f(()=>{"use strict";Vc();YC();rw()});import{acquirePooledClient as aD,isLanguageServerAvailable as cD}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as lD}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function iw(e){return me(e.queries||[],async t=>pt({toolName:je,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await uD(t);return kC(EC(TC(t,n)))}}),{toolName:je,minQueryTimeoutMs:3e4},e)}async function uD(e){if(e.type==="documentSymbols")return Lm(e);if(e.type==="workspaceSymbol")return Fm(e);if(e.type==="diagnostic")return Im(e);let t=await gC(e,je);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return gm(e,a)}let n=e.workspaceRoot??await lD(t.value.uri);await cD(t.value.uri,n)||Tt(t.value.uri,e.type);let o=await aD(n,t.value.uri);o||Tt(t.value.uri,e.type),GC.has(e.type)&&await HC(o,t.value,n);let i=o.getReadiness?.(),s=await QC(e,t.value,o);return fC(s,i)}var sw=f(()=>{"use strict";Xe();Zn();vt();hC();mm();jC();rs();ow();ns()});async function cw(e){let t=dD(e),n=an.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(Mm(),dw)),o=await r(n.data,{authInfo:e.authInfo});return pD(o)}function dD(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function pD(e){let t=mD(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function mD(e){return Ol(e)?{results:e.children.map(t=>aw(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:lw(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[aw(e,e.queryId??"oqlSearch-1")]}}function aw(e,t){let n=lw(e);return{id:e.queryId??t,...hD(e),data:n}}function lw(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||fD(d,u)){let{why:m,confidence:p,...h}=l;s[c]=h,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function fD(e,t){return e.why===t.why&&e.confidence===t.confidence}function hD(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var uw=f(()=>{"use strict";Fn();Pt()});var Dm,pw=f(()=>{"use strict";pe();Dm={hasTool(e){return cd(e)},getDescription(e){return ad[e]??""},getToolName(e){return v[e]??String(e)}}});function gD(e,t){return t.getToolName(e)}function Et(e,t,n){let r=gD(t,e);return{...n,name:r,description:Nm(r,e)}}function yD(e=Dm){let t=Et(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Lo,inputSchema:_o,executionFn:qS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=Et(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Qn,inputSchema:Ao,executionFn:MS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=Et(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:No,inputSchema:Go,executionFn:zP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=Et(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Io,inputSchema:Mo,executionFn:jP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=Et(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:jn,inputSchema:Fo,executionFn:TP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=Et(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ho,inputSchema:Qo,executionFn:dx,security:"remote",requiresServerRuntime:!0}}),a=Et(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Er,inputSchema:Oo,executionFn:JR,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=Et(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Wt,inputSchema:zo,executionFn:tC,security:"basic"}}),l=Et(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:$n,inputSchema:$o,executionFn:pC,security:"basic"}}),u=Et(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:zn,inputSchema:Bo,executionFn:Gx,security:"basic"}}),d=Et(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Bn,inputSchema:jo,executionFn:Fx,security:"basic"}}),m={name:je,description:Nm(je,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Uo,inputSchema:qo,executionFn:iw,security:"basic",requiresServerRuntime:!0}},p={name:Hn,description:Nm(Hn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:yo,inputSchema:an,executionFn:cw,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},h=[t,n,r,o,i,s,a,c,l,u,d,m,...To()?[p]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,OQL_SEARCH:p,ALL_TOOLS:h}}var Nm,et,k7,T7,E7,O7,v7,A7,L7,_7,F7,I7,M7,D7,N7,mw,fw=f(()=>{"use strict";fu();ZR();DS();WS();EP();BP();$P();px();Ix();Hx();nC();mC();sw();uw();vt();Eo();pw();Nm=(e,t=Dm)=>t.getDescription(e);et=yD(),k7=et.GITHUB_SEARCH_CODE,T7=et.GITHUB_FETCH_CONTENT,E7=et.GITHUB_VIEW_REPO_STRUCTURE,O7=et.GITHUB_SEARCH_REPOSITORIES,v7=et.GITHUB_SEARCH_PULL_REQUESTS,A7=et.PACKAGE_SEARCH,L7=et.GITHUB_CLONE_REPO,_7=et.LOCAL_RIPGREP,F7=et.LOCAL_VIEW_STRUCTURE,I7=et.LOCAL_FIND_FILES,M7=et.LOCAL_FETCH_CONTENT,D7=et.LSP_GET_SEMANTIC_CONTENT,N7=et.OQL_SEARCH,mw=et.ALL_TOOLS});import{ContentSanitizer as bD}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as RD}from"@octocodeai/config";function Hm(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:dt(t.structuredContent)}}catch{}return PD(t)?xD(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=bD.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function PD(e){return RD()==="mcp"&&process.env[SD]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function xD(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:CD(e.structuredContent)},...t]}}function CD(e){let t=["structuredContent available"];if(Gm(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=wD(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Gm(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function wD(e){let t=0,n=0;for(let r of e)Gm(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Gm(e){return typeof e=="object"&&e!==null}function Qm(e,t){let n=TD(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
41
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:kD,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Hm(r)}catch{return r}}function TD(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:ED(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function ED(e){try{return JSON.stringify(e)}catch{return}}var SD,kD,hw=f(()=>{"use strict";zr();SD="OCTOCODE_MCP_FULL_TEXT";kD="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as OD,withBasicSecurityValidation as vD}from"@octocodeai/octocode-engine/security";function gw(e,t){let n=OD(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function yw(e,t){let n=vD(r=>e(r),t);return(r,o)=>n(r,o)}var bw=f(()=>{"use strict"});import{getConfigSync as AD}from"@octocodeai/config";function _D(e){let t=e;return n=>t(n)}function FD(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:_D(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function MD(e){return ID.find(t=>t.name===e)}async function jm(e,t){let n=MD(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=DD(n,t);return await ND(n),GD(n),await HD(n,r)}catch(r){return Qm(n.name,r)}}function DD(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function ND(e){e.requiresServerRuntime&&(Kc||(Kc=LD().catch(t=>{throw Kc=null,t})),await Kc),e.requiresProviders&&(Yc||(Yc=gR().then(()=>{}).catch(t=>{throw Yc=null,t})),await Yc)}function GD(e){if(!e.isLocal&&!e.isClone)return;let t=AD();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function HD(e,t){try{let n=e.security==="remote"?await QD(e,t):await jD(e,t);return Hm(n)}catch(n){return Qm(e.name,n)}}async function QD(e,t){return gw(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function jD(e,t){return yw(e.execute,e.name)(t)}var Kc,Yc,LD,ID,Rw=f(()=>{"use strict";si();Bd();fw();hw();bw();hu();Kc=null,Yc=null,LD=Ty;ID=mw.map(FD)});var Sw=f(()=>{"use strict";hu();Rw()});function we(e,t){return jm(e,{queries:[{...BD,...t}]})}function En(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function no(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function is(e){return typeof e=="string"?e:void 0}var BD,tn=f(()=>{"use strict";Sw();BD={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function nn(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var Xc=f(()=>{"use strict"});function Bm(e){return nn(e)}function zD(e){if(e)return nn({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function ro(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges,c=i;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...c.kind!==void 0?{matchKind:c.kind}:{},...c.scoreHint!==void 0?{scoreHint:c.scoreHint}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:zm(zD(e.pagination),n.length)}}function zm(e,t,n=!1){if(e)return e.totalItemsKind!=="files"&&!n?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function ss(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:Bm(e.pagination)}}function Pw(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:Bm(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=UD(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:Bm(e.pagination)}}function UD(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=$D[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function xw(e,t,n,r="standard"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var $D,On=f(()=>{"use strict";Xc();$D={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});function $m(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function ar(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function Um(e){return e.structuredContent?.results?.[0]?.status}function Cw(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function qm(...e){return e.map(Cw).filter(Boolean).join("/")}function ww(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function Wm(e){return Cw(e).split("/").filter(Boolean).length}function qD(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function WD(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function VD(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KD(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(VD).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function kw(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(qD).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!KD(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(WD(o.path)))}function Vm(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function Tw(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function Ew(e){return typeof e=="string"?[]:e.matches??[]}function Fe(e){return e.from??{kind:"github"}}function Ow(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}var Km=f(()=>{"use strict"});function YD(e,t){return e>0?[]:[x("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function oo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function XD(e){if(Um(e)==="error"){let r=ar(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:oo(o.status),retryAfterSeconds:oo(o.retryAfter),rateLimitRemaining:oo(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:oo(n.status),retryAfterSeconds:oo(n.retryAfterSeconds),rateLimitRemaining:oo(n.rateLimitRemaining)}}function JD(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return x("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?x("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):x("invalidQuery",e.message,{backend:t})}function ZD(e,t){let n=XD(e);return n?[JD(n,t)]:Um(e)==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function as(e,t,n){let r=ZD(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...YD(t,n)]}var vw=f(()=>{"use strict";J();Km()});async function Aw(e){let t=Po(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await we("ghSearchCode",t.query),r=ar(n),o=new Set,i=[];for(let a of r?.files??[]){let c=Vm(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Fe(e),path:c,entryType:"file"}))}let s=nn(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...as(n,i.length,"ghSearchCode"),...i.length>0?[x("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Fe(e)}]}}async function Lw(e){let t=Po(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await we("ghSearchCode",t.query),r=ar(n),o=[];for(let s of r?.files??[]){let a=Vm(s),c=Tw(s),l=Ew(s);if(l.length===0){o.push({kind:"code",source:Fe(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Fe(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=zm(nn(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...as(n,o.length,"ghSearchCode"),...o.length>0?[x("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Fe(e)}]}}async function _w(e){let{owner:t,repo:n}=$m(Fe(e)),r=e.fetch?.content,o=r?.contentView??"standard",i=Ow(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Ie(e.scope)??"",type:"file",minify:o,...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await we("ghGetFileContent",s),c=ar(a),l=o,u=c?.pagination,d=c?.results??c?.files??[],m=d.map(h=>{let g=h.pagination??u,y=typeof g?.charOffset=="number",b={...h.startLine!==void 0?{startLine:h.startLine}:{},...h.endLine!==void 0?{endLine:h.endLine}:{},...y?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Fe(e),path:h.path,content:h.content,contentView:l,...Object.keys(b).length?{range:b}:{}}}),p=u??d.find(h=>h.pagination)?.pagination;return{results:m,...p?.hasMore!==void 0?{pagination:{hasMore:!!p.hasMore,...p.currentPage!==void 0?{currentPage:p.currentPage}:{},...p.totalPages!==void 0?{totalPages:p.totalPages}:{},...p.charLength!==void 0?{itemsPerPage:p.charLength}:{},...p.totalChars!==void 0?{totalItems:p.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...as(a,m.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Fe(e)}]}}async function Fw(e){let{owner:t,repo:n}=$m(Fe(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Ie(e.scope)??"",...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await we("ghViewRepoStructure",r),i=ar(o),s=[],a=Ie(e.scope);for(let u of ww(i?.structure)){let d=u.dir??".";for(let m of u.folders??[]){let p=qm(a,d,m);s.push({kind:"tree",source:Fe(e),path:p,entryType:"directory",depth:Wm(p)})}for(let m of u.files??[]){let p=qm(a,d,m);s.push({kind:"tree",source:Fe(e),path:p,entryType:"file",depth:Wm(p)})}}let c=kw(s,e),l=nn(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...as(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Fe(e)}]}}var Iw=f(()=>{"use strict";tn();Xc();On();J();Xl();ln();vw();Km()});async function Mw(e){switch(e.target){case"content":return _w(e);case"structure":return Fw(e);case"files":return Aw(e);default:return Lw(e)}}var Dw=f(()=>{"use strict";Iw()});function io(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Ym=f(()=>{"use strict"});function cr(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function Gw(e){return eN.test(e)}function Hw(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function lr(e,t,n){if(n){e.langType=n;return}let r=Qs(Sr(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=Hw(e.include,r.include))}function tN(e){return js(Sr(e))}function Nw(e){let t=io(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function so(e){return!!(e?.include?.length||e?.exclude?.length)}function cs(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(Nw).filter(i=>!!i);n.length>0&&!e.names&&(e.names=Hw(e.names,n));let r=(t?.include??[]).filter(i=>!Nw(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=tN(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function Qw(e,t){if(so(t.scope)){Zc(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function Zc(e){e.limit=Jc,e.itemsPerPage=Jc}function jw(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function el(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}var Jc,eN,ur=f(()=>{"use strict";ae();zs();ln();Ym();Jc=1e4;eN=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});function Bw(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?Xm(e.predicate):!1}function nN(e){return e.kind==="text"||e.kind==="regex"}function tl(e){return e?.kind==="not"&&nN(e.predicate)}function Xm(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}function Jm(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?Jm(e.predicate):!1}function nl(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(x("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(ls(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(ls(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(ls(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(x("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(ls(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(ls(i));break}r&&n.push(x("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function ls(e){return x("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function Ht(e,t){let n=[];e.status==="error"?n.push(x("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(x(rN(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function rN(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function Qt(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var ao=f(()=>{"use strict";J()});import Zm from"node:path";async function $w(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Bc(r);return{...Pw(o,t),diagnostics:Ht(o,"localViewStructure"),provenance:[Qt("localViewStructure",t,void 0)]}}async function Uw(e,t,n){let r=e.fetch?.content,o=r?.contentView??"standard",i=oN(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await _c(s);return{...xw(a,t,n,o),diagnostics:Ht(a,"localGetFileContent"),provenance:[Qt("localGetFileContent",t,void 0)]}}function oN(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function us(e,t,n){if(!so(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>iN(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function iN(e,t,n){let r=io(sN(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>zw(r,i))?!1:!(n?.exclude??[]).some(i=>zw(r,i))}function sN(e,t){let n=Zm.relative(t,e);return!n||n.startsWith("..")||Zm.isAbsolute(n)?e:n}function zw(e,t){let n=io(t),r=io(e),o=aN(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Zm.posix.basename(r))}function aN(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=cN(r)}return new RegExp(`${t}$`)}function cN(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}var rl=f(()=>{"use strict";zc();Fc();On();ur();ao();Ym()});function ol(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}function ds(e){let t=new Map;for(let n of e)t.set(n.path,ol(t.get(n.path),n));return t}function qw(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,ol(o,i))}return n}function Ww(e,t){return new Set([...e].filter(n=>t.has(n)))}var ps=f(()=>{"use strict"});async function ef(e,t,n,r){let o={path:n,entryType:"f"};cs(o,e.scope),so(e.scope)&&(Zc(o),o.page=1);let i=await ir(o),s=us(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),ds(ss({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function Vw(e,t,n,r,o,i){let s={path:r,details:!0};cs(s,e.scope),nl(t,s,i),so(e.scope)&&(Zc(s),s.page=1);let a=await ir(s),c=us(a,e,r);return o.push({backend:"localFindFiles",source:e.from}),ds(ss(c,n).results)}var Kw=f(()=>{"use strict";Ki();On();ur();ao();rl();ps()});async function Yw(e,t,n,r,o,i){let s=Ut(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:Jc,...cr(e.scope)};lr(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await yt(c);return o.push({backend:"localSearchCode",source:e.from}),ds((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}async function Xw(e,t,n,r){let o=await yt(Zw(e,n,r.predicate)),i=Ht(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[Qt("localSearchCode",t,r)]}}async function Jw(e,t,n,r){let o=await yt(Zw(e,n,r.predicate));return{...ro(o,t),diagnostics:Ht(o,"localSearchCode"),provenance:[Qt("localSearchCode",t,r)]}}function Zw(e,t,n){let o=Ut(n).match,i={path:t,filesWithoutMatch:!0,...cr(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...el(e)};return lr(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}var il=f(()=>{"use strict";eo();Ro();On();J();ur();ao();ps()});async function ek(e,t,n,r){let o=[],i=[],a=[...(await sl(e,r,t,n,o,i)).values()].sort(lN(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(x("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function lN(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function sl(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>sl(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:qw(a,c));case"any":{let s=await Promise.all(t.of.map(c=>sl(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,ol(a.get(l),u));return a}case"not":{let s=await ef(e,n,r,o),a=await sl(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return tk(e,t,n,r,o,i)}}async function tk(e,t,n,r,o,i){return t.kind==="field"?Vw(e,t,n,r,o,i):Yw(e,t,n,r,o,i)}async function nk(e,t,n){return new Set((await ef(e,e.from,t,n)).keys())}async function rk(e,t,n,r,o){return new Set((await tk(e,t,e.from,n,r,o)).keys())}var tf=f(()=>{"use strict";J();Kw();il();ps()});async function ok(e,t,n,r){let o=[],i=[],s=await al(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(x("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function al(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>al(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:Ww(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>al(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await nk(e,r,o),a=await al(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await rk(e,t,r,o,i),rows:[]};default:{let s=await uN(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function uN(e,t,n,r,o,i){let s=Ut(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...cr(e.scope)};lr(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await yt(c);return o.push({backend:"localSearchCode",source:n}),ro(l,n).results}var ik=f(()=>{"use strict";eo();Ro();On();J();ur();tf();ps()});async function cl(e,t,n){let r=e.where;if(Bw(r))return ok(e,t,n,r);if(e.view==="discovery"&&tl(r))return Jw(e,t,n,r);let o=Ut(r);if(o.unsupported)return{results:[],diagnostics:[x(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...cr(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...el(e)};lr(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await yt(s),c=ro(a,t),l=Ht(a,"localSearchCode"),u=dN(a);if(u.length>0){let d=u.reduce((p,h)=>p+(h.total??0),0),m=u.reduce((p,h)=>p+h.shown,0);l.push(x("matchTruncated",`${u.length} file(s) have more matches (showed ${m} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(x("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&Gw(i.keywords)&&l.push(x("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[Qt("localSearchCode",t,r)]}}function dN(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}var nf=f(()=>{"use strict";eo();Ro();On();J();ur();ao();ik();il()});async function sk(e,t,n){let r=e.where;if(tl(r))return Xw(e,t,n,r);if(r&&Xm(r))return ek(e,t,n,r);if(r&&Jm(r)){let l=await cl({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};cs(o,e.scope),Qw(o,e),jw(o,e);let i=[];r&&nl(r,o,i);let s=await ir(o),a=us(s,e,n);return{...ss(a,t),diagnostics:[...i,...Ht(a,"localFindFiles")],provenance:[Qt("localFindFiles",t,r)]}}var ak=f(()=>{"use strict";Ki();On();ur();ao();nf();tf();il();rl()});import pN from"node:fs";import mN from"node:path";function fN(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}async function ms(e){let t=e.from,n=fN(e),r=Ie(e.scope),o=r?mN.join(n,r):n;if(!pN.existsSync(o))return{results:[],diagnostics:[x("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return sk(e,t,o);case"structure":return $w(e,t,o);case"content":return Uw(e,t,o);default:return cl(e,t,o)}}var rf=f(()=>{"use strict";J();nf();ak();rl();ln()});import ck from"node:path";function lk(e){return[...new Set(e)]}function dk(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function pk(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!ck.isAbsolute(r.localPath)?ck.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function mk(e){if(e.from?.kind!=="github")return ms(e);let t=e.from,{owner:n,repo:r}=dk(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Ie(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await we("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=pk(s);if(u==="error"||!a)return{results:[],diagnostics:[x("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},m={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:lk([...d.excludeDir??[],".git"]),exclude:lk([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},p=await ms(m);return{...p,diagnostics:[...p.diagnostics,...c?[x("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...p.provenance]}}async function fk(e){if(e.from?.kind==="materialized"){let p=e.from.localPath;return{results:[uk(p,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[x("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=dk(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:Ie(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await we("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=pk(a);if(d==="error"||!c)return{results:[],diagnostics:[x("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let m=!i;return{results:[uk(c,t,t.ref,m,l)],diagnostics:l?[x("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function uk(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var hk=f(()=>{"use strict";tn();rf();J();ln()});import of from"node:path";function ll(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{byVerdict:t,facts:n,edges:r}}function co(e){let t=e.root,n=[...e.symbols.map(a=>hN(t,a)),...e.files.map(a=>RN(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>SN(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let{byVerdict:o,facts:i,edges:s}=ll(n);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function hN(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=gN(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:t.retentionSource==="ast"?"imports":"references",source:t.retentionSource==="ast"?"ast":"ripgrep",confidence:t.retentionSource==="ast"?"exact":"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:yN(r),next:bN(e,t)}}function gN(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function yN(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via AST import/call retention (or lexical fallback); likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable retainers found in analyze (AST import/call scan, then lexical fallback). Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only retained from unreachable code (AST or lexical scan). Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function bN(e,t){let n=of.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"none"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function RN(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:of.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:of.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function SN(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var gk=f(()=>{"use strict"});var fs=f(()=>{"use strict";gk()});function yk(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function sf(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:yk(e.relation),verdicts:yk(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function PN(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function dr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function hs(e,t){if(!PN(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>dr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>dr(i.relation,t)),o=e.why.some(i=>dr(i.claim,t));return n||r||o}function ul(e,t){e.set(t.id,t)}function bk(e,t,n){dr(t.claim,n)&&e.set(t.id,t)}function gs(e,t,n,r){dr(n.relation,r)&&(ul(e,n.from),ul(e,n.to),t.set(n.id,n))}function Rk(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}var dl=f(()=>{"use strict"});import Sk from"node:path";function ys(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function xk(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=CN(a.relation);if(!dr(c,i))continue;let l=Pk(a.from,e,a.line),u=Pk(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||gs(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function CN(e){let t=e.trim();return xN.has(t)?t:"references"}function Pk(e,t,n){let r=wN(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function wN(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:Sk.isAbsolute(o)?Sk.relative(t,o):o,name:i}}var xN,af=f(()=>{"use strict";dl();xN=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});function pr(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??kN),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function Ck(e,t,n,r,o,i){let s=t.filter(g=>hs(g,r)),a=pr(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,m=new Map,p={},h={};for(let g of s)p[g.verdict]=(p[g.verdict]??0)+1,h[g.proofStatus]=(h[g.proofStatus]??0)+1;for(let g of c){if(ul(l,g.subject),r.includeFacts)for(let y of g.why)bk(d,y,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let y of g.retainedBy)gs(l,u,y,r);if(r.direction!=="incoming")for(let y of g.retains??[])gs(l,u,y,r)}for(let y of g.missingProof)m.set(Rk(y),y)}return r.includeEdges&&xk(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:m.size,byVerdict:p,proofStatus:h},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...m.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function wk(e){let{byVerdict:t,facts:n,edges:r}=ll(e);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}var kN,bs=f(()=>{"use strict";fs();dl();af();dl();af();kN=25});function pl(e){if(!e)return[];for(let t of kk){let n=e[t];if(Array.isArray(n))return n}return[e]}function Tk(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function Ek(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))TN.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function cf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function lo(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function EN(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??lo(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:lo(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??lo(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??lo(t);case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:lo(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return lo(t)}function vn(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=EN(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}var kk,TN,Rs=f(()=>{"use strict";kk=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],TN=new Set([...kk,"pagination","contentPagination","next"])});import{statSync as ON}from"node:fs";import ml from"node:path";function fl(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function Ok(e,t){if(!t||ml.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?ml.join(n.base,t):t}function Ss(e){try{let t=ml.isAbsolute(e)?e:ml.resolve(e);return ON(t).isDirectory()}catch{return!1}}function An(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function St(e){return e.params??{}}function Ps(e,t){let n={...St(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}var Ln=f(()=>{"use strict"});function hl(e){return e==="plan"||e==="prove"?e:"analyze"}function vN(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;vk.includes(o)&&t.add(o)}return t.size>0?t:void 0}function Ak(e,t){let n=vN(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of vk){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:m,pagination:p}=pr(e,u.length);o[l]=u.slice(d,m),o[`${l}Page`]=p,s=p.itemsPerPage,a=Math.max(a,p.totalPages??1),p.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function Lk(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function lf(e,t){let{status:n,data:r}=En(e);return n==="error"?[x("invalidQuery",fl(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function mr(e,t,n,r){let{data:o,status:i}=En(e),s=lf(e,n),a=i==="error"?[]:pl(o);a.length===0&&!s.some(m=>m.code==="zeroMatches"||m.severity==="error")&&s.push(x("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=nn(c,l),d=t==="package"?Tk(o):void 0;return{results:vn(a,t,r,Ek(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function uf(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function _k(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:uf(n,t)}}var vk,fr=f(()=>{"use strict";J();tn();Xc();bs();Rs();Ln();vk=["manifests","files","dependencies","symbols","graphFacts"]});function AN(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}async function Fk(e){let{owner:t}=An(e.from),n=Ps(e,"limit"),r=typeof n.language=="string"?n.language:AN(e),o=Bs(r);o&&(n.language=o);let i=await we("ghSearchRepos",{...t?{owner:t}:{},...n}),s=mr(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&LN(n)&&s.diagnostics.push(x("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function LN(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function Ik(e){let t=await we("npmSearch",{...Ps(e)});return mr(t,"package","npmSearch",e.from??{kind:"npm"})}var Mk=f(()=>{"use strict";tn();J();zs();fr();Ln()});async function df(e){let{owner:t,repo:n}=An(e.from),r=e.target==="commits",o=r?void 0:FN(e),i=r?_N(e):void 0,s=Ps(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await we("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=mr(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?Nk(c,o):i?Dk(c,i):c}function _N(e){let t=St(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function Dk(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),m=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,m)+(m<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function FN(e){let t=St(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function IN(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
42
+ `)}function Nk(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=IN(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}var Gk=f(()=>{"use strict";tn();J();fr();Ln()});import gl from"node:path";function Hk(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}async function jk(e){let t=St(e),{owner:n,repo:r}=An(e.from),o=Rr(t);if(o.kind==="prPatch"){let i=await we("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return mr(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?MN(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):DN(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function MN(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[x("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=p=>({results:[],diagnostics:[x("invalidQuery",p,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=Ss(r)?r:gl.dirname(r),s=gl.isAbsolute(t.path)?gl.relative(i,t.path):t.path;if(!s||s.startsWith("..")||s.startsWith("-"))return o(`params.path must resolve inside from.path for a local ref diff (got "${t.path}").`);if(!Qk.test(t.baseRef)||!Qk.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(gl.sep).join("/")}`,c=p=>er("git",["-C",i,"show",`${p}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let p=l.success?u:l,h=l.success?t.headRef:t.baseRef;return o(`git show ${h}:${a} failed: ${p.stderr.trim().split(`
43
+ `)[0]||p.error?.message||`exit ${p.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=pf(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[x("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function DN(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[x("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=m=>we("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:m,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=Hk(i),c=Hk(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(m=>m.status==="error"||typeof m.content!="string");if(l){let m=fl(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[x("invalidQuery",m,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=pf(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[x("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function pf(e,t){let n=e===""?[]:e.split(`
49
44
  `),r=t===""?[]:t.split(`
50
- `),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let f=o-1;f>=0;f--)for(let m=i-1;m>=0;m--)s[f][m]=n[f]===r[m]?s[f+1][m+1]+1:Math.max(s[f+1][m],s[f][m+1]);let a=[],c=0,l=0,u=0,d=0,p=0;for(;d<o&&p<i;)n[d]===r[p]?(a.push(` ${n[d]}`),u++,d++,p++):s[d+1][p]>=s[d][p+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[p]}`),c++,p++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;p<i;)a.push(`+ ${r[p++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
51
- `)}}async function kM(e){let t=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!t)return{results:[],diagnostics:[P("invalidQuery",'target:"artifacts" needs a local file `from` (path).',{backend:"localBinaryInspect"})],provenance:[]};let n=await Ee("localBinaryInspect",{path:t,...cn(e)}),{data:r,status:o}=an(n),i=$u(n,"localBinaryInspect");return o==="error"||!r?{results:[],diagnostics:i.length?i:[P("zeroMatches","localBinaryInspect returned no data.",{backend:"localBinaryInspect",severity:"info",blocksAnswer:!1})],provenance:[{backend:"localBinaryInspect",source:e.from}]}:{results:_o([r],"artifact",e.from),diagnostics:[...i,...TM(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function TM(e,t){let n=e.pagination&&typeof e.pagination=="object"?e.pagination:void 0;return e.isPartial!==!0&&n?.hasMore!==!0?[]:[P("partialResult","Artifact text is paginated; follow the artifact continuation before treating the inline content as complete.",{backend:"localBinaryInspect",blocksAnswer:!0,continuation:EM(t,n)})]}function EM(e,t){if(!(t?.hasMore!==!0||typeof t.nextCharOffset!="number"))return{query:{...e,params:{...e.params??{},charOffset:t.nextCharOffset,...typeof t.charLength=="number"?{charLength:t.charLength}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}async function vM(e){let t,n,r=[],o=[],i=cn(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let _=e.from.path,E=ju(_);n=c??(E?le.resolve(_):void 0),t=a??(E?void 0:_)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let _=fS(e),E=_?le.isAbsolute(_)?_:le.join(e.from.localPath,_):void 0;s?(n=c??e.from.localPath,t=a??E):t=a??E??e.from.localPath}else if(e.from?.kind==="github"){let{owner:_,repo:E}=ma(e.from);if(!_||!E)return o.push(P("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,N=fS(e),F=w&&!le.isAbsolute(w)?w:N,v=await Ee("ghCloneRepo",{owner:_,repo:E,...e.from.ref?{branch:e.from.ref}:{},...F?{sparsePath:F}:{}}),Q=an(v).data,G=nM(v,Q?.localPath);if(!G)return o.push(P("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:G}),s?(n=c??G,w?t=le.isAbsolute(w)?w:le.join(G,w):N&&(t=le.isAbsolute(N)?N:le.join(G,N))):w?t=le.isAbsolute(w)?w:le.join(G,w):N?t=le.isAbsolute(N)?N:le.join(G,N):t=G}if(!t&&!n)return o.push(P("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...p}=i,f=await Ee("lspGetSemantics",{...p,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:m,status:h}=an(f),b=m,x=fM(b,e),S=rM(Eo(b?.uri),t,n),T=AM(e,S),L=LM(OM(b),u);return{results:h==="error"?[]:_o(L,"semantics",T),...x?{pagination:x}:{},diagnostics:[...o,...$u(f,"lspGetSemantics"),...pM(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:T}]}}function OM(e){if(!e)return[];let n=(mS(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=Eo(e.uri);return n.map(o=>mS(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return SS(e)}function LM(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function AM(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}async function _M(e){let t=cn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[P("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=PS(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[P("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await da({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[P("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:pa(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?yr(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?cM(e,i):{fields:{}},p={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:Hu(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=lM(l?.pagination,d.pagination);return{results:_o([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function IM(e){let t=cn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[P("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=PS(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[P("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await da({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[P("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:pa(i),a=iS(t),c=s?.packets??[],l=Bu(i.mode,t)?await uS(n,e,c,a,lS(e,t)):[],u=aS(c),d=sS(e,c,u,a,i.graphFacts,n),p=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[Bu(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],f={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:Hu(i.graphFacts),caveats:p};return{results:_o([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var RS,oM,CS,yS,kS,TS=y(()=>{"use strict";vo();Ci();Ze();zo();mo();$o();Iu();Mu();zu();dS();RS=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],oM=new Set([...RS,"pagination","contentPagination","next"]);CS=["manifests","files","dependencies","symbols","graphFacts"];yS=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/;kS={repositories:mM,packages:gM,pullRequests:gS,commits:gS,diff:CM,artifacts:kM,semantics:vM,research:_M,graph:IM}});var wR={};WS(wR,{buildArtifactContinuations:()=>FS,runOqlSearch:()=>OS});import ht from"node:path";import{statSync as vS}from"node:fs";async function OS(e,t={}){let n;try{n=ka(e)}catch(o){if(o instanceof _t)return Ko(o.diagnostics);throw o}if(Xu(n))return gD(n,e,t);let r=await LS(n,e,t);return qu(r.results),r}function qu(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function LS(e,t,n,r){let o=qa(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return sD(o,s,e.id,r,n.dryRun,e);let a=await hD(e,o);lD(e,a.results),FM(e,a),MM(a);let c=zM(e,a);BM(e,a.results);let l=mD(e,a.results),u=QM(a.results);return xr({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:Va(o.plan.backendCalls),plan:s})}function FM(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function MM(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}function DM(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function NM(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function GM(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function HM(e){let t=GM(e),n=NM(e),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${ES(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${ES(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function ES(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function zM(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${HM(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:oD(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=UM[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function QM(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||AS(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function AS(e,t){return e.why===t.why&&e.confidence===t.confidence}function BM(e,t){for(let n of t)n.proofGrade??=$M(e,n)}function $M(e,t){return t.kind==="code"?Io(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Io(e.where,"text")||Io(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?ga(t.data)?"missing":"graph":t.recordType==="research"?ga(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function Io(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Io(n,t)):e.kind==="not"?Io(e.predicate,t):!1:!1}function ga(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!jM(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function jM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function qM(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:DM(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"exact",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function WM(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function _S(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function IS(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function FS(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=IS(e);i&&(o==="strings"?n["next.search"]={query:{schema:"oql",target:"code",from:{kind:"local",path:i},where:{kind:"regex",value:"https?://\\S+"},controls:{search:{maxMatchesPerFile:100,matchPage:1}}},why:"Grep this strings dump with local code search (ripgrep) \u2014 swap the regex/pattern for what you need (URLs, hosts, symbols); page noisy hits losslessly with matchPage. For a huge binary this beats reading the capped inline preview.",confidence:"heuristic"}:Object.assign(n,_S(i,"extracted")));let s=typeof r?.nextScanOffset=="number"?r.nextScanOffset:void 0;s!==void 0&&(n["next.artifactStrings"]={query:{...t.query,params:{...t.query.params??{},scanOffset:s}},why:"Scan the next window of printable strings.",confidence:"exact"});let a=r?.pagination&&typeof r.pagination=="object"?r.pagination:void 0,c=typeof a?.nextCharOffset=="number"?a.nextCharOffset:void 0;if(a?.hasMore===!0&&c!==void 0){let l=typeof a.charLength=="number"?a.charLength:void 0;n["next.artifactContent"]={query:{...t.query,params:{...t.query.params??{},charOffset:c,...l!==void 0?{charLength:l}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}return Object.keys(n).length?n:void 0}function VM(e){let t=IS(e);return t?_S(t,"materialized"):void 0}function KM(e,t){return MS(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function YM(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(ga(r))return MS(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function MS(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!ga(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=JM(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function JM(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&XM.has(o));return r.length>0?r:void 0}function ZM(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=nD(e)??rD(t.query),i=eD(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"exact",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function eD(e,t){if(e&&ht.isAbsolute(e))return e;if(t&&ht.isAbsolute(t)){let n=tD(t);return e?ht.resolve(n,e):t}return t??e}function tD(e){try{return vS(e).isDirectory()?e:ht.dirname(e)}catch{return ht.dirname(e)}}function nD(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function rD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function oD(e){let t=NS(e);if(!t)return;let n=DS(t).slice(0,-ht.sep.length);return r=>({kind:"local",path:ht.isAbsolute(r)?r:ht.join(n,r)})}function iD(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function sD(e,t,n,r,o,i){let s=o&&i?aD(i):[],a=o&&i?cD(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:Ko(e.plan.diagnostics,t,n,r,iD(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function aD(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[P("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function cD(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}function DS(e){let t=ht.resolve(e);try{if(vS(t).isDirectory())return`${t}${ht.sep}`}catch{}return`${ht.dirname(t)}${ht.sep}`}function NS(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function lD(e,t){let n=NS(e);if(!n)return;let r=DS(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function mD(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):dD.has(c)?o.add(c):pD.has(c)?o.add("data"):fD.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!uD.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[P("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}async function hD(e,t){if(e.target==="materialize")return WR(e);let n=kS[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?Dr(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?qR(e):HR(e)}async function gD(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await LS(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=yD(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&qu(o.merged.results)}else for(let i of r)qu(i.envelope.results);return o}function yD(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let p=PD(d);n.has(p)||(n.add(p),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),bD(s,u.envelope.nextHints),RD(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),SD(u.envelope)&&(l=!0)}return l&&o.push(P("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:xr({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function bD(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||AS(o,r))&&(e[n]=r)}}function RD(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function SD(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function PD(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var UM,XM,uD,dD,pD,fD,wu=y(()=>{"use strict";Ea();Wa();Ze();Ka();Ac();zR();VR();TS();At();UM={code:qM,content:WM,"record:artifact":FS,"record:materialized":VM,"record:semantics":ZM,"record:research":KM,"record:graph":YM};XM=new Set(["symbols","files","dependencies","relations"]);uD=new Set(["kind","source","recordType","id","proofGrade"]),dD=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),pD=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),fD=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});At();In();Ea();Wa();Qo();Ze();Ka();wu();At();function CD(e){let t=wD(e);if("error"in t)return t;let n=t.target;if(e.search==="both"){let o=Wu({...e,target:"files",search:"path"});if("error"in o)return o;let i=Wu({...e,target:n==="files"?"code":n,search:"content"});return"error"in i?i:{input:{schema:"oql",queries:[o.query,i.query],combine:"independent",...e.limit!==void 0?{limit:e.limit}:{},...e.page!==void 0?{page:e.page}:{},...e.itemsPerPage!==void 0?{itemsPerPage:e.itemsPerPage}:{}}}}let r=Wu({...e,target:n});return"error"in r?r:{input:r.query}}function Wu(e){let t=FD(e.view);if("error"in t)return t;let n=kD(e),o=e.target==="code"||e.target==="files"?TD(e):{};if("error"in o)return o;if(["code","files"].includes(e.target)&&o.where===void 0&&!e.filesOnly&&!e.filesWithoutMatch)return{error:"No search term: provide text, --regex, --pattern, or --rule."};let s={schema:"oql",target:e.target,...n};o.where&&(s.where=o.where),t.view&&(s.view=t.view),e.limit!==void 0&&(s.limit=e.limit),e.page!==void 0&&(s.page=e.page),e.itemsPerPage!==void 0&&(s.itemsPerPage=e.itemsPerPage);let a=ID(e);a&&(s.materialize=a);let c=LD(e);c&&(s.fetch=c);let l=OD(e);l&&(s.controls=l);let u=AD(e);return Object.keys(u).length>0&&(s.params=u),{query:s}}function wD(e){let t=e.target;return t?xD(t)?{target:t}:{error:`--target must be one of: ${Je.join(", ")}.`}:e.op||e.symbol||e.uri||e.workspaceRoot?{target:"semantics"}:e.tree?{target:"structure"}:MD(e)?{target:"content"}:e.search==="path"?{target:"files"}:e.corpus.kind==="npm"?{target:"packages"}:{target:"code"}}function xD(e){return Je.includes(e)}function kD(e){let t={};if(e.lang&&(t.language=e.lang),e.include?.length&&(t.include=e.include),e.excludeDir?.length&&(t.excludeDir=e.excludeDir),e.extension){let n=e.extension.replace(/^\./,"");t.include=[...t.include??[],`**/*.${n}`]}if(e.exclude?.length&&(t.exclude=e.exclude),e.hidden&&(t.hidden=!0),e.noIgnore&&(t.noIgnore=!0),e.minDepth!==void 0&&(t.minDepth=e.minDepth),e.maxDepth!==void 0&&(t.maxDepth=e.maxDepth),Mo.includes(e.target)&&e.corpus.kind==="local")return Object.keys(t).length>0?{scope:t}:{};if(e.corpus.kind==="npm")return{from:{kind:"npm"},...Object.keys(t).length>0?{scope:t}:{}};if(e.corpus.kind==="github"){let n={kind:"github",repo:e.corpus.repo,...e.branch||e.corpus.ref?{ref:e.branch??e.corpus.ref}:{}};return e.corpus.path&&(t.path=e.corpus.path),{from:n,...Object.keys(t).length>0?{scope:t}:{}}}return{from:{kind:"local",path:e.corpus.path},...Object.keys(t).length>0?{scope:t}:{}}}function TD(e){let t=ED(e);if(e.filesWithoutMatch){let r=GS(e);if("error"in r||!r.where)return r;let o={kind:"not",predicate:r.where};return{where:t.length?{kind:"all",of:[...t,o]}:o}}let n=e.search==="path"?vD(e):GS(e);return"error"in n?n:t.length&&n.where?{where:{kind:"all",of:[...t,n.where]}}:t.length===1?{where:t[0]}:t.length>1?{where:{kind:"all",of:t}}:n}function ED(e){let t=[];e.filesOnly?t.push({kind:"field",field:"entryType",op:"=",value:"file"}):(e.directoriesOnly||e.entryType)&&t.push({kind:"field",field:"entryType",op:"=",value:e.directoriesOnly?"directory":e.entryType}),e.extension&&t.push({kind:"field",field:"extension",op:"=",value:e.extension.replace(/^\./,"")}),e.filename&&t.push({kind:"field",field:"basename",op:"glob",value:HS(e.filename)}),e.pathPattern&&t.push({kind:"field",field:"path",op:"glob",value:HS(e.pathPattern)}),e.sizeGreater&&t.push({kind:"field",field:"size",op:">",value:e.sizeGreater}),e.sizeLess&&t.push({kind:"field",field:"size",op:"<",value:e.sizeLess}),e.modifiedWithin&&t.push({kind:"field",field:"modified",op:"within",value:e.modifiedWithin}),e.modifiedBefore&&t.push({kind:"field",field:"modified",op:"before",value:e.modifiedBefore}),e.accessedWithin&&t.push({kind:"field",field:"accessed",op:"within",value:e.accessedWithin}),e.empty&&t.push({kind:"field",field:"empty",op:"=",value:!0}),e.permissions&&t.push({kind:"field",field:"permissions",op:"=",value:e.permissions});for(let[n,r]of[["executable",e.executable],["readable",e.readable],["writable",e.writable]])r&&t.push({kind:"field",field:n,op:"=",value:!0});return t}function GS(e){let t=e.lang;return e.pattern!==void 0?t?{where:{kind:"structural",lang:t,pattern:e.pattern}}:{error:"--pattern requires --lang (e.g. --lang ts)."}:e.rule!==void 0?t?{where:{kind:"structural",lang:t,rule:e.rule}}:{error:"--rule requires --lang (e.g. --lang ts)."}:e.regex!==void 0?e.fixedString?{where:{kind:"text",value:e.regex,...Vu(e),...e.wholeWord?{wholeWord:!0}:{}}}:{where:{kind:"regex",value:e.regex,...e.pcre2?{dialect:"pcre2"}:{},...Vu(e),...e.wholeWord?{wholeWord:!0}:{},...e.multiline?{multiline:!0}:{},...e.multilineDotall?{dotAll:!0}:{}}}:e.text!==void 0&&e.text!==""?{where:{kind:"text",value:e.text,...Vu(e),...e.wholeWord?{wholeWord:!0}:{}}}:{}}function vD(e){if(e.regex!==void 0)return{where:{kind:"field",field:"path",op:"regex",value:e.regex}};if(e.text!==void 0&&e.text!==""){let t=/[/*?[\]]/.test(e.text);return{where:{kind:"field",field:t?"path":"basename",op:"glob",value:t?e.text:`*${e.text}*`}}}return{}}function HS(e){return/[*?[\]]/.test(e)?e:`*${e}*`}function Vu(e){return e.caseSensitive?{case:"sensitive"}:e.caseInsensitive?{case:"insensitive"}:{}}function OD(e){let t={};e.countLinesPerFile&&(t.countLinesPerFile=!0),e.countMatchesPerFile&&(t.countMatchesPerFile=!0),e.onlyMatching&&(t.onlyMatching=!0),e.unique&&(t.unique=!0),e.countUnique&&(t.countUnique=!0),e.contextLines!==void 0&&(t.contextLines=e.contextLines),e.invertMatch&&(t.invertMatch=!0),e.matchWindow!==void 0&&(t.matchWindow=e.matchWindow),e.matchContentLength!==void 0&&(t.matchContentLength=e.matchContentLength),e.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=e.maxMatchesPerFile),e.matchPage!==void 0&&(t.matchPage=e.matchPage),zS(e.target)&&e.sort&&(t.sort=e.sort),zS(e.target)&&e.sortReverse&&(t.sortReverse=!0),e.rankingProfile&&(t.rankingProfile=e.rankingProfile),e.debugRanking&&(t.debugRanking=!0);let n={};e.maxFiles!==void 0&&(n.maxFiles=e.maxFiles);let r={};return Object.keys(t).length>0&&(r.search=t),Object.keys(n).length>0&&(r.budget=n),Object.keys(r).length>0?r:void 0}function zS(e){return e==="code"||e==="files"}function LD(e){let t={},n=QS(e.contentView);n&&(t.contentView=n),(e.startLine!==void 0||e.endLine!==void 0||e.contextLines!==void 0)&&(t.range={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...e.contextLines!==void 0?{contextLines:e.contextLines}:{}}),e.matchString&&(t.match={text:e.matchString,...e.matchRegex?{regex:!0}:{},...e.matchCaseSensitive?{caseSensitive:!0}:{}}),e.charOffset!==void 0&&(t.charOffset=e.charOffset),e.charLength!==void 0&&(t.charLength=e.charLength),e.fullContent&&(t.fullContent=!0);let r={};e.maxDepth!==void 0?r.maxDepth=e.maxDepth:e.tree&&e.depth!==void 0&&(r.maxDepth=e.depth),e.filename?r.pattern=e.filename:e.pattern&&(e.tree||e.target==="structure")&&(r.pattern=e.pattern),e.includeSizes&&(r.includeSizes=!0),e.extension&&(r.extensions=DD(e.extension)),e.filesOnly&&(r.filesOnly=!0),(e.directoriesOnly||e.entryType==="directory")&&(r.directoriesOnly=!0),ND(e.sort)&&(r.sortBy=e.sort),e.sortReverse&&(r.reverse=!0);let o={};return Object.keys(t).length>0&&(o.content=t),Object.keys(r).length>0&&(o.tree=r),Object.keys(o).length>0?o:void 0}function AD(e){switch(e.target){case"code":return Lt({concise:e.concise,extension:e.extension,filename:e.filename});case"semantics":return Lt({type:e.op??"documentSymbols",uri:e.uri,symbolName:e.symbol,symbolKind:e.symbolKind,lineHint:e.line,orderHint:e.order,depth:e.depth,workspaceRoot:e.workspaceRoot,format:e.format});case"repositories":return Lt({keywords:e.text?e.text.includes(" ")?e.text.split(/\s+/).filter(Boolean):[e.text]:void 0,topicsToSearch:e.topic?.length?e.topic:void 0,language:e.lang,owner:e.owner,stars:e.stars,forks:e.forks,goodFirstIssues:e.goodFirstIssues,license:e.license,created:e.created,updated:e.updated,size:e.size,match:e.match,archived:e.archived,visibility:e.visibility,concise:e.concise,sort:e.sort,limit:e.limit,page:e.page});case"packages":return Lt({packageName:e.text,page:e.page});case"pullRequests":return Lt({keywordsToSearch:e.text?[e.text]:void 0,query:void 0,concise:e.concise,state:e.state,author:e.author,label:e.label,prNumber:e.prNumber,head:e.head,base:e.base,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,draft:e.draft,archived:e.archived,sort:e.sort,order:e.orderDirection,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,charOffset:e.charOffset,charLength:e.charLength,content:_D(e),limit:e.limit,page:e.page,matchString:e.matchString,matchScope:e.matchString?"all":void 0});case"commits":return Lt({path:e.corpus.kind==="github"?e.corpus.path:void 0,branch:e.branch,since:e.since,until:e.until,author:e.author,includeDiff:e.patches,limit:e.limit,page:e.page,filePage:e.filePage,itemsPerPage:e.itemsPerPage});case"artifacts":return Lt({mode:e.artifactMode??"inspect",detailed:e.detailed,verbose:e.verbose,maxEntries:e.maxEntries,entriesPerPage:e.itemsPerPage,minLength:e.minLength,entryPageNumber:e.entryPageNumber,scanOffset:e.scanOffset,charOffset:e.charOffset,charLength:e.charLength,matchString:e.matchString,format:e.format,includeOffsets:e.includeOffsets,archiveFile:e.archiveFile});case"diff":{let t=e.corpus.kind==="local"&&e.diffPath!==void 0;return Lt({prNumber:e.prNumber,baseRef:e.baseRef??(t?"base":void 0),headRef:e.headRef??(t?"head":void 0),path:e.diffPath??(e.corpus.kind==="github"?e.corpus.path:void 0)})}case"research":case"graph":return Lt({goal:e.text,intent:e.intent,facets:e.facets,proof:e.proof,proofLimit:e.proofLimit,includePackets:e.includePackets,includeFacts:e.includeFacts,includeEdges:e.includeEdges,maxFiles:e.maxFiles});default:return{}}}function _D(e){if(!(!e.patches&&!e.patchFile&&!e.commentsContent&&!e.commitsContent&&!e.deep))return Lt({metadata:!0,body:e.deep?!0:void 0,changedFiles:e.deep||e.patches||e.patchFile?!0:void 0,patches:e.patchFile?{mode:"selected",files:[e.patchFile]}:e.deep||e.patches?{mode:"all"}:void 0,comments:e.deep||e.commentsContent?{discussion:!0,reviewInline:!0}:void 0,reviews:e.deep?!0:void 0,commits:e.deep||e.commitsContent?{list:!0}:void 0})}function ID(e){if(!e.materialize&&!e.forceRefresh)return;let t=e.materialize??"auto";return e.forceRefresh?{mode:t,forceRefresh:!0}:t}function FD(e){return e?e==="discovery"||e==="paginated"||e==="detailed"?{view:e}:{error:`--view must be discovery, paginated, or detailed (got "${e}").`}:{}}function QS(e){switch(e){case"exact":return"exact";case"compact":return"compact";case"symbols":return"symbols";default:return}}function MD(e){return!!(QS(e.contentView)||e.matchString||e.startLine!==void 0||e.endLine!==void 0||e.charOffset!==void 0||e.charLength!==void 0||e.fullContent)}function Lt(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function DD(e){return e.split(",").map(t=>t.trim().replace(/^\./,"")).filter(Boolean)}function ND(e){return e==="name"||e==="size"||e==="time"||e==="extension"}Ba();Qo();At();var Rr={schema:"oql",description:"octocode search \u2014 typed read-only queries over code, files, symbols, repos, packages, history, artifacts, diffs, and graph evidence. Think source + answer type + filters + read/output options; use --explain for routing; follow next.* for pages, exact reads, materialization, or proof.",activeTargets:Je,reservedTargets:_n,sourceGuide:{local:'from:{kind:"local",path:"./src"}; shorthand: search "term" ./src, search ./src --tree, search file.ts --op documentSymbols. Best for local code/content/files/tree/LSP/artifacts/diff.',github:'from:{kind:"github",repo:"owner/repo",ref?}; shorthand: search "term" owner/repo, search owner/repo --tree, search owner/repo#123 --target pullRequests. GitHub code is indexed/default-branch scoped; materialize for AST/LSP/local proof.',npm:'from:{kind:"npm"} with target:"packages"; shorthand: search zod --target packages. Use to resolve package metadata and source repo, then continue with GitHub or local/materialized proof.',materialized:'from:{kind:"materialized",localPath:"/abs/path"} after target:"materialize", clone, or cache fetch. Use when a remote repo/subtree must behave like local code.'},plainLanguage:{source:"`from` = where to look: local path, GitHub repo, npm, or a materialized checkout.",answerType:"`target` = what kind of answer you want: code matches, file content, tree, files, symbols, repos, packages, PRs, commits, artifacts, diffs, research packets, graph proof, or materialization.",filters:"`where` = match/filter conditions for code and file discovery only: text, regex, AST shape, file fields, and boolean combinations.",readOptions:"`fetch` = what to read once you know the file/tree: exact content, compact content, symbol outline, ranges, match slices, or tree depth.",targetOptions:"`params` = options that belong to one answer type, such as LSP operation, PR number, package name, artifact mode, research intent, or graph proof.",output:"`view`, `select`, and `controls` = response shape, projected fields, search tuning, and cost limits.",paging:"`page` + `itemsPerPage` page the target's primary result domain. For code search that may be matched files; per-file match paging uses `controls.search.matchPage` / `--match-page`."},targetDecisionTree:{"find a string/pattern in code":"target:code (shorthand default for text/regex/--pattern/--rule; needs a where filter)","read or slice a known file":"target:content (file positional + --content-view, --start-line/--end-line, or --match-string)","see the file/dir layout":"target:structure (--tree)","find files by name/glob/ext/size/mtime":"target:files (--search path, --name/--ext/--size-greater/--modified-within)","symbol defs/refs/callers/hover":"target:semantics (--op \u2026; local or materialized only)","search GitHub repos":"target:repositories (--stars/--lang/--topic)","resolve an npm package":"target:packages","PR list or deep-read":"target:pullRequests (owner/repo#N)","commit history":"target:commits (--since/--until)","a diff":"target:diff ({prNumber} for a PR patch, {baseRef,headRef,path} for two refs)","inspect a binary/archive":"target:artifacts (--inspect/--list/--strings/--extract)","dead-code / reachability sweep":'target:research, then upgrade with target:graph proof:"lsp"',"make a remote repo behave like local (AST/LSP/negation)":"target:materialize (or clone / cache fetch)"},agentBestPractices:["Start with cheap orientation: --tree, --search path, --view discovery, or --content-view symbols.","Then narrow and read exact evidence: --match-string, --start-line/--end-line, --char-offset/--char-length, or --content-view exact.","Use snippets as discovery only; make decisions from exact content, PR/commit metadata, or LSP/graph proof.","For semantics, run documentSymbols first to get line anchors, then references/callers/hover with symbolName + lineHint.","For GitHub zero rows / providerUnindexed, do NOT claim absence \u2014 follow evidenceSemantics.providerUnindexed (verify path with structure, then materialize a bounded path).","Read evidence.answerReady, evidence.complete, diagnostics, pagination, and next.* before concluding."],quickStart:{"text search (local)":'search "functionName" ./src',"text search (GitHub)":'search "functionName" vercel/next.js',"package lookup (npm)":"search zod --target packages","PR deep read (GitHub)":"search vercel/next.js#1 --target pullRequests --comments --patches","commit history (GitHub)":"search vercel/next.js/packages/next/src --target commits --since 2024-01-01T00:00:00Z","browse a tree (local dir or owner/repo)":"search ./src --tree | search vercel/next.js --tree","read a file (local or owner/repo/path)":"search ./src/index.ts | search vercel/next.js/packages/next/src/server/config.ts","read a remote file (exact)":"search vercel/next.js/README.md --content-view exact","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","artifact inspect/list":"search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect","PR diff (GitHub)":"search vercel/next.js#123 --target diff | search vercel/next.js --target diff --pr 123","two-ref / two-file diff":"search src/a.ts src/b.ts --target diff | search owner/repo --target diff --base-ref <sha> --head-ref <sha> --path <file>","structural AST (local \u2014 needs full node shape)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" ./src --lang ts',"structural AST (GitHub \u2014 clones bounded subtree)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" vercel/next.js/packages/next/src --lang ts --materialize auto',"GitHub index miss recovery":"search useState packages/next/src --repo vercel/next.js --materialize required | clone vercel/next.js/packages/next/src | cache fetch vercel/next.js packages/next/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},semanticsGuide:{documentSymbols:"list a file's symbols to get line anchors first (run before references/callers/hover)",references:"all usages of a symbol across the workspace (often includes its declaration)",callers:"incoming calls to a function/method (call sites only) \u2014 narrower than references",hover:"type, signature, and docs at a symbol"},query:{schema:'"oql" (inserted by normalization)',target:Je.join(" | "),from:'{ kind:"local", path } | { kind:"github", repo?, owner?, ref? } | { kind:"materialized", localPath, source? } | { kind:"npm" } \u2014 local row.path is relative to from.path; the pre-filled next.fetch carries the resolved ABSOLUTE path, so follow it directly rather than re-joining paths yourself',scope:"{ path?, language?, include?, exclude?, excludeDir?, hidden?, noIgnore?, minDepth?, maxDepth? } \u2014 minDepth/maxDepth bound directory recursion depth (0-64)",where:"filters for code/files only: text | regex | structural | field | all | any | not. To read a matched file slice, use fetch.content.match. For PR/commit/artifact text narrowing, use that target params hint.",materialize:'{ mode:"never"|"auto"|"required", strategy?:"file"|"tree"|"subtree"|"repo", allowFullRepo?, forceRefresh? }',fetch:'{ content?: { contentView:"exact"|"compact"|"symbols", fullContent?, match?:{text|regex,case?}, range?:{startLine?,endLine?,contextLines?}, charOffset?, charLength? }, tree?:{ maxDepth?, pattern?, includeSizes?, extensions?, filesOnly?, directoriesOnly?, sortBy?:"name"|"size"|"time"|"extension", reverse? } } \u2014 read options for known files/trees; fetch.content.fullContent:true returns the WHOLE file in one shot (lossless, no char-window paging); to read the region around a string, anchor with fetch.content.match (NOT a top-level where, which is code/files only)',params:"target options (validated by OQL for common fields and by the backing tool exhaustively) \u2014 see params hints below",select:"string[] projection of result/continuation fields",view:"discovery | paginated | detailed",controls:'{ search?: { countLinesPerFile?, countMatchesPerFile?, onlyMatching?, unique?, countUnique?, contextLines?, invertMatch?, matchWindow?, matchContentLength?, maxMatchesPerFile?, matchPage?, sort?:"relevance"|"matchCount"|"path"|"modified"|"accessed"|"created"|"size"|"name", sortReverse?, rankingProfile?, debugRanking? }, budget?: { maxFiles?, maxCandidates?, maxBytes?, maxMaterializedBytes?, maxPlanNodes?, maxBooleanExpansion?, timeoutMs? } } \u2014 output/cost controls; sort values "size"/"name" apply to target:"files" only (lowered to localFindFiles sortBy), the rest are code-search sorts',limit:"number \u2014 total result cap where supported. Prefer itemsPerPage for paged research/graph/file-history continuations.",page:"number \u2014 top-level page number for OQL windowing/continuations",itemsPerPage:"number \u2014 page size for the target primary result domain. For code search this may be matched files, not individual matches; per-file match paging uses controls.search.matchPage. Per-target params expose backing-tool sub-pages only (filePage/commentPage/commitPage, entryPageNumber, scanOffset, etc.).",explain:"boolean"},params:{semantics:'{ type:"definition"|"references"|"callers"|"callees"|"callHierarchy"|"hover"|"documentSymbols"|"typeDefinition"|"implementation"|"workspaceSymbol"|"supertypes"|"subtypes"|"diagnostic", uri?, symbolName?, symbolKind?, lineHint?, orderHint?, depth?, contextLines?, includeDeclaration?, groupByFile?, workspaceRoot?, format? } \u2014 backing tool lspGetSemantics; contextLines adds call-flow snippets; symbolKind filters returned symbol rows after documentSymbols/workspaceSymbol',repositories:"{ keywords?: string[], topicsToSearch?: string[], language?, owner?, stars?, license?, sort?, archived?, limit?, page? } \u2014 backing tool ghSearchRepos; keywords/topicsToSearch are arrays even for one term",packages:'{ packageName?: string | keywords?: string[], mode?:"lean"|"full", page? } \u2014 backing tool npmSearch',pullRequests:'{ state?:"open"|"closed"|"merged", author?, label?, keywordsToSearch?, prNumber?, reviewMode?, filePage?, commentPage?, commitPage?, limit?, page?, matchString?, matchScope?:"body"|"title"|"comments"|"reviews"|"all", content? } \u2014 backing tool ghHistoryResearch; matchString filters fetched PR title/body/comments/reviews per matchScope (default body), not a search-index query \u2014 no match \u2192 zeroMatches',commits:'{ path?, branch?, since?, until?, includeDiff?, limit?, page?, filePage?, itemsPerPage?, matchString? } \u2014 backing tool ghHistoryResearch type:"commits"; matchString filters commit messages; repo/directory diffs page changed files per commit with filePage/itemsPerPage',artifacts:'{ mode:"inspect"|"list"|"extract"|"decompress"|"strings"|"unpack", minLength?, entryPageNumber?, scanOffset?, charOffset?, charLength?, matchString? } \u2014 localBinaryInspect. matchString filters text-producing modes (extract/decompress/strings) over the current fetched payload. For large strings dumps, follow next.search on data.localPath for lossless ripgrep paging; next.artifactContent (charOffset) = next inline text window; next.artifactStrings (scanOffset) = next binary scan window. extract/unpack/decompress \u2192 tree at data.localPath (next.structure/next.files).',diff:"{ prNumber, files? } (PR patch via ghHistoryResearch) | { baseRef, headRef, path } (direct two-ref file diff via ghGetFileContent + local line diff); neither shape -> invalidQuery repair",research:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:("symbols"|"files"|"dependencies"|"relations")[], mode?:"plan"|"analyze"|"prove", maxFiles? } \u2014 TWO-PHASE: page:1+itemsPerPage:1 \u2192 data.summary (full-scope counts) and may include a bounded first packet page; page:2+ \u2192 data.packets[] continuation pages (candidates w/ retainedBy edges + per-packet next.*). Always evidence:"candidate"/answerReady:false (normal). Follow the row's pre-filled next.graph (proof:"lsp", proofLimit-bounded) to upgrade a page to LSP-proven proofStatus.`,graph:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:(\u2026)[], mode?:"plan"|"analyze"|"prove", maxFiles?, subject?, subjectKind?, relation?, verdict?, direction?:"incoming"|"outgoing"|"both", proof?:"none"|"lsp", proofLimit?, includePackets?, includeFacts?, includeEdges? } \u2014 UPGRADE PATH: run a research row's pre-filled next.graph directly. proof:"lsp" sets per-row proofStatus: "confirmed-by-lsp" (refs=0 in bounded workspace; still inspect entrypoints/exports before deletion), "conflicting-evidence" (refs>0 \u2192 retained, check retainedBy), "needs-framework-graph" (maybe an entrypoint). answerReady:false is normal \u2014 follow next.* for more pages/proof.`,materialize:'(no params; no `where`) clone/cache a bounded corpus (from:{kind:"github",repo} + scope.path) and return a stable materialized checkpoint row (localPath/repoRoot/ref/cache/complete) with next.structure/next.files. Use after GitHub providerUnindexed; for CLI alternatives use clone owner/repo[/path] or cache fetch owner/repo [path] --depth file|tree|clone.'},predicates:{text:'{ kind:"text", value, case?, wholeWord? }',regex:'{ kind:"regex", value, dialect?:"rust"|"pcre2"|"provider", case?, wholeWord?, multiline?, dotAll? }',structural:'{ kind:"structural", lang, pattern? | rule? } (exactly one; rule is a JSON object or grep-compatible YAML rule string) \u2014 pattern must match the COMPLETE node, so include the parts the real node has: a fn WITH a return type only matches if the pattern has one too (`function $N($$$A): $R { $$$B }`); omitting it returns 0. Shapes: `function $N($$$A) { $$$B }` (no-return-type fn), `($$$A) => $$$B` (arrow, block+expression), `$F($$$A)` (call), `$O.$M($$$A)` (method). For "find symbol X" the ROBUST form is a rule, not a pattern: `{ kind:"function_declaration", has:{ pattern:"X" } }`. 0 matches + no parse error = pattern shape \u2260 real node (add `: $R`, or switch to a rule). Note: $$$-only patterns skip files with no literal anchor \u2192 low counts; add a literal name or use a regex where.',field:'{ kind:"field", field:"path"|"basename"|"extension"|"size"|"modified"|"accessed"|"empty"|"permissions"|"executable"|"readable"|"writable"|"entryType", op:"="|"!="|"in"|"exists"|"glob"|"regex"|">"|">="|"<"|"<="|"within"|"before", value? } (use symbolic ops like "="; aliases such as "eq" are invalid; there is no "contains" op \u2014 use op:"glob", value:"*term*" or op:"regex"; "within"/"before" compare modified/accessed times; empty/executable/readable/writable are boolean file attributes paired with op:"exists" or op:"=") SCOPE: field predicates evaluate file attributes, so they run on target:"files" (and mixed into files-lane booleans); target:"code" rejects a bare field predicate with unsupportedPredicate \u2014 use text/regex/structural for code content, or target:"files" for file discovery.',boolean:'{ kind:"all"|"any", of: Predicate[] } | { kind:"not", predicate }',booleanSugar:"Top-level sugar keys lower to canonical booleans at normalize time: and:[...]\u2192all, or:[...]\u2192any, noneOf:[...]\u2192not(any), xor:[a,b]\u2192any(all(a,not b),all(not a,b)), oneOf:[...]\u2192exactly-one expansion (bounded by controls.budget.maxBooleanExpansion), invert:true\u2192not(where). Prefer canonical all/any/not in programmatic queries; sugar is for terse hand-written ones."},batch:{queries:"OqlQuery[] (1-5)",combine:"independent | merge"},explainRoutes:{PUSHDOWN:"Backend evaluates this predicate exactly \u2014 good. No residual work.",RESIDUAL:"Backend narrows candidates but OQL must finish evaluation locally.",ROUTE:"OQL must use a different lane, often materialization.",UNSUPPORTED:"OQL cannot execute this predicate safely on the chosen source."},defaults:De};function GD(){return JSON.stringify(Rr,null,2)}function BS(e){let t="shorthand: ",n=e.indexOf(t);if(n===-1)return null;let r=e.slice(n+t.length).trim(),o=r.length,i=r.indexOf(",");i!==-1&&(o=Math.min(o,i));let s=r.search(/\.\s/);return s!==-1&&(o=Math.min(o,s)),r.slice(0,o).trim().replace(/\.$/,"")||null}function $S(){let e=[],t=new Set;for(let[n,r]of Object.entries(Rr.targetDecisionTree))for(let o of r.matchAll(/target:"?(\w+)"?/g)){let i=o[1];!i||t.has(i)||(t.add(i),e.push({target:i,task:n}))}for(let n of Rr.activeTargets)t.has(n)||(t.add(n),e.push({target:n,task:"advanced target; see full schema"}));return e}function HD(){let e=Rr,t=["local","github","npm","materialized"],n=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],r=e.quickStart,o=e.agentBestPractices.find(i=>/snippet/i.test(i));return{schema:"oql",kind:"octocode.search.compactScheme",description:e.description,sources:Object.fromEntries(t.map(i=>[i,BS(e.sourceGuide[i])??"a prior clone / cache fetch / materialize localPath"])),targets:$S(),recipes:Object.fromEntries(n.map(i=>[i,r[i]]).filter(i=>typeof i[1]=="string")),semantics:e.semanticsGuide,proof:{snippets:o,providerUnindexed:e.evidenceSemantics.providerUnindexed},commands:{explain:"search --explain --query '{...}'",fullSchema:"search --scheme"}}}function zD(){return JSON.stringify(HD(),null,2)}function QD(){let e=Rr,t=["octocode search \u2014 compact agent guide (full reference: search --scheme)","","SOURCE \u2014 where to look (choose one):"],n=["local","github","npm","materialized"];for(let s of n){let a=BS(e.sourceGuide[s]);t.push(` ${s.padEnd(13)}${a??"a prior clone / cache fetch / materialize localPath"}`)}t.push("","TARGET \u2014 answer type (--target, or inferred from the args):");for(let{target:s,task:a}of $S())t.push(` ${s.padEnd(13)}${a}`);t.push("","COMMON RECIPES:");let r=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],o=e.quickStart;for(let s of r){let a=o[s];a&&t.push(` ${a}`)}t.push("","LSP SEMANTICS (run documentSymbols first, then narrow):");for(let[s,a]of Object.entries(e.semanticsGuide))t.push(` ${s.padEnd(16)}${a}`);t.push("","PROOF \u2014 snippets are discovery, not proof:");let i=e.agentBestPractices.find(s=>/snippet/i.test(s));return i&&t.push(` ${i}`),t.push(` ${e.evidenceSemantics.providerUnindexed}`),t.push("","Routing debug: search --explain --query '{...}'","Full schema: search --scheme"),t.join(`
52
- `)}ur();Iu();Mu();export{Je as ACTIVE_TARGETS,Mo as CORPUS_OPTIONAL_TARGETS,De as DEFAULTS,Rr as OQL_SCHEMA_DOC,sd as OqlBatchSchema,ZS as OqlCanonicalInputSchema,Ra as OqlInputBatchSchema,ba as OqlInputQuerySchema,Pr as OqlQuerySchema,un as OqlSearchInputSchema,_t as OqlValidationError,Wt as PredicateSchema,Do as QuerySourceSchema,_n as RESERVED_TARGETS,Ku as SEARCH_SORTS_BY_TARGET,ln as StructuralRuleSchema,da as analyzeResearchFlow,Oa as appliedDefaults,Qa as backendCallsForTransformer,Va as backendsApproximate,Sa as blocksAnswer,xr as buildEnvelope,pa as buildResearchPackets,CD as buildShorthandInput,P as diagnostic,qo as findTransformerById,fn as findTransformerEntry,nP as hasErrors,Ju as isBatchEnvelope,Yu as isBatchInput,Xu as isCanonicalBatch,BP as listTransformerEntries,ka as normalizeInput,Ta as normalizeQuery,zD as oqlCompactSchemeJson,QD as oqlCompactSchemeText,GD as oqlSchemaText,qa as planQuery,OS as runOqlSearch,ut as sanitizeStructuredContent,Ko as unsupportedEnvelope};
45
+ `),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let p=o-1;p>=0;p--)for(let h=i-1;h>=0;h--)s[p][h]=n[p]===r[h]?s[p+1][h+1]+1:Math.max(s[p+1][h],s[p][h+1]);let a=[],c=0,l=0,u=0,d=0,m=0;for(;d<o&&m<i;)n[d]===r[m]?(a.push(` ${n[d]}`),u++,d++,m++):s[d+1][m]>=s[d][m+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[m]}`),c++,m++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;m<i;)a.push(`+ ${r[m++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
46
+ `)}}var Qk,Bk=f(()=>{"use strict";tn();J();_s();Ua();fr();Ln();Qk=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/});import Ne from"node:path";function NN(e,t,n){let r=t??n??".";if(!e)return r;if(Ne.isAbsolute(e))return e;if(n&&Ne.isAbsolute(n))return Ne.resolve(n,e);if(t&&Ne.isAbsolute(t)){let o=Ss(t)?t:Ne.dirname(t);return Ne.resolve(o,e)}return e}function zk(){return x("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function GN(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(x("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(x("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push(zk()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push(zk());let i=e?.pagination;return i?.hasMore&&n.push(x("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:uf(i,t)})),n}async function $k(e){let t,n,r=[],o=[],i=St(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let T=e.from.path,_=Ss(T);n=c??(_?Ne.resolve(T):void 0),t=a??(_?void 0:T)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let T=Ie(e.scope),_=T?Ne.isAbsolute(T)?T:Ne.join(e.from.localPath,T):void 0;s?(n=c??e.from.localPath,t=a??_):t=a??_??e.from.localPath}else if(e.from?.kind==="github"){let{owner:T,repo:_}=An(e.from);if(!T||!_)return o.push(x("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,G=Ie(e.scope),M=w&&!Ne.isAbsolute(w)?w:G,A=await we("ghCloneRepo",{owner:T,repo:_,...e.from.ref?{branch:e.from.ref}:{},...M?{sparsePath:M}:{}}),q=En(A).data,H=Ok(A,q?.localPath);if(!H)return o.push(x("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:H}),s?(n=c??H,w?t=Ne.isAbsolute(w)?w:Ne.join(H,w):G&&(t=Ne.isAbsolute(G)?G:Ne.join(H,G))):w?t=Ne.isAbsolute(w)?w:Ne.join(H,w):G?t=Ne.isAbsolute(G)?G:Ne.join(H,G):t=H}if(!t&&!n)return o.push(x("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...m}=i,p=await we("lspGetSemantics",{...m,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:h,status:g}=En(p),y=h,b=_k(y,e),S=NN(is(y?.uri),t,n),C=jN(e,S),E=QN(HN(y),u);return{results:g==="error"?[]:vn(E,"semantics",C),...b?{pagination:b}:{},diagnostics:[...o,...lf(p,"lspGetSemantics"),...GN(y,e)],provenance:[...r,{backend:"lspGetSemantics",source:C}]}}function HN(e){if(!e)return[];let n=(cf(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=is(e.uri);return n.map(o=>cf(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return pl(e)}function QN(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function jN(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}var Uk=f(()=>{"use strict";tn();J();ln();Rs();fr();Ln()});import{builtinModules as BN}from"node:module";var mf,qk,Wk,Vk,xs=f(()=>{"use strict";mf=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],qk="package.json",Wk=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),Vk=new Set(BN.flatMap(e=>[e,`node:${e}`]))});import yl from"node:path";function bl(){if(Cs)return Cs;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Cs=new Set(e.length>0?e:mf)}catch{Cs=new Set(mf)}return Cs}function Kk(){if(ws)return ws;try{let e=JSON.parse(D.getGraphFactCapabilities());ws=Array.isArray(e)?e.filter(zN):[]}catch{ws=[]}return ws}function zN(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function ff(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function Rl(e,t,n){return Sl(yl.resolve(e,t),n)}function Sl(e,t){let n=bl(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(yl.join(e,`index${o}`));return r.find(o=>t.has(o))}function ks(e){return e.startsWith("./")||e.startsWith("../")}function Yk(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function Xk(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function hf(e){return typeof e=="string"&&e.trim()?e:void 0}function Pl(e){return typeof e=="string"&&e.length>0}function Jk(e){return typeof e=="string"}function Zk(e){return[...new Set(e)]}function jt(e,t){return yl.relative(e,t)||yl.basename(t)}function eT(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function tT(e,t){return!!(e===t||e.endsWith(`.${t}`)||e.endsWith(`::${t}`))}var Cs,ws,Ts=f(()=>{"use strict";Ee();xs()});import rn from"node:path";import{readFile as $N,readdir as UN}from"node:fs/promises";async function nT(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await UN(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(Wk.has(s.name))continue;await r(rn.join(o,s.name));continue}s.isFile()&&n.push(rn.join(o,s.name))}}return await r(e),n}async function rT(e){return(await Promise.all(e.map(async n=>qN(n)))).filter(n=>n!==null)}async function qN(e){let t=await WN(e);if(!t)return null;let n=rn.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=Xk(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:hf(t.name),deps:r,entrypoints:VN(n,t)}}async function WN(e){try{let t=JSON.parse(await $N(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function VN(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=hf(t[o]);i&&n.add(rn.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(rn.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(rn.resolve(e,o));oT(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(rn.resolve(e,o));return[...n]}function oT(e,t,n){if(typeof t=="string"){n.add(rn.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))oT(e,r,n)}function iT(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=KN(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:jt(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:jt(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:jt(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function KN(e,t){return t.filter(r=>e.startsWith(`${r.dir}${rn.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}var sT=f(()=>{"use strict";xs();Ts()});import uo from"node:path";import{readFile as YN}from"node:fs/promises";async function aT(e,t){let n=bl(),r=t.filter(i=>n.has(uo.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await YN(i,"utf8").catch(()=>""),a=uo.extname(i).toLowerCase(),c=XN(s,i,jt(e,i)),l=Zk(c?c.imports.map(u=>u.specifier):JN(s));return{path:i,rel:jt(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!ks(u)).map(Yk).filter(Pl).filter(u=>!Vk.has(u)),...c?{graphFacts:c}:{}}}))}function XN(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??uo.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(Jk):[]}}catch{return}}function gf(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...bl()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=ff(e,l=>l.language),s=ff(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function JN(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function cT(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,uo.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??uo.dirname(o.path);for(let a of o.imports){if(!ks(a))continue;let c=Rl(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function lT(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=Sl(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","lib.rs","main.rs","mod.rs"]){let s=Sl(uo.resolve(e,i),r);s&&o.add(s)}return[...o]}function uT(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}var dT=f(()=>{"use strict";Ee();xs();Ts()});import ZN from"node:path";import{readFile as pT}from"node:fs/promises";async function mT(e){return(await Promise.all(e.map(async n=>{let r=eG(n);if(r.length>0)return r;let o=await pT(n.path,"utf8").catch(()=>"");return tG(n.rel,o)}))).flat()}function eG(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function tG(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:eT(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function fT(e,t,n){let r=new Map(t.map(a=>[a.rel,a])),o=new Map(t.map(a=>[a.path,a])),i=new Set(t.map(a=>a.path)),s=nG(t);return e.map(a=>{let c=r.get(a.file),l=rG(a,t,c,s,i,o),u=l.length>0?"ast":"ripgrep",d=l.length>0?l:t.filter(g=>g.rel!==a.file&&oG(g.path,a.symbol)).map(g=>g.rel),m=d.filter(g=>{let y=r.get(g);return y?n.has(y.path):!1}),p=c?n.has(c.path):!1,h=m.length>0?"reachable":d.length>0?"transitive-dead":p?"candidate-unused-export":"unused-export";return{symbol:a.symbol,kind:a.kind,file:a.file,line:a.line,evidenceSource:a.evidenceSource,retentionSource:u,directRefs:d.length,externalRefs:m.length,retainedBy:d,verdict:h}})}function nG(e){let t=new Map;for(let n of e){let r=n.graphFacts;if(r){for(let o of r.declarations){if(!o.exported)continue;let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}for(let o of r.exports){let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}}}return t}function rG(e,t,n,r,o,i){let s=r.get(e.symbol)??(n?new Set([n.path]):new Set),a=new Set;for(let c of t){if(c.rel===e.file)continue;let l=c.graphFacts;if(l){for(let u of l.imports){let d=u.importedName&&u.importedName!=="default"?u.importedName:void 0,m=u.localName;if(!(d===e.symbol||m===e.symbol)||!ks(u.specifier))continue;let h=Rl(ZN.dirname(c.path),u.specifier,o);if(h&&s.has(h)){a.add(c.rel);break}}if(!a.has(c.rel)){for(let u of l.calls)if(tT(u.callee,e.symbol)){a.add(c.rel);break}}}}return[...a].sort()}function oG(e,t){return yf.get(e)?.has(t)??!1}async function hT(e){yf.clear(),await Promise.all(e.map(async t=>{let n=await pT(t.path,"utf8").catch(()=>"");yf.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}var yf,gT=f(()=>{"use strict";Ts();yf=new Map});import iG from"node:path";async function Es(e){let t=iG.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=sG(r,e.intent,e.facets),i=aG(o,e.facets),s=cG(o,i),a=Kk();if(n==="plan")return lG({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:gf([],[],a)});let c=await nT(t,e.maxFiles??5e3),l=await rT(c.filter(w=>w.endsWith(qk))),u=await aT(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),m=gf(u,d,a);await hT(u);let p=new Set(l.map(w=>w.name).filter(Pl)),h=cT(u),g=lT(t,l,u),y=uT(g,h),b=u.filter(w=>!y.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=iT(t,l,u,p),C=await mT(u),E=fT(C,u,y),T=E.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,_=E.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:y.size,unusedFiles:b.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:E.length,candidateUnusedExports:T,transitiveDeadExports:_,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,G)=>w+G.declarations.length,0),nativeGraphCalls:d.reduce((w,G)=>w+G.calls.length,0)},manifests:l.map(w=>({manifest:jt(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(G=>jt(t,G)),dependencyCount:[...w.deps.keys()].length})),files:b,dependencies:S,symbols:E,graphFacts:d,graphCapabilities:m,caveats:["Analyze uses native AST graph facts for inventory and preferred cross-file retention (named imports / call callees). Lexical token scan is fallback only when AST finds no retainers.",'Graph facts are syntax inventory, not semantic identity. Upgrade candidates with target:graph proof:"lsp" (or lspGetSemantics references/callers) before destructive cleanup.',"Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function sG(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function aG(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function cG(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["extractGraphFacts","export regex fallback"],produces:["symbols","lineHints"],evidence:"heuristic"},{id:"reference-scan",purpose:"Candidate cross-file retention from native AST imports/calls (preferred) with lexical token fallback. Upgrade via target:graph proof:lsp \u2014 analyze does not run LSP.",tools:["extractGraphFacts","token scan fallback"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"heuristic"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function lG(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}var xl=f(()=>{"use strict";sT();dT();gT();xs();Ts()});async function yT(e){let t=St(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=hl(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await Es({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[x("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:co(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?pr(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?Ak(e,i):{fields:{}},m={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:ys(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},p=Lk(l?.pagination,d.pagination);return{results:vn([m],"research",e.from),...p?{pagination:p}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}var bT=f(()=>{"use strict";J();xl();fs();bs();fr();Rs();Ln()});import Cl from"node:path";function Rf(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function ST(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function PT(e,t,n,r,o){let i=n.filter(l=>hs(l,r)),s=pr(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await dG(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(x(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(x("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),uG(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(x("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function uG(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function dG(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=Cl.isAbsolute(t.subject.uri)?t.subject.uri:Cl.resolve(e,t.subject.uri);try{let i=await we("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=pG(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=En(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:is(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,m=no(a?.totalReferences)??no(u?.totalReferences)??no(a?.referenceCount)??no(u?.referenceCount)??no(d?.totalItems)??RT(u)??RT(a);return{status:"ok",...typeof m=="number"?{totalReferences:m}:{},files:mG(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function pG(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function RT(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function mG(e,t){let n=new Set;return bf(e,n,t),[...n].slice(0,25)}function bf(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)bf(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&fG(i)&&t.add(Cl.isAbsolute(i)?Cl.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])bf(r[o],t,n)}function fG(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var xT=f(()=>{"use strict";tn();J();bs()});async function CT(e){let t=St(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=hl(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await Es({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[x("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:co(i),a=sf(t),c=s?.packets??[],l=Rf(i.mode,t)?await PT(n,e,c,a,ST(e,t)):[],u=wk(c),d=Ck(e,c,u,a,i.graphFacts,n),m=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[Rf(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],p={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:ys(i.graphFacts),caveats:m};return{results:vn([p],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var wT=f(()=>{"use strict";J();xl();fs();bs();xT();fr();Rs();Ln()});var kT,TT=f(()=>{"use strict";Mk();Gk();Bk();Uk();bT();wT();kT={repositories:Fk,packages:Ik,pullRequests:df,commits:df,diff:jk,semantics:$k,research:yT,graph:CT}});function hG(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function ET(e,t,n,r,o,i){let s=o&&i?gG(i):[],a=o&&i?yG(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:xo(e.plan.diagnostics,t,n,r,hG(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function gG(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[x("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function yG(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}var OT=f(()=>{"use strict";J();xr()});function vT(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):RG.has(c)?o.add(c):SG.has(c)?o.add("data"):PG.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!bG.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[x("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}var bG,RG,SG,PG,AT=f(()=>{"use strict";J();bG=new Set(["kind","source","recordType","id","proofGrade"]),RG=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","matchKind","scoreHint","proofGrade","size","modified","entryType","depth","children","data"]),SG=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),PG=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});function Os(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function wl(e,t,n,r){let o=Jl(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return ET(o,s,e.id,r,n.dryRun,e);let a=await wG(e,o);Oh(e,a.results),xG(e,a),CG(a);let c=jh(e,a);Ah(e,a.results);let l=vT(e,a.results),u=Bh(a.results);return Pr({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:eu(o.plan.backendCalls),plan:s})}function xG(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function CG(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}async function wG(e,t){if(e.target==="materialize")return fk(e);let n=kT[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?ms(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?mk(e):Mw(e)}var Sf=f(()=>{"use strict";Dw();rf();hk();TT();xr();Zl();ou();OT();tu();nu();AT()});async function LT(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await wl(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=kG(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&Os(o.merged.results)}else for(let i of r)Os(i.envelope.results);return o}function kG(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let m=vG(d);n.has(m)||(n.add(m),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),TG(s,u.envelope.nextHints),EG(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),OG(u.envelope)&&(l=!0)}return l&&o.push(x("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Pr({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function TG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||ru(o,r))&&(e[n]=r)}}function EG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function OG(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function vG(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var _T=f(()=>{"use strict";J();xr();ou();Sf()});var dw={};YT(dw,{runOqlSearch:()=>FT});async function FT(e,t={}){let n;try{n=Nl(e)}catch(o){if(o instanceof Ot)return xo(o.diagnostics);throw o}if(El(n))return LT(n,e,t);let r=await wl(n,e,t);return Os(r.results),r}var Mm=f(()=>{"use strict";Gl();J();xr();Pt();_T();Sf()});Pt();Fn();Gl();Zl();Fs();J();xr();Mm();Pt();function DT(e){let t=AG(e);if(e.filesWithoutMatch){let r=IT(e);if("error"in r||!r.where)return r;let o={kind:"not",predicate:r.where};return{where:t.length?{kind:"all",of:[...t,o]}:o}}let n=e.search==="path"?LG(e):IT(e);return"error"in n?n:t.length&&n.where?{where:{kind:"all",of:[...t,n.where]}}:t.length===1?{where:t[0]}:t.length>1?{where:{kind:"all",of:t}}:n}function AG(e){let t=[];e.filesOnly?t.push({kind:"field",field:"entryType",op:"=",value:"file"}):(e.directoriesOnly||e.entryType)&&t.push({kind:"field",field:"entryType",op:"=",value:e.directoriesOnly?"directory":e.entryType}),e.extension&&t.push({kind:"field",field:"extension",op:"=",value:e.extension.replace(/^\./,"")}),e.filename&&t.push({kind:"field",field:"basename",op:"glob",value:MT(e.filename)}),e.pathPattern&&t.push({kind:"field",field:"path",op:"glob",value:MT(e.pathPattern)}),e.sizeGreater&&t.push({kind:"field",field:"size",op:">",value:e.sizeGreater}),e.sizeLess&&t.push({kind:"field",field:"size",op:"<",value:e.sizeLess}),e.modifiedWithin&&t.push({kind:"field",field:"modified",op:"within",value:e.modifiedWithin}),e.modifiedBefore&&t.push({kind:"field",field:"modified",op:"before",value:e.modifiedBefore}),e.accessedWithin&&t.push({kind:"field",field:"accessed",op:"within",value:e.accessedWithin}),e.empty&&t.push({kind:"field",field:"empty",op:"=",value:!0}),e.permissions&&t.push({kind:"field",field:"permissions",op:"=",value:e.permissions});for(let[n,r]of[["executable",e.executable],["readable",e.readable],["writable",e.writable]])r&&t.push({kind:"field",field:n,op:"=",value:!0});return t}function IT(e){let t=e.lang;return e.pattern!==void 0?t?{where:{kind:"structural",lang:t,pattern:e.pattern}}:{error:"--pattern requires --lang (e.g. --lang ts)."}:e.rule!==void 0?t?{where:{kind:"structural",lang:t,rule:e.rule}}:{error:"--rule requires --lang (e.g. --lang ts)."}:e.regex!==void 0?e.fixedString?{where:{kind:"text",value:e.regex,...Pf(e),...e.wholeWord?{wholeWord:!0}:{}}}:{where:{kind:"regex",value:e.regex,...e.pcre2?{dialect:"pcre2"}:{},...Pf(e),...e.wholeWord?{wholeWord:!0}:{},...e.multiline?{multiline:!0}:{},...e.multilineDotall?{dotAll:!0}:{}}}:e.text!==void 0&&e.text!==""?{where:{kind:"text",value:e.text,...Pf(e),...e.wholeWord?{wholeWord:!0}:{}}}:{}}function LG(e){if(e.regex!==void 0)return{where:{kind:"field",field:"path",op:"regex",value:e.regex}};if(e.text!==void 0&&e.text!==""){let t=/[/*?[\]]/.test(e.text);return{where:{kind:"field",field:t?"path":"basename",op:"glob",value:t?e.text:`*${e.text}*`}}}return{}}function MT(e){return/[*?[\]]/.test(e)?e:`*${e}*`}function Pf(e){return e.caseSensitive?{case:"sensitive"}:e.caseInsensitive?{case:"insensitive"}:{}}function Bt(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function NT(e){return e.split(",").map(t=>t.trim().replace(/^\./,"")).filter(Boolean)}function GT(e){return e==="name"||e==="size"||e==="time"||e==="extension"}function QT(e){let t={};e.countLinesPerFile&&(t.countLinesPerFile=!0),e.countMatchesPerFile&&(t.countMatchesPerFile=!0),e.onlyMatching&&(t.onlyMatching=!0),e.unique&&(t.unique=!0),e.countUnique&&(t.countUnique=!0),e.contextLines!==void 0&&(t.contextLines=e.contextLines),e.invertMatch&&(t.invertMatch=!0),e.matchWindow!==void 0&&(t.matchWindow=e.matchWindow),e.matchContentLength!==void 0&&(t.matchContentLength=e.matchContentLength),e.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=e.maxMatchesPerFile),e.matchPage!==void 0&&(t.matchPage=e.matchPage),HT(e.target)&&e.sort&&(t.sort=e.sort),HT(e.target)&&e.sortReverse&&(t.sortReverse=!0),e.rankingProfile&&(t.rankingProfile=e.rankingProfile),e.debugRanking&&(t.debugRanking=!0);let n={};e.maxFiles!==void 0&&(n.maxFiles=e.maxFiles);let r={};return Object.keys(t).length>0&&(r.search=t),Object.keys(n).length>0&&(r.budget=n),Object.keys(r).length>0?r:void 0}function HT(e){return e==="code"||e==="files"}function jT(e){let t={},n=$T(e.contentView);n&&(t.contentView=n),(e.startLine!==void 0||e.endLine!==void 0||e.contextLines!==void 0)&&(t.range={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...e.contextLines!==void 0?{contextLines:e.contextLines}:{}}),e.matchString&&(t.match={text:e.matchString,...e.matchRegex?{regex:!0}:{},...e.matchCaseSensitive?{caseSensitive:!0}:{}}),e.charOffset!==void 0&&(t.charOffset=e.charOffset),e.charLength!==void 0&&(t.charLength=e.charLength),e.fullContent&&(t.fullContent=!0);let r={};e.maxDepth!==void 0?r.maxDepth=e.maxDepth:e.tree&&e.depth!==void 0&&(r.maxDepth=e.depth),e.filename?r.pattern=e.filename:e.pattern&&(e.tree||e.target==="structure")&&(r.pattern=e.pattern),e.includeSizes&&(r.includeSizes=!0),e.extension&&(r.extensions=NT(e.extension)),e.filesOnly&&(r.filesOnly=!0),(e.directoriesOnly||e.entryType==="directory")&&(r.directoriesOnly=!0),GT(e.sort)&&(r.sortBy=e.sort),e.sortReverse&&(r.reverse=!0);let o={};return Object.keys(t).length>0&&(o.content=t),Object.keys(r).length>0&&(o.tree=r),Object.keys(o).length>0?o:void 0}function BT(e){if(!e.materialize&&!e.forceRefresh)return;let t=e.materialize??"auto";return e.forceRefresh?{mode:t,forceRefresh:!0}:t}function zT(e){return e?e==="discovery"||e==="paginated"||e==="detailed"?{view:e}:{error:`--view must be discovery, paginated, or detailed (got "${e}").`}:{}}var _G={none:"none",exact:"none",standard:"standard",compact:"standard",symbols:"symbols"};function $T(e){return e!==void 0?_G[e]:void 0}function UT(e){return!!($T(e.contentView)||e.matchString||e.startLine!==void 0||e.endLine!==void 0||e.charOffset!==void 0||e.charLength!==void 0||e.fullContent)}function qT(e){switch(e.target){case"code":return Bt({concise:e.concise,extension:e.extension,filename:e.filename});case"semantics":return Bt({type:e.op??"documentSymbols",uri:e.uri,symbolName:e.symbol,symbolKind:e.symbolKind,lineHint:e.line,orderHint:e.order,depth:e.depth,workspaceRoot:e.workspaceRoot,format:e.format});case"repositories":return Bt({keywords:e.text?e.text.includes(" ")?e.text.split(/\s+/).filter(Boolean):[e.text]:void 0,topicsToSearch:e.topic?.length?e.topic:void 0,language:e.lang,owner:e.owner,stars:e.stars,forks:e.forks,goodFirstIssues:e.goodFirstIssues,license:e.license,created:e.created,updated:e.updated,size:e.size,match:e.match,archived:e.archived,visibility:e.visibility,concise:e.concise,sort:e.sort,limit:e.limit,page:e.page});case"packages":return Bt({packageName:e.text,page:e.page});case"pullRequests":return Bt({keywordsToSearch:e.text?[e.text]:void 0,query:void 0,concise:e.concise,state:e.state,author:e.author,label:e.label,prNumber:e.prNumber,head:e.head,base:e.base,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,draft:e.draft,archived:e.archived,sort:e.sort,order:e.orderDirection,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,charOffset:e.charOffset,charLength:e.charLength,content:FG(e),limit:e.limit,page:e.page,matchString:e.matchString,matchScope:e.matchString?"all":void 0});case"commits":return Bt({path:e.corpus.kind==="github"?e.corpus.path:void 0,branch:e.branch,since:e.since,until:e.until,author:e.author,includeDiff:e.patches,limit:e.limit,page:e.page,filePage:e.filePage,itemsPerPage:e.itemsPerPage});case"diff":{let t=e.corpus.kind==="local"&&e.diffPath!==void 0;return Bt({prNumber:e.prNumber,baseRef:e.baseRef??(t?"base":void 0),headRef:e.headRef??(t?"head":void 0),path:e.diffPath??(e.corpus.kind==="github"?e.corpus.path:void 0)})}case"research":case"graph":return Bt({goal:e.text,intent:e.intent,facets:e.facets,proof:e.proof,proofLimit:e.proofLimit,includePackets:e.includePackets,includeFacts:e.includeFacts,includeEdges:e.includeEdges,maxFiles:e.maxFiles});default:return{}}}function FG(e){if(!(!e.patches&&!e.patchFile&&!e.commentsContent&&!e.commitsContent&&!e.deep))return Bt({metadata:!0,body:e.deep?!0:void 0,changedFiles:e.deep||e.patches||e.patchFile?!0:void 0,patches:e.patchFile?{mode:"selected",files:[e.patchFile]}:e.deep||e.patches?{mode:"all"}:void 0,comments:e.deep||e.commentsContent?{discussion:!0,reviewInline:!0}:void 0,reviews:e.deep?!0:void 0,commits:e.deep||e.commitsContent?{list:!0}:void 0})}function IG(e){let t=MG(e);if("error"in t)return t;let n=t.target;if(e.search==="both"){let o=xf({...e,target:"files",search:"path"});if("error"in o)return o;let i=xf({...e,target:n==="files"?"code":n,search:"content"});return"error"in i?i:{input:{schema:"oql",queries:[o.query,i.query],combine:"independent",...e.limit!==void 0?{limit:e.limit}:{},...e.page!==void 0?{page:e.page}:{},...e.itemsPerPage!==void 0?{itemsPerPage:e.itemsPerPage}:{}}}}let r=xf({...e,target:n});return"error"in r?r:{input:r.query}}function xf(e){let t=zT(e.view);if("error"in t)return t;let n=NG(e),o=e.target==="code"||e.target==="files"?DT(e):{};if("error"in o)return o;if(["code","files"].includes(e.target)&&o.where===void 0&&!e.filesOnly&&!e.filesWithoutMatch)return{error:"No search term: provide text, --regex, --pattern, or --rule."};let s={schema:"oql",target:e.target,...n};o.where&&(s.where=o.where),t.view&&(s.view=t.view),e.limit!==void 0&&(s.limit=e.limit),e.page!==void 0&&(s.page=e.page),e.itemsPerPage!==void 0&&(s.itemsPerPage=e.itemsPerPage);let a=BT(e);a&&(s.materialize=a);let c=jT(e);c&&(s.fetch=c);let l=QT(e);l&&(s.controls=l);let u=qT(e);return Object.keys(u).length>0&&(s.params=u),{query:s}}function MG(e){let t=e.target;return t?DG(t)?{target:t}:{error:`--target must be one of: ${Ye.join(", ")}.`}:e.op||e.symbol||e.uri||e.workspaceRoot?{target:"semantics"}:e.tree?{target:"structure"}:UT(e)?{target:"content"}:e.search==="path"?{target:"files"}:e.corpus.kind==="npm"?{target:"packages"}:{target:"code"}}function DG(e){return Ye.includes(e)}function NG(e){let t={};if(e.lang&&(t.language=e.lang),e.include?.length&&(t.include=e.include),e.excludeDir?.length&&(t.excludeDir=e.excludeDir),e.extension){let n=e.extension.replace(/^\./,"");t.include=[...t.include??[],`**/*.${n}`]}if(e.exclude?.length&&(t.exclude=e.exclude),e.hidden&&(t.hidden=!0),e.noIgnore&&(t.noIgnore=!0),e.minDepth!==void 0&&(t.minDepth=e.minDepth),e.maxDepth!==void 0&&(t.maxDepth=e.maxDepth),ho.includes(e.target)&&e.corpus.kind==="local")return Object.keys(t).length>0?{scope:t}:{};if(e.corpus.kind==="npm")return{from:{kind:"npm"},...Object.keys(t).length>0?{scope:t}:{}};if(e.corpus.kind==="github"){let n={kind:"github",repo:e.corpus.repo,...e.branch||e.corpus.ref?{ref:e.branch??e.corpus.ref}:{}};return e.corpus.path&&(t.path=e.corpus.path),{from:n,...Object.keys(t).length>0?{scope:t}:{}}}return{from:{kind:"local",path:e.corpus.path},...Object.keys(t).length>0?{scope:t}:{}}}zl();Fs();Pt();var po={schema:"oql",description:"octocode search \u2014 typed read-only queries over code, files, symbols, repos, packages, history, diffs, and graph evidence. Think source + answer type + filters + read/output options; use --explain for routing; follow next.* for pages, exact reads, materialization, or proof.",activeTargets:Ye,reservedTargets:_n,sourceGuide:{local:'from:{kind:"local",path:"./src"}; shorthand: search "term" ./src, search ./src --tree, search file.ts --op documentSymbols. Best for local code/content/files/tree/LSP/diff.',github:'from:{kind:"github",repo:"owner/repo",ref?}; shorthand: search "term" owner/repo, search owner/repo --tree, search owner/repo#123 --target pullRequests. GitHub code is indexed/default-branch scoped; materialize for AST/LSP/local proof.',npm:'from:{kind:"npm"} with target:"packages"; shorthand: search zod --target packages. Use to resolve package metadata and source repo, then continue with GitHub or local/materialized proof.',materialized:'from:{kind:"materialized",localPath:"/abs/path"} after target:"materialize", clone, or cache fetch. Use when a remote repo/subtree must behave like local code.'},plainLanguage:{source:"`from` = where to look: local path, GitHub repo, npm, or a materialized checkout.",answerType:"`target` = what kind of answer you want: code matches, file content, tree, files, symbols, repos, packages, PRs, commits, diffs, research packets, graph proof, or materialization.",filters:"`where` = match/filter conditions for code and file discovery only: text, regex, AST shape, file fields, and boolean combinations.",readOptions:"`fetch` = what to read once you know the file/tree: exact content, compact content, symbol outline, ranges, match slices, or tree depth.",targetOptions:"`params` = options that belong to one answer type, such as LSP operation, PR number, package name, research intent, or graph proof.",output:"`view`, `select`, and `controls` = response shape, projected fields, search tuning, and cost limits.",paging:"`page` + `itemsPerPage` page the target's primary result domain. For code search that may be matched files; per-file match paging uses `controls.search.matchPage` / `--match-page`."},targetDecisionTree:{"find a string/pattern in code":"target:code (shorthand default for text/regex/--pattern/--rule; needs a where filter)","read or slice a known file":"target:content (file positional + --content-view, --start-line/--end-line, or --match-string)","see the file/dir layout":"target:structure (--tree)","find files by name/glob/ext/size/mtime":"target:files (--search path, --name/--ext/--size-greater/--modified-within)","symbol defs/refs/callers/hover":"target:semantics (--op \u2026; local or materialized only)","search GitHub repos":"target:repositories (--stars/--lang/--topic)","resolve an npm package":"target:packages","PR list or deep-read":"target:pullRequests (owner/repo#N)","commit history":"target:commits (--since/--until)","a diff":"target:diff ({prNumber} for a PR patch, {baseRef,headRef,path} for two refs)","dead-code / reachability sweep":'target:research, then upgrade with target:graph proof:"lsp"',"make a remote repo behave like local (AST/LSP/negation)":"target:materialize (or clone / cache fetch)"},agentBestPractices:["Start with cheap orientation: --tree, --search path, --view discovery, or --content-view symbols.","Then narrow and read exact evidence: --match-string, --start-line/--end-line, --char-offset/--char-length, or --content-view none.","Use snippets as discovery only; make decisions from exact content, PR/commit metadata, or LSP/graph proof.","For semantics, run documentSymbols first to get line anchors, then references/callers/hover with symbolName + lineHint.","For GitHub zero rows / providerUnindexed, do NOT claim absence \u2014 follow evidenceSemantics.providerUnindexed (verify path with structure, then materialize a bounded path).","Read evidence.answerReady, evidence.complete, diagnostics, pagination, and next.* before concluding."],quickStart:{"text search (local)":'search "functionName" ./src',"text search (GitHub)":'search "functionName" vercel/next.js',"package lookup (npm)":"search zod --target packages","PR deep read (GitHub)":"search vercel/next.js#1 --target pullRequests --comments --patches","commit history (GitHub)":"search vercel/next.js/packages/next/src --target commits --since 2024-01-01T00:00:00Z","browse a tree (local dir or owner/repo)":"search ./src --tree | search vercel/next.js --tree","read a file (local or owner/repo/path)":"search ./src/index.ts | search vercel/next.js/packages/next/src/server/config.ts","read a remote file (exact)":"search vercel/next.js/README.md --content-view none","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","PR diff (GitHub)":"search vercel/next.js#123 --target diff | search vercel/next.js --target diff --pr 123","two-ref / two-file diff":"search src/a.ts src/b.ts --target diff | search owner/repo --target diff --base-ref <sha> --head-ref <sha> --path <file>","structural AST (local \u2014 needs full node shape)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" ./src --lang ts',"structural AST (GitHub \u2014 clones bounded subtree)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" vercel/next.js/packages/next/src --lang ts --materialize auto',"GitHub index miss recovery":"search useState packages/next/src --repo vercel/next.js --materialize required | clone vercel/next.js/packages/next/src | cache fetch vercel/next.js packages/next/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},semanticsGuide:{documentSymbols:"list a file's symbols to get line anchors first (run before references/callers/hover)",references:"all usages of a symbol across the workspace (often includes its declaration)",callers:"incoming calls to a function/method (call sites only) \u2014 narrower than references",hover:"type, signature, and docs at a symbol"},query:{schema:'"oql" (inserted by normalization)',target:Ye.join(" | "),from:'{ kind:"local", path } | { kind:"github", repo?, owner?, ref? } | { kind:"materialized", localPath, source? } | { kind:"npm" } \u2014 local row.path is relative to from.path; the pre-filled next.fetch carries the resolved ABSOLUTE path, so follow it directly rather than re-joining paths yourself',scope:"{ path?, language?, include?, exclude?, excludeDir?, hidden?, noIgnore?, minDepth?, maxDepth? } \u2014 minDepth/maxDepth bound directory recursion depth (0-64)",where:"filters for code/files only: text | regex | structural | field | all | any | not. To read a matched file slice, use fetch.content.match. For PR/commit text narrowing, use that target params hint.",materialize:'{ mode:"never"|"auto"|"required", strategy?:"file"|"tree"|"subtree"|"repo", allowFullRepo?, forceRefresh? }',fetch:'{ content?: { contentView:"none"|"standard"|"symbols", fullContent?, match?:{text|regex,case?}, range?:{startLine?,endLine?,contextLines?}, charOffset?, charLength? }, tree?:{ maxDepth?, pattern?, includeSizes?, extensions?, filesOnly?, directoriesOnly?, sortBy?:"name"|"size"|"time"|"extension", reverse? } } \u2014 read options for known files/trees; fetch.content.fullContent:true returns the WHOLE file in one shot (lossless, no char-window paging); to read the region around a string, anchor with fetch.content.match (NOT a top-level where, which is code/files only)',params:"target options (validated by OQL for common fields and by the backing tool exhaustively) \u2014 see params hints below",select:"string[] projection of result/continuation fields",view:"discovery | paginated | detailed",controls:'{ search?: { countLinesPerFile?, countMatchesPerFile?, onlyMatching?, unique?, countUnique?, contextLines?, invertMatch?, matchWindow?, matchContentLength?, maxMatchesPerFile?, matchPage?, sort?:"relevance"|"matchCount"|"path"|"modified"|"accessed"|"created"|"size"|"name", sortReverse?, rankingProfile?, debugRanking? }, budget?: { maxFiles?, maxCandidates?, maxBytes?, maxMaterializedBytes?, maxPlanNodes?, maxBooleanExpansion?, timeoutMs? } } \u2014 output/cost controls; sort values "size"/"name" apply to target:"files" only (lowered to localFindFiles sortBy), the rest are code-search sorts',limit:"number \u2014 total result cap where supported. Prefer itemsPerPage for paged research/graph/file-history continuations.",page:"number \u2014 top-level page number for OQL windowing/continuations",itemsPerPage:"number \u2014 page size for the target primary result domain. For code search this may be matched files, not individual matches; per-file match paging uses controls.search.matchPage. Per-target params expose backing-tool sub-pages only (filePage/commentPage/commitPage, etc.).",explain:"boolean"},params:{semantics:'{ type:"definition"|"references"|"callers"|"callees"|"callHierarchy"|"hover"|"documentSymbols"|"typeDefinition"|"implementation"|"workspaceSymbol"|"supertypes"|"subtypes"|"diagnostic", uri?, symbolName?, symbolKind?, lineHint?, orderHint?, depth?, contextLines?, includeDeclaration?, groupByFile?, workspaceRoot?, format? } \u2014 backing tool lspGetSemantics; contextLines adds call-flow snippets; symbolKind filters returned symbol rows after documentSymbols/workspaceSymbol',repositories:"{ keywords?: string[], topicsToSearch?: string[], language?, owner?, stars?, license?, sort?, archived?, limit?, page? } \u2014 backing tool ghSearchRepos; keywords/topicsToSearch are arrays even for one term",packages:'{ packageName?: string | keywords?: string[], mode?:"lean"|"full", page? } \u2014 backing tool npmSearch',pullRequests:'{ state?:"open"|"closed"|"merged", author?, label?, keywordsToSearch?, prNumber?, reviewMode?, filePage?, commentPage?, commitPage?, limit?, page?, matchString?, matchScope?:"body"|"title"|"comments"|"reviews"|"all", content? } \u2014 backing tool ghHistoryResearch; matchString filters fetched PR title/body/comments/reviews per matchScope (default body), not a search-index query \u2014 no match \u2192 zeroMatches',commits:'{ path?, branch?, since?, until?, includeDiff?, limit?, page?, filePage?, itemsPerPage?, matchString? } \u2014 backing tool ghHistoryResearch type:"commits"; matchString filters commit messages; repo/directory diffs page changed files per commit with filePage/itemsPerPage',diff:"{ prNumber, files? } (PR patch via ghHistoryResearch) | { baseRef, headRef, path } (direct two-ref file diff via ghGetFileContent + local line diff); neither shape -> invalidQuery repair",research:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:("symbols"|"files"|"dependencies"|"relations")[], mode?:"plan"|"analyze"|"prove", maxFiles? } \u2014 TWO-PHASE: page:1+itemsPerPage:1 \u2192 data.summary (full-scope counts) and may include a bounded first packet page; page:2+ \u2192 data.packets[] continuation pages (candidates w/ retainedBy edges + per-packet next.*). Always evidence:"candidate"/answerReady:false (normal). Follow the row's pre-filled next.graph (proof:"lsp", proofLimit-bounded) to upgrade a page to LSP-proven proofStatus.`,graph:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:(\u2026)[], mode?:"plan"|"analyze"|"prove", maxFiles?, subject?, subjectKind?, relation?, verdict?, direction?:"incoming"|"outgoing"|"both", proof?:"none"|"lsp", proofLimit?, includePackets?, includeFacts?, includeEdges? } \u2014 UPGRADE PATH: run a research row's pre-filled next.graph directly. proof:"lsp" sets per-row proofStatus: "confirmed-by-lsp" (refs=0 in bounded workspace; still inspect entrypoints/exports before deletion), "conflicting-evidence" (refs>0 \u2192 retained, check retainedBy), "needs-framework-graph" (maybe an entrypoint). answerReady:false is normal \u2014 follow next.* for more pages/proof.`,materialize:'(no params; no `where`) clone/cache a bounded corpus (from:{kind:"github",repo} + scope.path) and return a stable materialized checkpoint row (localPath/repoRoot/ref/cache/complete) with next.structure/next.files. Use after GitHub providerUnindexed; for CLI alternatives use clone owner/repo[/path] or cache fetch owner/repo [path] --depth file|tree|clone.'},predicates:{text:'{ kind:"text", value, case?, wholeWord? }',regex:'{ kind:"regex", value, dialect?:"rust"|"pcre2"|"provider", case?, wholeWord?, multiline?, dotAll? }',structural:'{ kind:"structural", lang, pattern? | rule? } (exactly one; rule is a JSON object or grep-compatible YAML rule string) \u2014 pattern must match the COMPLETE node, so include the parts the real node has: a fn WITH a return type only matches if the pattern has one too (`function $N($$$A): $R { $$$B }`); omitting it returns 0. Shapes: `function $N($$$A) { $$$B }` (no-return-type fn), `($$$A) => $$$B` (arrow, block+expression), `$F($$$A)` (call), `$O.$M($$$A)` (method). For "find symbol X" the ROBUST form is a rule, not a pattern: `{ kind:"function_declaration", has:{ pattern:"X" } }`. 0 matches + no parse error = pattern shape \u2260 real node (add `: $R`, or switch to a rule). Note: $$$-only patterns skip files with no literal anchor \u2192 low counts; add a literal name or use a regex where.',field:'{ kind:"field", field:"path"|"basename"|"extension"|"size"|"modified"|"accessed"|"empty"|"permissions"|"executable"|"readable"|"writable"|"entryType", op:"="|"!="|"in"|"exists"|"glob"|"regex"|">"|">="|"<"|"<="|"within"|"before", value? } (use symbolic ops like "="; aliases such as "eq" are invalid; there is no "contains" op \u2014 use op:"glob", value:"*term*" or op:"regex"; "within"/"before" compare modified/accessed times; empty/executable/readable/writable are boolean file attributes paired with op:"exists" or op:"=") SCOPE: field predicates evaluate file attributes, so they run on target:"files" (and mixed into files-lane booleans); target:"code" rejects a bare field predicate with unsupportedPredicate \u2014 use text/regex/structural for code content, or target:"files" for file discovery.',boolean:'{ kind:"all"|"any", of: Predicate[] } | { kind:"not", predicate }',booleanSugar:"Top-level sugar keys lower to canonical booleans at normalize time: and:[...]\u2192all, or:[...]\u2192any, noneOf:[...]\u2192not(any), xor:[a,b]\u2192any(all(a,not b),all(not a,b)), oneOf:[...]\u2192exactly-one expansion (bounded by controls.budget.maxBooleanExpansion), invert:true\u2192not(where). Prefer canonical all/any/not in programmatic queries; sugar is for terse hand-written ones."},batch:{queries:"OqlQuery[] (1-5)",combine:"independent | merge"},explainRoutes:{PUSHDOWN:"Backend evaluates this predicate exactly \u2014 good. No residual work.",RESIDUAL:"Backend narrows candidates but OQL must finish evaluation locally.",ROUTE:"OQL must use a different lane, often materialization.",UNSUPPORTED:"OQL cannot execute this predicate safely on the chosen source."},defaults:$e};function GG(){return JSON.stringify(po,null,2)}function WT(e){let t="shorthand: ",n=e.indexOf(t);if(n===-1)return null;let r=e.slice(n+t.length).trim(),o=r.length,i=r.indexOf(",");i!==-1&&(o=Math.min(o,i));let s=r.search(/\.\s/);return s!==-1&&(o=Math.min(o,s)),r.slice(0,o).trim().replace(/\.$/,"")||null}function VT(){let e=[],t=new Set;for(let[n,r]of Object.entries(po.targetDecisionTree))for(let o of r.matchAll(/target:"?(\w+)"?/g)){let i=o[1];!i||t.has(i)||(t.add(i),e.push({target:i,task:n}))}for(let n of po.activeTargets)t.has(n)||(t.add(n),e.push({target:n,task:"advanced target; see full schema"}));return e}function HG(){let e=po,t=["local","github","npm","materialized"],n=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],r=e.quickStart,o=e.agentBestPractices.find(i=>/snippet/i.test(i));return{schema:"oql",kind:"octocode.search.compactScheme",description:e.description,sources:Object.fromEntries(t.map(i=>[i,WT(e.sourceGuide[i])??"a prior clone / cache fetch / materialize localPath"])),targets:VT(),recipes:Object.fromEntries(n.map(i=>[i,r[i]]).filter(i=>typeof i[1]=="string")),semantics:e.semanticsGuide,proof:{snippets:o,providerUnindexed:e.evidenceSemantics.providerUnindexed},commands:{explain:"search --explain --query '{...}'",fullSchema:"search --scheme"}}}function QG(){return JSON.stringify(HG(),null,2)}function jG(){let e=po,t=["octocode search \u2014 compact agent guide (full reference: search --scheme)","","SOURCE \u2014 where to look (choose one):"],n=["local","github","npm","materialized"];for(let s of n){let a=WT(e.sourceGuide[s]);t.push(` ${s.padEnd(13)}${a??"a prior clone / cache fetch / materialize localPath"}`)}t.push("","TARGET \u2014 answer type (--target, or inferred from the args):");for(let{target:s,task:a}of VT())t.push(` ${s.padEnd(13)}${a}`);t.push("","COMMON RECIPES:");let r=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],o=e.quickStart;for(let s of r){let a=o[s];a&&t.push(` ${a}`)}t.push("","LSP SEMANTICS (run documentSymbols first, then narrow):");for(let[s,a]of Object.entries(e.semanticsGuide))t.push(` ${s.padEnd(16)}${a}`);t.push("","PROOF \u2014 snippets are discovery, not proof:");let i=e.agentBestPractices.find(s=>/snippet/i.test(s));return i&&t.push(` ${i}`),t.push(` ${e.evidenceSemantics.providerUnindexed}`),t.push("","Routing debug: search --explain --query '{...}'","Full schema: search --scheme"),t.join(`
47
+ `)}zr();xl();fs();export{Ye as ACTIVE_TARGETS,ho as CORPUS_OPTIONAL_TARGETS,$e as DEFAULTS,po as OQL_SCHEMA_DOC,_f as OqlBatchSchema,nE as OqlCanonicalInputSchema,_l as OqlInputBatchSchema,Ll as OqlInputQuerySchema,go as OqlQuerySchema,an as OqlSearchInputSchema,Ot as OqlValidationError,zt as PredicateSchema,As as QuerySourceSchema,_n as RESERVED_TARGETS,kl as SEARCH_SORTS_BY_TARGET,sn as StructuralRuleSchema,Es as analyzeResearchFlow,Hl as appliedDefaults,Bl as backendCallsForTransformer,eu as backendsApproximate,Fl as blocksAnswer,Pr as buildEnvelope,co as buildResearchPackets,IG as buildShorthandInput,x as diagnostic,Ds as findTransformerById,Dn as findTransformerEntry,iE as hasErrors,Ol as isBatchEnvelope,Tl as isBatchInput,El as isCanonicalBatch,FE as listTransformerEntries,Nl as normalizeInput,br as normalizeQuery,QG as oqlCompactSchemeJson,jG as oqlCompactSchemeText,GG as oqlSchemaText,Jl as planQuery,FT as runOqlSearch,dt as sanitizeStructuredContent,xo as unsupportedEnvelope};