@octocodeai/octocode-tools-core 16.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/dist/commands/BaseCommandBuilder.d.ts +14 -0
  2. package/dist/commands/FindCommandBuilder.d.ts +23 -0
  3. package/dist/commands/LsCommandBuilder.d.ts +15 -0
  4. package/dist/commands/RipgrepCommandBuilder.d.ts +27 -0
  5. package/dist/config.d.ts +16 -0
  6. package/dist/direct.d.ts +3 -0
  7. package/dist/direct.js +53 -0
  8. package/dist/errors/ToolError.d.ts +21 -0
  9. package/dist/errors/domainErrors.d.ts +310 -0
  10. package/dist/errors/errorFactories.d.ts +12 -0
  11. package/dist/errors/localToolErrors.d.ts +29 -0
  12. package/dist/errors/pathUtils.d.ts +1 -0
  13. package/dist/github/client.d.ts +12 -0
  14. package/dist/github/codeSearch.d.ts +8 -0
  15. package/dist/github/directoryFetch.d.ts +5 -0
  16. package/dist/github/errorConstants.d.ts +81 -0
  17. package/dist/github/errors.d.ts +3 -0
  18. package/dist/github/fileContent.d.ts +4 -0
  19. package/dist/github/fileContentProcess.d.ts +11 -0
  20. package/dist/github/fileContentRaw.d.ts +12 -0
  21. package/dist/github/githubAPI.d.ts +237 -0
  22. package/dist/github/history.d.ts +16 -0
  23. package/dist/github/prByNumber.d.ts +5 -0
  24. package/dist/github/prContentFetcher.d.ts +5 -0
  25. package/dist/github/prTransformation.d.ts +109 -0
  26. package/dist/github/pullRequestSearch.d.ts +4 -0
  27. package/dist/github/queryBuilders.d.ts +12 -0
  28. package/dist/github/repoSearch.d.ts +25 -0
  29. package/dist/github/repoStructure.d.ts +7 -0
  30. package/dist/github/repoStructurePagination.d.ts +6 -0
  31. package/dist/github/repoStructureRecursive.d.ts +3 -0
  32. package/dist/github/responseHeaders.d.ts +1 -0
  33. package/dist/hints/dynamic.d.ts +6 -0
  34. package/dist/hints/index.d.ts +2 -0
  35. package/dist/hints/types.d.ts +1 -0
  36. package/dist/index.d.ts +187 -0
  37. package/dist/index.js +64 -0
  38. package/dist/providers/capabilities.d.ts +2 -0
  39. package/dist/providers/factory.d.ts +9 -0
  40. package/dist/providers/github/GitHubProvider.d.ts +14 -0
  41. package/dist/providers/github/githubContent.d.ts +9 -0
  42. package/dist/providers/github/githubPullRequests.d.ts +12 -0
  43. package/dist/providers/github/githubSearch.d.ts +12 -0
  44. package/dist/providers/github/githubStructure.d.ts +9 -0
  45. package/dist/providers/github/utils.d.ts +10 -0
  46. package/dist/providers/providerQueries.d.ts +111 -0
  47. package/dist/providers/providerResults.d.ts +175 -0
  48. package/dist/providers/types.d.ts +48 -0
  49. package/dist/responses.d.ts +47 -0
  50. package/dist/scheme/coreSchemas.d.ts +10 -0
  51. package/dist/scheme/fields.d.ts +13 -0
  52. package/dist/scheme/responseEnvelope.d.ts +16 -0
  53. package/dist/security/bridge.d.ts +10 -0
  54. package/dist/serverConfig.d.ts +23 -0
  55. package/dist/session.d.ts +25 -0
  56. package/dist/tools/directToolCatalog.d.ts +56 -0
  57. package/dist/tools/executionGuard.d.ts +14 -0
  58. package/dist/tools/github_clone_repo/cache.d.ts +21 -0
  59. package/dist/tools/github_clone_repo/cloneRepo.d.ts +6 -0
  60. package/dist/tools/github_clone_repo/execution.d.ts +8 -0
  61. package/dist/tools/github_clone_repo/hints.d.ts +2 -0
  62. package/dist/tools/github_clone_repo/scheme.d.ts +50 -0
  63. package/dist/tools/github_clone_repo/types.d.ts +19 -0
  64. package/dist/tools/github_fetch_content/execution.d.ts +7 -0
  65. package/dist/tools/github_fetch_content/finalizer.d.ts +10 -0
  66. package/dist/tools/github_fetch_content/hints.d.ts +2 -0
  67. package/dist/tools/github_fetch_content/scheme.d.ts +120 -0
  68. package/dist/tools/github_fetch_content/types.d.ts +66 -0
  69. package/dist/tools/github_search_code/execution.d.ts +8 -0
  70. package/dist/tools/github_search_code/finalizer.d.ts +6 -0
  71. package/dist/tools/github_search_code/hints.d.ts +2 -0
  72. package/dist/tools/github_search_code/scheme.d.ts +88 -0
  73. package/dist/tools/github_search_pull_requests/contentRequest.d.ts +52 -0
  74. package/dist/tools/github_search_pull_requests/contentResponse.d.ts +18 -0
  75. package/dist/tools/github_search_pull_requests/execution.d.ts +17 -0
  76. package/dist/tools/github_search_pull_requests/hints.d.ts +2 -0
  77. package/dist/tools/github_search_pull_requests/scheme.d.ts +224 -0
  78. package/dist/tools/github_search_pull_requests/types.d.ts +120 -0
  79. package/dist/tools/github_search_repos/execution.d.ts +17 -0
  80. package/dist/tools/github_search_repos/hints.d.ts +2 -0
  81. package/dist/tools/github_search_repos/scheme.d.ts +96 -0
  82. package/dist/tools/github_view_repo_structure/constants.d.ts +4 -0
  83. package/dist/tools/github_view_repo_structure/execution.d.ts +20 -0
  84. package/dist/tools/github_view_repo_structure/hints.d.ts +2 -0
  85. package/dist/tools/github_view_repo_structure/scheme.d.ts +81 -0
  86. package/dist/tools/github_view_repo_structure/types.d.ts +39 -0
  87. package/dist/tools/local_binary_inspect/archiveOps.d.ts +22 -0
  88. package/dist/tools/local_binary_inspect/binaryInspector.d.ts +49 -0
  89. package/dist/tools/local_binary_inspect/binaryOps.d.ts +18 -0
  90. package/dist/tools/local_binary_inspect/decompressOps.d.ts +16 -0
  91. package/dist/tools/local_binary_inspect/execution.d.ts +4 -0
  92. package/dist/tools/local_binary_inspect/scheme.d.ts +44 -0
  93. package/dist/tools/local_fetch_content/contentExtractor.d.ts +9 -0
  94. package/dist/tools/local_fetch_content/execution.d.ts +5 -0
  95. package/dist/tools/local_fetch_content/fetchContent.d.ts +4 -0
  96. package/dist/tools/local_fetch_content/hints.d.ts +2 -0
  97. package/dist/tools/local_fetch_content/scheme.d.ts +31 -0
  98. package/dist/tools/local_find_files/execution.d.ts +5 -0
  99. package/dist/tools/local_find_files/findFiles.d.ts +11 -0
  100. package/dist/tools/local_find_files/hints.d.ts +2 -0
  101. package/dist/tools/local_find_files/scheme.d.ts +9 -0
  102. package/dist/tools/local_ripgrep/execution.d.ts +5 -0
  103. package/dist/tools/local_ripgrep/grepFallbackExecutor.d.ts +3 -0
  104. package/dist/tools/local_ripgrep/hints.d.ts +2 -0
  105. package/dist/tools/local_ripgrep/patternValidation.d.ts +12 -0
  106. package/dist/tools/local_ripgrep/ripgrepExecutor.d.ts +3 -0
  107. package/dist/tools/local_ripgrep/ripgrepParser.d.ts +9 -0
  108. package/dist/tools/local_ripgrep/ripgrepResultBuilder.d.ts +9 -0
  109. package/dist/tools/local_ripgrep/scheme.d.ts +55 -0
  110. package/dist/tools/local_ripgrep/searchContentRipgrep.d.ts +5 -0
  111. package/dist/tools/local_ripgrep/structuralSearch.d.ts +9 -0
  112. package/dist/tools/local_view_structure/execution.d.ts +5 -0
  113. package/dist/tools/local_view_structure/hints.d.ts +2 -0
  114. package/dist/tools/local_view_structure/local_view_structure.d.ts +7 -0
  115. package/dist/tools/local_view_structure/scheme.d.ts +33 -0
  116. package/dist/tools/local_view_structure/structureFilters.d.ts +33 -0
  117. package/dist/tools/local_view_structure/structureParser.d.ts +3 -0
  118. package/dist/tools/local_view_structure/structureResponse.d.ts +32 -0
  119. package/dist/tools/local_view_structure/structureWalker.d.ts +24 -0
  120. package/dist/tools/lsp/semantic_content/execution.d.ts +4 -0
  121. package/dist/tools/lsp/semantic_content/hints.d.ts +4 -0
  122. package/dist/tools/lsp/semantic_content/index.d.ts +2 -0
  123. package/dist/tools/lsp/semantic_content/scheme.d.ts +509 -0
  124. package/dist/tools/lsp/shared/callHierarchyTraversal.d.ts +11 -0
  125. package/dist/tools/lsp/shared/resolveSymbolAnchor.d.ts +20 -0
  126. package/dist/tools/lsp/shared/semanticTypes.d.ts +134 -0
  127. package/dist/tools/package_search/execution.d.ts +7 -0
  128. package/dist/tools/package_search/hints.d.ts +2 -0
  129. package/dist/tools/package_search/scheme.d.ts +51 -0
  130. package/dist/tools/providerExecution.d.ts +51 -0
  131. package/dist/tools/providerMappers.d.ts +277 -0
  132. package/dist/tools/toolConfig.d.ts +41 -0
  133. package/dist/tools/toolMetadata/baseSchema.d.ts +2 -0
  134. package/dist/tools/toolMetadata/descriptions.d.ts +1 -0
  135. package/dist/tools/toolMetadata/gateway.d.ts +7 -0
  136. package/dist/tools/toolMetadata/metadataPresence.d.ts +1 -0
  137. package/dist/tools/toolMetadata/names.d.ts +2 -0
  138. package/dist/tools/toolMetadata/proxies.d.ts +10 -0
  139. package/dist/tools/toolMetadata/state.d.ts +5 -0
  140. package/dist/tools/toolMetadata/types.d.ts +2 -0
  141. package/dist/tools/toolNames.d.ts +2 -0
  142. package/dist/tools/utils.d.ts +27 -0
  143. package/dist/types/bulk.d.ts +41 -0
  144. package/dist/types/execution.d.ts +11 -0
  145. package/dist/types/metadata.d.ts +69 -0
  146. package/dist/types/promise.d.ts +12 -0
  147. package/dist/types/responseTypes.d.ts +57 -0
  148. package/dist/types/server.d.ts +15 -0
  149. package/dist/types/session.d.ts +29 -0
  150. package/dist/types/toolResults.d.ts +62 -0
  151. package/dist/utils/contextUtils.d.ts +31 -0
  152. package/dist/utils/core/bestEffort.d.ts +2 -0
  153. package/dist/utils/core/compare.d.ts +1 -0
  154. package/dist/utils/core/constants.d.ts +47 -0
  155. package/dist/utils/core/promise.d.ts +2 -0
  156. package/dist/utils/core/safeRegex.d.ts +5 -0
  157. package/dist/utils/core/types.d.ts +50 -0
  158. package/dist/utils/environment/environmentDetection.d.ts +5 -0
  159. package/dist/utils/exec/commandAvailability.d.ts +19 -0
  160. package/dist/utils/exec/npm.d.ts +16 -0
  161. package/dist/utils/exec/ripgrepBinary.d.ts +3 -0
  162. package/dist/utils/exec/safe.d.ts +2 -0
  163. package/dist/utils/exec/spawn.d.ts +34 -0
  164. package/dist/utils/file/byteOffset.d.ts +12 -0
  165. package/dist/utils/file/filters.d.ts +11 -0
  166. package/dist/utils/file/size.d.ts +2 -0
  167. package/dist/utils/file/toolHelpers.d.ts +28 -0
  168. package/dist/utils/http/cache.d.ts +16 -0
  169. package/dist/utils/http/circuitBreaker.d.ts +17 -0
  170. package/dist/utils/http/fetch.d.ts +13 -0
  171. package/dist/utils/package/common.d.ts +5 -0
  172. package/dist/utils/package/npm.d.ts +8 -0
  173. package/dist/utils/package/schemas.d.ts +60 -0
  174. package/dist/utils/package/types.d.ts +55 -0
  175. package/dist/utils/pagination/boundary.d.ts +11 -0
  176. package/dist/utils/pagination/charLimit.d.ts +3 -0
  177. package/dist/utils/pagination/core.d.ts +15 -0
  178. package/dist/utils/pagination/hints.d.ts +3 -0
  179. package/dist/utils/pagination/outputSizeLimit.d.ts +16 -0
  180. package/dist/utils/pagination/types.d.ts +43 -0
  181. package/dist/utils/parsers/diff.d.ts +2 -0
  182. package/dist/utils/parsers/ripgrep.d.ts +11 -0
  183. package/dist/utils/parsers/schemas.d.ts +72 -0
  184. package/dist/utils/response/bulk.d.ts +5 -0
  185. package/dist/utils/response/callToolResult.d.ts +3 -0
  186. package/dist/utils/response/charSavings.d.ts +3 -0
  187. package/dist/utils/response/error.d.ts +20 -0
  188. package/dist/utils/response/groupedFinalizer.d.ts +37 -0
  189. package/dist/utils/response/pathRelativize.d.ts +9 -0
  190. package/dist/utils/response/structuredPagination.d.ts +9 -0
  191. package/dist/zod.d.ts +1 -0
  192. package/dist/zod.js +8 -0
  193. package/package.json +66 -0
package/dist/direct.js ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ var gr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{z as Ho}from"zod";import{resolveTokenFull as ju,getConfigSync as Ko,invalidateConfigCache as DS}from"octocode-shared";var ct="16.2.0";var yr={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},Ze={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"}},Je={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})`}},zu={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"}},Ce={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}`}},Ge={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"}},te={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}`}},Qu={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}`}},qe={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"}},Rr={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}`}},MS={...yr,...Ze,...Je,...zu,...Ce,...Ge,...te,...Qu,...qe,...Rr};import{maskSensitiveData as Vu}from"octocode-security/mask";var Nt=null,Mt=null,Wu=ju;var Ku=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"]);async function Yo(){try{let e=await Wu({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:Ku.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Xo(){if(Nt!==null)return;if(Mt!==null)return Mt;let e=(async()=>{let t=Ko(),n=await Yo();Nt={version:ct,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,loggingEnabled:t.telemetry.logging,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Mt=e;try{await e}catch(t){throw Mt===e&&(Nt=null,Mt=null),t}}function br(){if(!Nt){let e=Vu(yr.NOT_INITIALIZED.message);throw new Error(e)}return Nt}async function Zo(){return(await Yo()).token}function un(){let e=br();return e.enableLocal&&e.enableClone}function dn(){return"github"}function Sr(){let e=Ko().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as Qd}from"octocode-security/contentSanitizer";import{createRequire as Yu}from"node:module";var Xu=Yu(import.meta.url),Jo="@octocodeai/octocode-context-utils",pn,Zu=()=>Xu(Jo),Cr=class extends Error{constructor(n){super(`Failed to load native dependency ${Jo}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function le(){if(pn)return pn;try{return pn=Zu(),pn}catch(e){throw new Cr(e)}}var U={applyContentViewMinification(e,t){return le().applyContentViewMinification(e,t)},applyMinification(e,t){return le().applyMinification(e,t)},minifyContent(e,t){return le().minifyContent(e,t)},minifyContentSync(e,t){return le().minifyContentSync(e,t)},minifyContentResult(e,t){return le().minifyContentResult(e,t)},minifyMarkdownCore(e){return le().minifyMarkdownCore(e)},extractSignatures(e,t){return le().extractSignatures(e,t)},structuralSearch(e,t,n,r){return le().structuralSearch(e,t,n,r)},getSemanticBoundaryOffsets(e,t){return le().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return le().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return le().parseRipgrepJson(e,t)},queryFileSystem(e){return le().queryFileSystem(e)},extractMatchingLines(e,t,n){return le().extractMatchingLines(e,t,n)},filterPatch(e,t){return le().filterPatch(e,t)},charToByteOffset(e,t){return le().charToByteOffset(e,t)},byteToCharOffset(e,t){return le().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return le().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return le().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return le().SIGNATURES_ONLY_HINT}};import{Octokit as ed}from"octokit";import{throttling as td}from"@octokit/plugin-throttling";import{createHash as nd}from"crypto";import{getOrCreateSession as eC,incrementToolCalls as tC,incrementErrors as nC,incrementRateLimits as rC,incrementGitHubCacheRateLimits as oC,updateSessionStats as iC}from"octocode-shared";import{completeMetadata as Ju}from"@octocodeai/octocode-core";var ge="lspGetSemantics",qo=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation"];function bt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Pr(e){return{uri:e.uri,...e.content!==void 0&&{content:e.content},...e.displayRange&&{displayRange:e.displayRange},...e.isDefinition&&{isDefinition:!0}}}var W=Ju.toolNames,KS=new Set([W.LOCAL_RIPGREP,W.LOCAL_FETCH_CONTENT,W.LOCAL_FIND_FILES,W.LOCAL_VIEW_STRUCTURE,W.LOCAL_BINARY_INSPECT,ge]);var qu=null;function Er(){return qu}async function H(e,t){let n=Er();n&&await n.logError(e,t)}async function et(e){let t=Er();t&&await t.logRateLimit(e)}function ei(e){let t=Er();t&&t.logPackageRegistryFailure(e)}function rd(e){return nd("sha256").update(e).digest("hex").substring(0,16)}var od=ed.plugin(td),id=300*1e3,Tr=50,sd=60*1e3;function wr(e){return Date.now()-e.createdAt>id}var Me=new Map,Ht=null,Dt=null;function si(){for(let[e,t]of Me.entries())wr(t)&&Me.delete(e);if(Me.size>Tr){let e=[...Me.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=Me.size-Tr;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Me.delete(r[0])}}}function ad(){Dt||(Dt=setInterval(si,sd),typeof Dt=="object"&&"unref"in Dt&&Dt.unref())}var ti=3,ni=60;function ri(e,t,n){et({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var cd=()=>({onRateLimit:(e,t,n,r)=>(ri("primary",e,t),r<ti&&e<ni),onSecondaryRateLimit:(e,t,n,r)=>(ri("secondary",e,t),r<ti&&e<ni)});function oi(e){let t=br(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${ct}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:cd(),log:r,...e&&{auth:e}};return new od(o)}async function ne(e){if(ad(),e?.token){let n=rd(e.token),r=Me.get(n);if(r&&!wr(r))return r.client;Me.size>=Tr&&si();let o=oi(e.token);return Me.set(n,{client:o,createdAt:Date.now()}),o}let t=Me.get("DEFAULT");return t&&!wr(t)?t.client:Ht||(Ht=(async()=>{try{let n=await Zo(),r=oi(n??void 0);return Me.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{Ht=null}})(),Ht)}var ld=200,Gt=new Map;async function Oe(e,t,n){let r=`${e}/${t}`,o=Gt.get(r);if(o)return o;let i=await ne(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return ii(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}),ii(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 ii(e,t){if(Gt.size>=ld){let n=Gt.keys().next().value;n!==void 0&&Gt.delete(n)}Gt.set(e,t)}import{RequestError as ci}from"octokit";var z={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"},ue={[z.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."},[z.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."},[z.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},[z.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)."},[z.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."},[z.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."},[z.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."},[z.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."},[z.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."},[z.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},ai={401:z.AUTH_REQUIRED,403:z.FORBIDDEN_PERMISSIONS,404:z.NOT_FOUND,422:z.INVALID_REQUEST,502:z.SERVER_UNAVAILABLE,503:z.SERVER_UNAVAILABLE,504:z.SERVER_UNAVAILABLE},_r={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},xr={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},mn={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var ud=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function lt(e){if(!(e instanceof ci)||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 ud.some(o=>r.includes(o))})}function Z(e){return e instanceof ci?dd(e):e instanceof Error?bd(e):{error:typeof e=="string"?e:ue[z.UNKNOWN].message,type:"unknown"}}function dd(e){let{status:t,message:n,response:r}=e;if(t===403)return md(n,r);if(t===429)return pd(n,r);let o=ai[t];return o?Rd(o,t):St(z.UNKNOWN,{error:n||ue[z.UNKNOWN].message,status:t})}function Ar(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function pd(e,t){let n=t?.headers,r=Ar(n,"retry-after"),o=Ar(n,"x-ratelimit-reset"),i=Ar(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+mn.RESET_BUFFER_SECONDS,0):void 0);return et({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),St(z.RATE_LIMIT_PRIMARY,{error:e||ue[z.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ue[z.RATE_LIMIT_PRIMARY].suggestion})}function md(e,t){let n=t?.headers;if(xr.SECONDARY.test(e))return fd(n);let r=n?.["x-ratelimit-remaining"],o=yd(t);return r==="0"||o?hd(n):gd(n)}function fd(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?mn.SECONDARY_FALLBACK_SECONDS:t;return et({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),St(z.RATE_LIMIT_SECONDARY,{error:ue[z.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ue[z.RATE_LIMIT_SECONDARY].suggestion})}function hd(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)+mn.RESET_BUFFER_SECONDS,0):void 0,i=r?ue[z.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ue[z.RATE_LIMIT_PRIMARY].messageWithoutTime;return et({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),St(z.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ue[z.RATE_LIMIT_PRIMARY].suggestion})}function gd(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ue[z.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Sd(String(t),String(n))),St(z.FORBIDDEN_PERMISSIONS,{error:ue[z.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function yd(e){return e?.data?.errors?.some(n=>n.type===xr.GRAPHQL_TYPE)??!1}function Rd(e,t){let n=ue[e];return St(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function bd(e){return _r.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ue[z.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ue[z.NETWORK_CONNECTION_FAILED].suggestion}:_r.TIMEOUT.some(t=>e.message.includes(t))?{error:ue[z.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ue[z.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function St(e,t){return{type:"http",...t}}function Sd(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?ue[z.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ue[z.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Cd(e){return`user:${e}`}var Pd=/[@/]/,Ed=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Td=/^[A-Za-z0-9_-]+$/;function li(e){return e.startsWith('"')||Td.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var $t=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(Cd(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=Pd.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},Lr=class extends $t{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(li))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Ed):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}},Ir=class extends $t{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(li)),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}},Or=class extends $t{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 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}};function ui(e){return new Lr().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function di(e){return new Ir().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function pi(e){return new Or().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function mi(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)}import wd from"node-cache";import _d from"crypto";import{incrementGitHubCacheHits as xd}from"octocode-shared";var Ad="v1",Ld=300*1e3,ut=new wd({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Ct={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},fi={"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},Bt=new Map;function Id(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Od(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function kd(e){let t=Id(e);if(!(!t||!Od(t)))try{xd(t,1)}catch{}}function vd(){let e=Date.now();for(let[t,n]of Bt.entries())e-n.startedAt>Ld&&Bt.delete(t)}var Fd=new Set([]);function Md(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(Fd.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Pe(e,t,n){let r=kr(Md(t)),o=n?`${n}:${r}`:r,i=_d.createHash("sha256").update(o).digest("hex");return`${Ad}-${e}:${i}`}function kr(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=>kr(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${kr(i,t)}`}).join(",")}}`)}function Nd(e){return fi[e]||fi.default}function Hd(e,t,n){try{return ut.set(e,t,n),Ct.sets++,Ct.totalKeys=ut.keys().length,!0}catch{try{let r=ut.keys();for(let o of r)ut.get(o);return ut.set(e,t,n),Ct.sets++,Ct.totalKeys=ut.keys().length,!0}catch{return!1}}}async function Ee(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=ut.get(e);if(i!==void 0)return Ct.hits++,kd(e),i}catch{}vd();let r=Bt.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Ct.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Nd(l)}Hd(e,i,a)}return i}finally{Bt.delete(e)}})();return Bt.set(e,{promise:o,startedAt:Date.now()}),o}var hi=[".github",".git",".vscode",".devcontainer",".config",".cargo",".changeset",".husky",".aspect",".eslint-plugin-local",".yarn",".gemini",".ng-dev",".configurations",".tx","dist","build","out","output","target","release","node_modules","vendor","third_party","tmp","temp","cache",".cache",".tmp",".pytest_cache",".tox",".venv",".mypy_cache",".next",".svelte-kit",".turbo",".angular",".dart_tool","__pycache__",".ruff_cache",".nox","htmlcov","cover",".gradle",".m2",".sbt",".bloop",".metals",".bsp","bin","obj","TestResults","BenchmarkDotNet.Artifacts",".vendor-new","Godeps","composer.phar",".phpunit.result.cache",".bundle",".byebug_history",".rspec_status",".mvn",".aws",".gcp","fastlane","DerivedData","xcuserdata","local.properties",".navigation","captures",".externalNativeBuild",".cxx",".idea",".idea_modules",".vs",".history","coverage",".nyc_output","logs","log",".DS_Store"],Dd=["package-lock.json",".secrets",".secret","secrets.json","secrets.yaml","secrets.yml","credentials.json","credentials.yaml","credentials.yml","auth.json","auth.yaml","auth.yml","api-keys.json","api_keys.json","service-account.json","service_account.json","private-key.pem","private_key.pem","id_rsa","id_dsa","id_ecdsa","id_ed25519","keyfile","keyfile.json","gcloud-service-key.json","firebase-adminsdk.json","google-services.json","GoogleService-Info.plist",".DS_Store","Thumbs.db","db.sqlite3","db.sqlite3-journal",".eslintcache",".stylelintcache",".node_repl_history",".yarn-integrity","celerybeat-schedule","celerybeat.pid","ThirdPartyNoticeText.txt","ThirdPartyNotices.txt","cglicenses.json","cgmanifest.json"],Gd=[".lock",".log",".tmp",".temp",".cache",".bak",".backup",".orig",".swp",".swo",".rej",".pid",".seed",".old",".save",".temporary",".exe",".dll",".so",".dylib",".a",".lib",".o",".obj",".bin",".class",".pdb",".dSYM",".pyc",".pyo",".pyd",".jar",".war",".ear",".nar",".db",".sqlite",".sqlite3",".mdb",".accdb",".zip",".tar",".gz",".bz2",".xz",".lz",".lzma",".Z",".tgz",".rar",".7z",".deb",".rpm",".pkg",".dmg",".msi",".appx",".snap",".map",".d.ts.map",".min.js",".min.css",".key",".pem",".p12",".pfx",".crt",".cer",".der",".csr",".jks",".keystore",".truststore",".kate-swp",".gnome-desktop",".sublime-project",".sublime-workspace",".iml",".iws",".ipr",".patch",".diff",".prof",".profile",".trace",".perf",".coverage",".egg-info",".egg",".mo",".pot",".setup",".paket.template"];function Ut(e){return hi.includes(e)}function Pt(e){let t=e.split("/").pop()||"";for(let r of Gd)if(t.endsWith(r))return!0;if(Dd.includes(t))return!0;let n=e.split("/");for(let r of n)if(hi.includes(r))return!0;return!1}import{completeMetadata as vr}from"@octocodeai/octocode-core";var S=new Proxy({},{get(e,t){return vr.toolNames[t]},ownKeys(){return Object.keys(vr.toolNames)},getOwnPropertyDescriptor(e,t){let n=vr.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as $d}from"@octocodeai/octocode-core";var Fr=new Proxy({},{get(e,t){return $d.tools[t]?.description??""}});import{completeMetadata as Bd}from"@octocodeai/octocode-core";function Mr(e){return Object.prototype.hasOwnProperty.call(Bd.tools,e)}import{completeMetadata as Ud}from"@octocodeai/octocode-core";function Nr(){return Ud.baseSchema}var zd=new Proxy({},{get(e,t){return Nr()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Nr())]))},getOwnPropertyDescriptor(e,t){let n=Nr();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as Et}from"@octocodeai/octocode-core";function gi(e){return Et.tools[e]?.hints??{hasResults:[],empty:[]}}var NC=new Proxy({},{get(e,t){if(typeof t=="string")return t==="base"?Et.baseHints:gi(t)},ownKeys(){return["base",...Object.keys(Et.tools)]},getOwnPropertyDescriptor(e,t){if(typeof t=="string"&&(t==="base"||t in Et.tools))return{enumerable:!0,configurable:!0,value:t==="base"?Et.baseHints:gi(t)}}}),HC=new Proxy([],{get(e,t){return Et.genericErrorHints[t]}});var yi=Symbol.for("octocode.rawResponseChars");function $(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Ri(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function D(e,t){let n=typeof t=="number"?Ri(t):$(t);if(n===void 0)return e;try{Object.defineProperty(e,yi,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function q(e){if(!(typeof e!="object"||e===null))return Ri(e[yi])}function fn(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 bi=30;async function Si(e,t,n){let r=Pe("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 Ee(r,async()=>await jd(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function jd(e,t){try{let n=await ne(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(R=>R&&R.trim()).length===0)return await H(S.GITHUB_SEARCH_CODE,te.QUERY_EMPTY.code),{error:te.QUERY_EMPTY.message,type:"http",status:400};let r=ui(e);if(!r.trim())return await H(S.GITHUB_SEARCH_CODE,te.QUERY_EMPTY.code),{error:te.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:bi,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 Vd(a.data.items,a.data.total_count),l=c.total_count,d=Math.min(l,1e3),u=Math.min(Math.ceil(d/o),10),m=Math.min(i,Math.max(1,u)),p=m<u,f=Math.min(d,u*o);return{data:{total_count:c.total_count,items:c.items,repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:m,totalPages:u,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:f,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:p,uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:fn(a.headers),rawResponseChars:$(a.data)}}catch(n){if(lt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:bi,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 Z(n)}}async function Vd(e,t){let n=Wd(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Pt(p.path)),c=0,l=0,d=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],h=await Promise.allSettled((p.text_matches||[]).map(async E=>{let L=E.fragment,I=Qd.sanitizeContent(L||"",p.path);L=I.content,I.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${I.secretsDetected.join(", ")}`),I.warnings.length>0&&I.warnings.forEach(k=>r.add(`${p.path}: ${k}`));try{let k=await U.minifyContent(L||"",p.path);L=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}return{context:L||"",positions:E.matches?.map(k=>Array.isArray(k.indices)&&k.indices.length>=2?[k.indices[0],k.indices[1]]:[0,0])||[]}})),R=h.filter(E=>E.status==="fulfilled").map(E=>E.value),b=h.filter(E=>E.status==="rejected").length;b>0&&(l+=b);let g=p,C=Array.from(new Set(f));return{path:p.path,matches:R,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...g.last_modified_at&&{lastModifiedAt:g.last_modified_at},...C.length>0&&{minificationType:C.join(",")}}})),u=d.filter(p=>p.status==="fulfilled").map(p=>p.value);c=d.filter(p=>p.status==="rejected").length;let m={items:u,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 Wd(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 Ci=30;function Pi(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 Ei(e,t,n){let r=Pe("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 Ee(r,async()=>await Yd(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Kd(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{try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){return Z(p)}}let a=i.map(p=>{let h=p.full_name.split("/"),R=h[0]||"",b=h[1]||"";return{owner:R,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description.length>150?p.description.substring(0,150)+"...":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},...Pi(p)}}),c=a.length,l=c===n,d=(r-1)*n+c,u=s??d+(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:u,reachableTotalMatches:d,totalMatchesKind:m,hasMore:l}},status:200,rawResponseChars:$(i)}}async function Yd(e,t){try{let n=await ne(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 Kd({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=di(e);if(!i.trim())return await H(S.GITHUB_SEARCH_REPOSITORIES,te.QUERY_EMPTY.code),{error:te.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Ci,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 d=await n.rest.search.repos(c),u=d.data.items.map(g=>{let E=g.full_name.split("/"),L=E[0]||"",I=E[1]||"";return{owner:L,repo:I,defaultBranch:g.default_branch,stars:g.stargazers_count||0,description:g.description?g.description.length>150?g.description.substring(0,150)+"...":g.description:"No description",url:g.html_url,createdAt:g.created_at,updatedAt:g.updated_at,pushedAt:g.pushed_at,visibility:g.visibility,...g.topics&&g.topics.length>0&&{topics:g.topics},...g.forks_count&&g.forks_count>0&&{forksCount:g.forks_count},...g.open_issues_count&&g.open_issues_count>0&&{openIssuesCount:g.open_issues_count},...g.language&&{language:g.language},...Pi(g)}}),m=d.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),h=Math.min(a,Math.max(1,f)),R=h<f,b=Math.min(p,f*s);return{data:{repositories:u,pagination:{currentPage:h,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:R}},status:200,headers:fn(d.headers),rawResponseChars:$(d.data)}}catch(n){if(lt(n)){let r=Math.min(e.limit||Ci,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 Z(n)}}function Tt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function de(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 Xd(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 je(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:Xd(e)}}function hn(e){return Zd(e)?je({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 Zd(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||Jd(n)}function Jd(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Ti(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 qd(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,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Ti(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope}}function ep(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,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Ti(e.pagination)},nonExistentScope:e.nonExistentScope}}async function wi(e,t,n=de){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 Si(s,t);return Tt(a)?je(a):a.data?{data:qd(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??$(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function _i(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 Ei(n,t);return"error"in r?hn(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:ep(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??$(r.data)}}import{RequestError as xi}from"octokit";async function np(e,t,n,r,o,i,s,a){let c=await Oe(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 d=Z(t),u=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 ki(e,r,o,i,s||c);return m.length>0&&(d.hints=[...d.hints||[],...Oi(i,m)]),{...d,...u&&{scopesSuggestion:u}}}async function rp(e,t,n,r,o,i){let s=Z(t),a=await ki(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Oi(o,a)]),s}async function Ai(e,t){let n=e.replace(/\s/g,"");if(!n)return await H(S.GITHUB_FETCH_CONTENT,Ce.FILE_EMPTY.code),{error:Ce.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?(await H(S.GITHUB_FETCH_CONTENT,Ce.BINARY_FILE.code),{error:Ce.BINARY_FILE.message,type:"unknown",status:415}):{data:r.toString("utf-8"),status:200}}catch{return await H(S.GITHUB_FETCH_CONTENT,Ce.DECODE_FAILED.code),{error:Ce.DECODE_FAILED.message,type:"unknown",status:422}}}async function Li(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"?Ai(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return Z(i)}}async function op(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 Oe(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 d=l.data.find(m=>m.name===a&&m.type==="file");if(!d)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let u=await Li(e,t,n,d.sha,r);return"error"in u?u:{data:{rawContent:u.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return Z(s)}}async function Ii(e,t){try{let n=await ne(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(u){if(u instanceof xi&&u.status===404)if(s){let m=await np(n,u,a,r,o,i,s,t);if("result"in m)c=m.result,l=m.actualBranch;else return m}else return await rp(n,u,r,o,i,s);else{if(u instanceof xi&&u.status===413)return await op(n,r,o,i,s||l,t);throw u}}let d=c.data;if(Array.isArray(d))return await H(S.GITHUB_FETCH_CONTENT,Ce.PATH_IS_DIRECTORY.code),{error:Ce.PATH_IS_DIRECTORY.message(S.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let u=typeof d.content=="string"?d.content:"",m=d.size??0,p;if(u.length>0)p=await Ai(u,i);else if(m>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)p=await Li(n,r,o,d.sha,i);else return await H(S.GITHUB_FETCH_CONTENT,Ce.FILE_EMPTY.code),{error:Ce.FILE_EMPTY.message,type:"unknown",status:404};if("error"in p)return p;if(!l&&!s)try{l=await Oe(r,o,t)}catch{}return{data:{rawContent:p.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:$(d)}}return await H(S.GITHUB_FETCH_CONTENT,Ce.UNSUPPORTED_TYPE.code),{error:Ce.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(n){return Z(n)}}function Oi(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 ki(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=[],d=c.find(p=>p.name.toLowerCase()===s.toLowerCase());d&&l.push(d.path);let u=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(u+".")).forEach(p=>l.push(p.path)),l.length===0&&u.length>=3&&c.filter(f=>{let h=f.name.replace(/\.[^/.]+$/,"");return h!==u&&h.length>=3&&(u.startsWith(h)||h.startsWith(u))}).forEach(f=>l.push(f.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}import{getConfigSync as ip}from"octocode-shared";import{DEFAULT_OUTPUT_CONFIG as sp}from"octocode-shared";function $e(){try{return ip().output.pagination.defaultCharLength}catch{return sp.pagination.defaultCharLength}}import{ContentSanitizer as Hi}from"octocode-security/contentSanitizer";function Hr(e,t){return U.byteToCharOffset(e,t)}function vi(e,t){return U.charToByteOffset(e,t)}function Fi(e){return U.charToByteOffset(e,e.length)}function Dr(e,t,n,r){return U.sliceContent(e,t,n,r)}function wt(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Fi(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,d,u,m,p,f,h;if(o==="bytes"){let R=Math.min(t,s),b=Math.min(R+n,s);u=Hr(e,R),m=Hr(e,b),m<i&&vi(e,m)<b&&(m+=1);let g=Dr(e,u,m-u);c=g.text,u=g.charOffset,m=g.charOffset+g.charLength,l=g.byteOffset,d=g.byteOffset+g.byteLength,p=d<s;let C=r.actualOffset??R;f=Math.floor(C/a)+1,h=Math.max(f,Math.ceil(s/a))}else{let R=Dr(e,t,n);c=R.text,u=R.charOffset,m=R.charOffset+R.charLength,l=R.byteOffset,d=R.byteOffset+R.byteLength,p=m<i;let b=r.actualOffset??u;f=Math.floor(b/a)+1,h=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:d-l,totalBytes:s,nextByteOffset:p?d:void 0,charOffset:u,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:h}}function Mi(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 ap=8e3,cp="__octocode_generic__.unknown";function lp(e){return e&&e.trim().length>0?e:cp}function Ni(e,t){return U.getSemanticBoundaryOffsets(e,lp(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function up(e,t){let n=e.indexOf(`
9
+ `,t);return n===-1?void 0:n+1}function gn(e){let t=e.trimEnd().split(`
10
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function yn(e,t,n){let r=up(e,Math.max(0,t));if(r!==void 0)return Ni(e,n).find(o=>o>=r&&o>t)}function Rn(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=Ni(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(d=>d>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=ap?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function bn(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let d=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${d}`)}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=U.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)}}function pp(){let e=$e();return Math.min(e,8e3)}function Sn(e,t){return{sourceChars:e,sourceBytes:t}}function Di(e,t,n){let r=e.content??"",o=n??pp();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=Rn(r,t,o,i),c=wt(r,t,s),l;if(c.hasMore&&a==="char-limit"&&gn(c.paginatedContent)){let d=c.charOffset+c.charLength;l=yn(r,d,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,chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function Gi(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 $i(e,t,n,r,o,i,s,a,c=5,l,d,u,m="standard"){let p=e.length,f=Buffer.byteLength(e,"utf-8"),h=m==="standard"||m==="symbols",R=h?"standard":"none",b;if(m==="symbols"){let N=U.extractSignatures(e,o);if(N===null&&(b=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),N!==null){let M=Hi.sanitizeContent(N,o),oe=U.applyContentViewMinification(M.content,o),ae=[U.SIGNATURES_ONLY_HINT];return l&&ae.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),M.hasSecrets&&ae.push(`Secrets detected and redacted: ${M.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:oe,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:e.split(`
12
+ `).length,...Sn(p,f),isPartial:!1,signaturesExtracted:!0,hints:ae}}}let g=new Set,E=e.split(`
13
+ `),L=E.length,I=e,k,j,P=!1,x;if(i)I=e;else if(l){let N=u===!0,M;try{M=bn(E,l,c,d??!1,N)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:L,...Sn(p,f),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(M.matchCount===0){let O=d?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${N?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${N?" (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:L,...Sn(p,f),matchNotFound:!0,searchedFor:l,hints:O}}I=M.lines.join(`
14
+ `);let oe=M.matchRanges[0],ae=M.matchRanges[M.matchRanges.length-1];s=oe.start,a=ae.end,k=oe.start,j=ae.end,P=!0,M.matchRanges.length>1&&(x=M.matchRanges);let ce=M.matchingLines.slice(0,5).join(", "),Q=M.matchingLines.length>5?` and ${M.matchingLines.length-5} more`:"";g.add(M.matchCount>1?`Found ${M.matchCount} occurrences of "${l}" on lines ${ce}${Q} \u2014 all shown as ${M.matchRanges.length} slice${M.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${M.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let N=s||1,M=a||L;if(N<1||N>L)I=e;else if(M<N)I=e;else{let oe=Math.max(1,N),ae=Math.min(L,M),ce=E.slice(oe-1,ae);k=oe,j=ae,P=!0,I=ce.join(`
15
+ `),M>L&&g.add(`Requested endLine ${M} adjusted to ${L} (file end)`)}}let A=Hi.sanitizeContent(I,o);if(I=h?U.applyContentViewMinification(A.content,o):A.content,A.hasSecrets&&g.add(`Secrets detected and redacted: ${A.secretsDetected.join(", ")}`),A.warnings.length>0&&A.warnings.forEach(N=>g.add(N)),L>2e3&&m!=="symbols"&&!l&&!s&&!a&&!i){let N=Math.max(1,L-200);g.add(`Large file (${L} lines) \u2014 minify:"symbols" for an export index, or startLine=${N} for the tail.`)}let B=Array.from(g);return{owner:t,repo:n,path:o,content:I,...R!=="standard"&&{contentView:R},branch:r,totalLines:L,...Sn(p,f),...P&&{startLine:k,endLine:j,isPartial:P},...x&&{matchRanges:x},...B.length>0&&{matchLocations:B},...(B.length>0||b)&&{warnings:[...b?[b]:[],...B]}}}async function Bi(e,t,n){let r=Pe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await Ee(r,async()=>await Ii(e,t),{shouldCache:p=>"data"in p&&!p.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 $i(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,d=e.charLength,u=a?c:Di(c,l,d),m=(e.charOffset??0)>0;if(!e.noTimestamp&&!m)try{let p=await ne(t),f=await Ee(Pe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>Gi(p,e.owner,e.repo,e.path,e.branch),{shouldCache:h=>h!==null,forceRefresh:e.forceRefresh===!0});f&&(u.lastModified=f.lastModified,u.lastModifiedBy=f.lastModifiedBy)}catch{}return{data:u,status:200,rawResponseChars:o.rawResponseChars}}function mp(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:fp(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function fp(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 Ui(e,t,n=de){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,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Bi(i,t);if(Tt(s))return je(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:mp(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??$(s.data),...a?.length?{hints:a}:{}}}import{ContentSanitizer as ji}from"octocode-security/contentSanitizer";var gp=2;function zi(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return U.filterPatch(e,r)}function Qi(e){return e?U.filterPatch(e,{trimContext:!0,contextLines:gp}):""}function Gr(e){let t=ji.sanitizeContent(e.title??""),n=e.body?ji.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}}var yp=$e(),Rp=Math.round($e()/4),Vi=3;function Wi(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 zt(e,t={}){let n=t.charOffset??0,r=t.charLength??yp,o=t.charLength??Rp,i=typeof e.body=="string"?U.minifyMarkdownCore(e.body):e.body,s=Wi(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,h)=>{let R=f.commentType==="review_inline"?0:1,b=h.commentType==="review_inline"?0:1;return R-b}),c=a.filter(f=>f.commentType==="review_inline").length,l=a.length-c,d=t.includeFullCommentDetails?a:a.slice(0,Vi),u=d.map(f=>{let h=Wi(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:h.value??"",...h.pagination?{body_pagination:h.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>d.length||u.some(f=>"body_pagination"in f)),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 ${Vi} 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(f=>({id:0,name:f,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((f,h)=>f+h.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((f,h)=>f+h.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(f=>({filename:f.filename,status:f.status,additions:f.additions,deletions:f.deletions,patch:f.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...u.length>0&&{comment_details:u,comment_details_shown:u.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function Qt(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 Cn(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?zi(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?Qi(a.patch):a.patch}))}import{ContentSanitizer as $r}from"octocode-security/contentSanitizer";function Pn(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Ki(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Yi(e){let t=Ki(e);return t?t.discussion!==!1:!1}function Xi(e){let t=Ki(e);return t?t.reviewInline!==!1:!1}function Zi(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function Ji(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function qi(e){return!!e.content?.comments?.includeBots}var bp=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function es(e){let t=e.toLowerCase();return t.endsWith("[bot]")||bp.has(t.replace(/\[bot\]$/,""))}function Br(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
16
+
17
+ `).trim()}async function ts(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+=$(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!es(p.user?.login??"")),d=i.length-l.length,u=l.map(p=>{let f=U.minifyMarkdownCore(Br(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:$r.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return d>0&&m.push(`${d} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:D(u,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:D([],0)}}}async function ns(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Ur(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return D(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:$r.sanitizeContent(U.minifyMarkdownCore(Br(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return D([],0)}}async function rs(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+=$(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!es(p.user?.login??"")),d=i.length-l.length,u=l.map(p=>{let f=U.minifyMarkdownCore(Br(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:$r.sanitizeContent(f).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 d>0&&m.push(`${d} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:D(u,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:D([],0)}}}async function os(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Gr(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:d}=Qt(t);if(l&&d){let u=await n.rest.pulls.get({owner:l,repo:d,pull_number:e.number});if(u.data&&(s+=$(u.data),o.head=u.data.head?.ref,o.head_sha=u.data.head?.sha,o.base=u.data.base?.ref,o.base_sha=u.data.base?.sha,o.draft=u.data.draft??!1,u.data.merged_at&&(o.merged_at=u.data.merged_at),o.additions=u.data.additions??0,o.deletions=u.data.deletions??0,Pn(t)||(o.file_changes={total_count:u.data.changed_files??0,files:[]}),Pn(t))){let m=await is(l,d,e.number);m&&(s+=q(m)??0,m.files=Cn(m.files,t),o.file_changes=m)}}}catch(l){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=Yi(t),c=Xi(t);if(a||c){let{owner:l,repo:d}=Qt(t);if(l&&d){let u=qi(t),m=()=>Promise.resolve({comments:D([],0)}),[{comments:p,note:f},{comments:h,note:R}]=await Promise.all([a?ts(n,l,d,e.number,u):m(),c?rs(n,l,d,e.number,u):m()]);o.comments=[...p,...h],s+=(q(p)??0)+(q(h)??0);let b=[f,R].filter(g=>typeof g=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(Ji(t))try{let{owner:l,repo:d}=Qt(t);if(l&&d){let u=await ns(n,l,d,e.number);s+=q(u)??0,o.reviews=u}}catch(l){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(Zi(t))try{let{owner:l,repo:d}=Qt(t);if(l&&d){let u=await ss(l,d,e.number,t);u&&(s+=q(u)??0,o.commits=u)}}catch(l){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return D(o,s)}async function Ur(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=$(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function is(e,t,n,r){let o=await ne(r),{items:i,rawResponseChars:s}=await Ur(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return D({total_count:i.length,files:i},s)}async function Sp(e,t,n,r){let o=await ne(r),{items:i,rawResponseChars:s}=await Ur(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return D(i,s)}async function Cp(e,t,n,r){try{let i=await(await ne(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return D(i.data.files||[],i.data)}catch{return null}}async function ss(e,t,n,r,o){let i=await Sp(e,t,n,o);if(!i)return null;let s=q(i)??0,a=[...i].sort((l,d)=>{let u=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(d.commit.author?.date?new Date(d.commit.author.date).getTime():0)-u}),c=await Promise.all(a.map(async l=>{let d=await Cp(e,t,l.sha,o),u=[];return d&&(s+=q(d)??0,u=Cn(d,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:u}}));return D(c,s)}async function En(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Gr(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,Pn(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Pn(t))try{let u=await is(a,c,e.number,r);u&&(s+=q(u)??0,u.files=Cn(u.files,t),o.file_changes=u)}catch(u){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let l=Yi(t),d=Xi(t);if(l||d){let u=qi(t),m=()=>Promise.resolve({comments:D([],0)}),[{comments:p,note:f},{comments:h,note:R}]=await Promise.all([l?ts(n,a,c,e.number,u):m(),d?rs(n,a,c,e.number,u):m()]);o.comments=[...p,...h],s+=(q(p)??0)+(q(h)??0);let b=[f,R].filter(g=>typeof g=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(Ji(t))try{let u=await ns(n,a,c,e.number);s+=q(u)??0,o.reviews=u}catch(u){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(Zi(t))try{let u=await ss(a,c,e.number,t,r);u&&(s+=q(u)??0,o.commits=u)}catch(u){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return D(o,s)}function Pp(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 as(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PR_REQUIRED_PARAMS.code),{pull_requests:[],total_count:0,error:te.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PR_SINGLE_VALUES.code),{pull_requests:[],total_count:0,error:te.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ne(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await En(a,e,i,t);return{pull_requests:[zt(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:$(s.data)+(q(c)??0)}}catch(i){let s=Z(i);return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PULL_REQUEST_FETCH_FAILED.code),Pp(s,te.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"])}}function cs(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 ls(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 us(e,t,n){let r=Pe("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,"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},n);return await Ee(r,async()=>await Ep(e,t,n),{shouldCache:i=>!i.error})}async function Ep(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await as(e,t);let r=await ne(t);if(!mi(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Tp(r,e);let i=pi(e);if(!i)return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.NO_VALID_PARAMETERS.code),{pull_requests:[],total_count:0,error:te.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let s=e.sort&&e.sort!=="best-match"?e.sort:void 0,a=Math.min(e.limit||30,100),c=e.page||1,l=i,d=await r.rest.search.issuesAndPullRequests({q:i,sort:s,order:e.order||"desc",per_page:a,page:c}),u=d.data.items?.filter(L=>!!L.pull_request)||[],m=await Promise.all(u.map(async L=>await os(L,e,r))),p=m.reduce((L,I)=>L+(q(I)??0),0),f=m.map(L=>zt(L,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:e.charOffset,charLength:e.charLength})),h=d.data.total_count,R=Math.min(h,1e3),b=Math.min(Math.ceil(R/a),10),g=Math.min(c,Math.max(1,b)),C=g<b,E=Math.min(R,b*a);return{pull_requests:f,total_count:d.data.total_count,effectiveQuery:l,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:g,totalPages:b,perPage:a,totalMatches:R,reportedTotalMatches:h,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:h>R,hasMore:C},rawResponseChars:$(d.data)+p}}catch(r){if(lt(r))return ls(e);let o=Z(r);return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PULL_REQUEST_SEARCH_FAILED.code),cs(o,te.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function Tp(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 En(m,t,e))),c=a.reduce((m,p)=>m+(q(p)??0),0),l=a.map(m=>zt(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),d=s.data.length===o,u=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:d?i+1:i,perPage:o,totalMatches:u+(d?1:0),reachableTotalMatches:u,totalMatchesKind:d?"lowerBound":"exact",hasMore:d},rawResponseChars:$(s.data)+c}}catch(n){if(lt(n))return ls(t);let r=Z(n);return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PULL_REQUEST_LIST_FAILED.code),cs(r,te.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}function wp(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 _p(e,t,n=de){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,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...wp(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function ds(e,t,n=de){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,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 us(s,t);return a.error?je({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:_p(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??$(a)}}import{RequestError as Ip}from"octokit";var dt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function Ap(e,t){return t?e>5e4?[`Response ~${e.toLocaleString()} tokens \u2014 exceeds typical context. Reduce charLength or refine the query.`]:e>3e4?[`Response ~${e.toLocaleString()} tokens \u2014 approaching context limit. Consider reducing charLength.`]:[]:[]}function Lp(e){if(e.hasMore&&e.nextCharOffset!==void 0){let t=e.charOffset+1,n=e.charOffset+e.charLength;return[`Page ${e.currentPage}/${e.totalPages} (chars ${t}-${n} of ${e.totalChars}). Next: charOffset=${e.nextCharOffset}`]}return[]}function ps(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...Ap(e.estimatedTokens,n)),o.push(...Lp(e)),o}function Tn(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function ms(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:P,...x}=e;return x}let r=t.itemsPerPage??dt.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),d=Object.create(null),u=e.path==="/"?"":e.path,m=P=>{let x=P;u&&P.startsWith(u)&&(x=P.slice(u.length),x.startsWith("/")&&(x=x.slice(1)));let A=x.lastIndexOf("/");return A===-1?".":x.slice(0,A)},p=P=>{let x=P.lastIndexOf("/");return x===-1?P:P.slice(x+1)};for(let P of l){let x=m(P.path);d[x]||(d[x]={files:[],folders:[]});let A=p(P.path);P.type==="file"?d[x].files.push(A):d[x].folders.push(A)}for(let P of Object.keys(d)){let x=d[P];x&&(x.files.sort(),x.folders.sort())}let f=Object.create(null),h=Object.keys(d).sort((P,x)=>P==="."?-1:x==="."?1:P.localeCompare(x));for(let P of h){let x=d[P];x&&(f[P]=x)}let R=l.filter(P=>P.type==="file").length,b=l.filter(P=>P.type==="dir").length,g=n.filter(P=>P.type==="file").length,C=n.filter(P=>P.type==="dir").length,E=o<s,L={currentPage:o,totalPages:s,hasMore:E,entriesPerPage:r,totalEntries:i},I=Tn(L,{owner:e.owner,repo:e.repo,branch:e.branch,path:u,depth:t.maxDepth??1,pageFiles:R,pageFolders:b,allFiles:g,allFolders:C}),k,j=e._cachedFileSizeMap;if(j){let P=new Set(l.filter(B=>B.type==="file").map(B=>B.path)),x=e.path==="/"?"":e.path,A=Object.create(null);for(let[B,N]of Object.entries(j))for(let[M,oe]of Object.entries(N)){let ae=B==="."?x?`${x}/${M}`:M:x?`${x}/${B}/${M}`:`${B}/${M}`;P.has(ae)&&(A[B]||(A[B]=Object.create(null)),A[B][M]=oe)}Object.keys(A).length>0&&(k=A)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:g,totalFolders:C,truncated:E,filtered:!0,originalCount:i},structure:f,...k!==void 0&&{fileSizeMap:k},...j!==void 0&&{_cachedFileSizeMap:j},pagination:L,hints:I,rawResponseChars:e.rawResponseChars}}async function zr(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return D([],0);a.add(o);try{let c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r}),l=$(c.data),u=(Array.isArray(c.data)?c.data:[c.data]).map(p=>({name:p.name,path:p.path,type:p.type,size:"size"in p?p.size:void 0,download_url:"download_url"in p?p.download_url:void 0,url:p.url,html_url:p.html_url,git_url:p.git_url,sha:p.sha})),m=[...u];if(i<s){let p=u.filter(h=>h.type==="dir"),f=3;for(let h=0;h<p.length;h+=f){let b=p.slice(h,h+f).map(async C=>{try{let E=await zr(e,t,n,r,C.path,i+1,s,a);return l+=q(E)??0,E}catch{return[]}});(await Promise.all(b)).forEach(C=>{m.push(...C)})}}return D(m,l)}catch{return D([],0)}}var wn=S.GITHUB_VIEW_REPO_STRUCTURE;async function Op(e,t,n,r,o,i){let s;try{s=o??await Oe(t,n,i)}catch(a){let c=Z(a);return await H(wn,Ge.NOT_FOUND.code),{error:Ge.NOT_FOUND.message(t,n,c.error),status:c.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s}}catch(a){if(!(a instanceof Ip&&a.status===404)){let l=Z(a);return await H(wn,Ge.ACCESS_FAILED.code),{error:Ge.ACCESS_FAILED.message(t,n,l.error),status:l.status,rateLimitRemaining:l.rateLimitRemaining,rateLimitReset:l.rateLimitReset,retryAfter:l.retryAfter}}let c=Z(a);return await H(wn,Ge.PATH_NOT_FOUND.code),{error:Ge.PATH_NOT_FOUND.message(r,t,n,s),status:c.status}}}function kp(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 vp(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 fs(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 hs(e,t,n){let r=Pe("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await Ee(r,async()=>await Fp({...e,itemsPerPage:e.itemsPerPage??dt.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?ms(o,e):o}async function Fp(e,t){try{let n=await ne(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await Op(n,r,o,c,i,t);if("error"in l)return l;let{data:d,workingBranch:u,repoDefaultBranch:m}=l,p=$(d),f=Array.isArray(d)?d:[d],h=kp(f);if(a>1){let Q=await zr(n,r,o,u,c,1,a);p+=q(Q)??0,h=[...h,...Q].filter((K,pe,Se)=>Se.findIndex(De=>De.path===K.path)===pe)}let R=h.filter(Q=>Q.type==="dir"?!Ut(Q.name):!Pt(Q.path));R.sort((Q,O)=>{if(Q.type!==O.type)return Q.type==="dir"?-1:1;let K=Q.path.split("/").length,pe=O.path.split("/").length;return K!==pe?K-pe:Q.path.localeCompare(O.path)});let b=e.itemsPerPage??dt.ENTRIES_PER_PAGE,g=e.page??1,C=R.length,E=Math.max(1,Math.ceil(C/b)),L=(g-1)*b,I=Math.min(L+b,C),k=R.slice(L,I),j=vp(k,c),P=e.includeSizes===!0?fs(R,c):void 0,x=P!==void 0?fs(k,c):void 0,A=k.filter(Q=>Q.type==="file").length,B=k.filter(Q=>Q.type==="dir").length,N=R.filter(Q=>Q.type==="file").length,M=R.filter(Q=>Q.type==="dir").length,oe=g<E,ae={currentPage:g,totalPages:E,hasMore:oe,entriesPerPage:b,totalEntries:C},ce=Tn(ae,{owner:r,repo:o,branch:u,path:c,depth:a,pageFiles:A,pageFolders:B,allFiles:N,allFolders:M});return{owner:r,repo:o,branch:u,...m!==void 0&&{defaultBranch:m},path:c||"/",apiSource:!0,summary:{totalFiles:N,totalFolders:M,truncated:oe,filtered:!0,originalCount:R.length},structure:j,...x!==void 0&&{fileSizeMap:x},...P!==void 0&&{_cachedFileSizeMap:P},pagination:ae,hints:ce,rawResponseChars:p,_cachedItems:R.map(Q=>({path:Q.path,type:Q.type}))}}catch(n){let r=Z(n);return await H(wn,Ge.STRUCTURE_EXPLORATION_FAILED.code),{error:Ge.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}function Mp(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 gs(e,t,n=de){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 hs(i,t);return"error"in s?hn(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:Mp(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??$(s)}}var ys={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};var _n=class{type="github";capabilities=ys.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await wi(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Ui(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await _i(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await ds(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await gs(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=de(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Oe(n,r,this.authInfo)}handleError(t){let n=Z(t);return je(n)}};import{createHash as Hp}from"crypto";var Dp=3600*1e3,Qr=20,Be=new Map;function Rs(e){return Date.now()-e.createdAt<Dp}function Gp(){for(let[e,t]of Be.entries())Rs(t)||Be.delete(e);if(Be.size>Qr){let e=[...Be.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Be.size-Qr;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Be.delete(r[0])}}}function $p(e){return e?Hp("sha256").update(e).digest("hex").slice(0,16):"default"}function Bp(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 Up(e,t){let n=Bp(t?.baseUrl||"default"),r=$p(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function jr(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=Up(e,t),r=Be.get(n);if(r&&Rs(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Be.delete(n),Be.size>=Qr&&Gp();let o=new _n({...t,type:e}),i=Date.now();return Be.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function bs(){try{return jr("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}
18
+ `),[{provider:"github",ok:!1,error:t}]}}import{CloneRepoQuerySchema as Yp}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as Xp}from"@octocodeai/octocode-core/schemas/outputs";import{z as xn}from"zod";function F(e,t){return xn.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,xn.number().int().min(e).max(t))}var J=F(1,1e3).optional().default(1),_t=F(0,100).optional(),xt=F(1,1e9).optional(),Qp={responseCharOffset:F(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:F(1,5e4).optional().describe("Full-response char window.")};function Y(e,t={}){let{maxQueries:n=5}=t;return xn.object({queries:xn.array(e).min(1).max(n).describe("Parallel queries."),...Qp}).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))})})}import{z as jp}from"zod";function Vp(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Ss(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=Vp(e.shape[r],o);return n}function Wp(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function ee(e,t={},n={}){let r=Wp(e,Ss(e,t));return n.strict?r.strict():r}function ie(e,t={},n={}){let r=jp.object({...e.shape,...Ss(e,t)});return n.strict?r.strict():r}import{z as fe}from"zod";var Kp=fe.object({currentPage:fe.number(),totalPages:fe.number(),hasMore:fe.boolean(),charOffset:fe.number(),charLength:fe.number(),totalChars:fe.number(),nextCharOffset:fe.number().optional()}).optional(),Te={hints:fe.array(fe.string()).optional(),base:fe.string().optional(),shared:fe.record(fe.string(),fe.union([fe.string(),fe.number(),fe.boolean()])).optional(),responsePagination:Kp};var Wr=ee(Yp),Cs=Y(Wr),jT=Xp.extend(Te);import{z as w}from"zod";import{FileContentQuerySchema as Ps}from"@octocodeai/octocode-core/schemas";var Zp=w.enum(["none","standard","symbols"]).optional().default("standard"),Jp=w.object({currentPage:w.number(),totalPages:w.number(),hasMore:w.boolean(),charOffset:w.number().optional(),charLength:w.number().optional(),totalChars:w.number().optional(),nextCharOffset:w.number().optional(),filesPerPage:w.number().optional(),totalFiles:w.number().optional(),entriesPerPage:w.number().optional(),totalEntries:w.number().optional(),matchesPerPage:w.number().optional(),totalMatches:w.number().optional()}),qp=w.object({path:w.string(),content:w.string(),contentView:w.enum(["none","standard","symbols"]).optional(),isSkeleton:w.boolean().optional(),totalLines:w.number().optional(),sourceChars:w.number().optional(),sourceBytes:w.number().optional(),resolvedBranch:w.string().optional(),pagination:Jp.optional(),isPartial:w.boolean().optional(),startLine:w.number().optional(),endLine:w.number().optional(),matchRanges:w.array(w.object({start:w.number(),end:w.number()})).optional(),lastModified:w.string().optional(),lastModifiedBy:w.string().optional(),warnings:w.array(w.string()).optional(),matchNotFound:w.boolean().optional(),searchedFor:w.string().optional()}),em=w.object({path:w.string(),localPath:w.string(),fileCount:w.number(),totalSize:w.number(),files:w.array(w.object({path:w.string(),size:w.number(),type:w.string()})).optional(),cached:w.boolean().optional(),resolvedBranch:w.string().optional()}),Es={startLine:xt,endLine:xt,contextLines:_t,charOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional(),minify:Zp},tm=ie(Ps,Es),An=ee(Ps,Es),Ts=Y(tm),qT=w.object({base:w.string().optional(),shared:w.record(w.string(),w.union([w.string(),w.number(),w.boolean()])).optional(),responsePagination:Te.responsePagination,results:w.array(w.object({id:w.string(),owner:w.string(),repo:w.string(),files:w.array(qp).optional(),directories:w.array(em).optional()})),hints:w.array(w.string()).optional(),errors:w.array(w.object({id:w.string(),owner:w.string().optional(),repo:w.string().optional(),path:w.string().optional(),error:w.string(),hints:w.array(w.string()).optional()})).optional()});import{z as v}from"zod";import{GitHubCodeSearchQuerySchema as ws}from"@octocodeai/octocode-core/schemas";var _s={limit:F(1,100).optional(),page:J.default(1)},xs=ee(ws,_s),As=Y(ie(ws,_s)),aw=v.object({base:v.string().optional(),shared:v.record(v.string(),v.union([v.string(),v.number(),v.boolean()])).optional(),responsePagination:Te.responsePagination,results:v.array(v.object({id:v.string(),data:v.object({files:v.array(v.object({id:v.string(),owner:v.string(),repo:v.string(),path:v.string(),queryId:v.string().optional(),matches:v.array(v.object({value:v.string().optional(),pathOnly:v.boolean().optional(),matchIndices:v.array(v.object({start:v.number(),end:v.number()})).optional(),url:v.string().optional()}))})),pagination:v.object({currentPage:v.number(),totalPages:v.number(),perPage:v.number(),totalMatches:v.number(),reportedTotalMatches:v.number().optional(),reachableTotalMatches:v.number().optional(),totalMatchesKind:v.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:v.boolean().optional(),hasMore:v.boolean(),uniqueFileCount:v.number().optional()}).optional()})})),hints:v.array(v.string()).optional(),emptyQueries:v.array(v.object({id:v.string(),hints:v.array(v.string()).optional(),nonExistentScope:v.literal(!0).optional()})).optional(),errors:v.array(v.object({id:v.string(),error:v.string(),hints:v.array(v.string()).optional()})).optional()});import{z as pt}from"zod";import{GitHubPullRequestSearchQuerySchema as Ls}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as rm}from"@octocodeai/octocode-core/schemas/outputs";var Is={perPage:F(1,100).optional().default(30),prNumber:F(1,1e9).optional(),limit:F(1,100).optional().default(30),page:J.default(1),filePage:J.optional(),commentPage:J.optional(),commitPage:J.optional(),itemsPerPage:F(1,100).optional().default(20),charOffset:F(0,1e8).optional(),commentBodyOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional()},om=ie(Ls,Is),Ln=ee(Ls,Is),Os=Y(om),gw=rm.extend({results:pt.array(pt.object({id:pt.string().optional(),status:pt.string().optional(),data:pt.object({pull_requests:pt.array(pt.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Te});import{z as V}from"zod";import{GitHubReposSearchSingleQuerySchema as ks}from"@octocodeai/octocode-core/schemas";var vs={limit:F(1,100).optional(),page:J.default(1)},Fs=ee(ks,vs),Ms=Y(ie(ks,vs)),im=V.object({owner:V.string(),repo:V.string(),stars:V.number().optional(),forks:V.number().optional(),openIssuesCount:V.number().optional(),language:V.string().optional(),license:V.string().optional(),description:V.string().optional(),homepage:V.string().optional(),pushedAt:V.string().optional(),createdAt:V.string().optional(),defaultBranch:V.string().optional(),topics:V.array(V.string()).optional(),visibility:V.string().optional(),url:V.string().optional(),updatedAt:V.string().optional()}),sm=V.object({currentPage:V.number(),totalPages:V.number(),hasMore:V.boolean(),perPage:V.number().optional(),totalMatches:V.number().optional(),reportedTotalMatches:V.number().optional(),reachableTotalMatches:V.number().optional(),totalMatchesKind:V.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:V.boolean().optional()}).optional(),am=V.object({repositories:V.array(V.union([V.string(),im])).optional(),pagination:sm}).passthrough(),Tw=V.object({results:V.array(V.object({id:V.string().optional(),status:V.string().optional(),data:am.optional()}).passthrough()).optional()}).extend(Te);import{GitHubViewRepoStructureQuerySchema as Ns}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as lm}from"@octocodeai/octocode-core/schemas/outputs";var Hs={maxDepth:F(0,20).optional(),page:J.default(1),itemsPerPage:F(1,200).optional()},Ds=ee(Ns,Hs),Gs=Y(ie(Ns,Hs)),vw=lm.extend(Te);import{z as re}from"zod";import{NpmPackageQuerySchema as $s}from"@octocodeai/octocode-core/schemas";var Bs={page:J,mode:re.enum(["lean","full"]).optional()},Us=ee($s,Bs),zs=Y(ie($s,Bs,{strict:!0}),{maxQueries:5}),$w=re.object({results:re.array(re.looseObject({id:re.string(),data:re.looseObject({packages:re.array(re.object({name:re.string(),version:re.string().optional(),description:re.string().optional(),license:re.string().optional(),weeklyDownloads:re.number().optional(),repository:re.string().optional(),repositoryDirectory:re.string().optional()}).passthrough()).optional(),pagination:re.object({currentPage:re.number(),totalPages:re.number(),perPage:re.number(),totalFound:re.number(),returned:re.number(),hasMore:re.boolean()}).optional()}).optional(),status:re.string().optional()})).optional()}).extend(Te);import{z as um}from"zod";import{FetchContentQuerySchema as Qs}from"@octocodeai/octocode-core/schemas";var dm=um.enum(["none","standard","symbols"]).optional().default("standard"),js={startLine:xt,endLine:xt,contextLines:_t.default(5),charOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional(),minify:dm},pm=ie(Qs,js),In=ee(Qs,js),Vs=Y(pm,{maxQueries:5});import{z as mm}from"zod";import{FindFilesQuerySchema as fm}from"@octocodeai/octocode-core/schemas";var Ws={maxDepth:F(0,100).optional(),minDepth:F(0,100).optional(),limit:F(1,1e4).optional(),page:J.default(1),itemsPerPage:F(1,50).optional()},Ks=mm.object(Object.fromEntries(Object.entries(fm.shape).filter(([e])=>e!=="regexType")));function hm(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 gm=ie(Ks,Ws),On=ee(Ks,Ws).superRefine(hm),Ys=Y(gm,{maxQueries:5});import{RipgrepQuerySchema as Xs}from"@octocodeai/octocode-core/schemas";var Zs={contextLines:_t,matchContentLength:F(1,1e5).optional().default(500),maxMatchesPerFile:F(1,1e5).optional(),maxFiles:F(1,1e5).optional(),matchPage:J.optional(),itemsPerPage:F(1,1e3).optional(),page:J.default(1)},ym=ie(Xs,Zs),tt=ee(Xs,Zs,{strict:!0}),Js=Y(ym,{maxQueries:5});import{ViewStructureQuerySchema as qs}from"@octocodeai/octocode-core/schemas";var ea={maxDepth:F(0,20).optional(),limit:F(1,1e4).optional(),page:J.default(1),itemsPerPage:F(1,50).optional()},Rm=ie(qs,ea),kn=ee(qs,ea),ta=Y(Rm,{maxQueries:5});import{z as y}from"zod";import{LspGetSemanticsQuerySchema as oa}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as bm}from"@octocodeai/octocode-core/schemas/outputs";var Sm=F(1,1e9),Cm=F(0,1e5).optional(),Pm=["structured","compact"],ia={type:y.enum(qo).default("definition"),symbolName:y.string().min(1).optional(),lineHint:Sm.optional(),orderHint:Cm,depth:F(0,20).optional(),includeDeclaration:y.boolean().optional().default(!0),page:J,itemsPerPage:F(1,100).optional(),contextLines:F(0,100).optional(),format:y.enum(Pm).optional().default("structured")},Em=ie(oa,ia),sa=ee(oa,ia);var aa=Y(Em,{maxQueries:5}),na=y.object({line:y.number(),character:y.number()}),Tm=y.object({start:na,end:na}),wm=y.object({startLine:y.number(),endLine:y.number()}),vn=y.object({uri:y.string(),content:y.string().optional(),displayRange:wm.optional(),isDefinition:y.boolean().optional()}),Fn=y.string(),_m=y.object({name:y.string(),uri:y.string(),foundAtLine:y.number(),orderHint:y.number().optional()}),xm=y.object({serverAvailable:y.boolean().optional(),provider:y.string().optional(),source:y.string().optional()}),ca=y.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls"]),Xr=y.object({category:ca,reason:y.string()}),Am=y.object({currentPage:y.number(),totalPages:y.number(),totalResults:y.number(),hasMore:y.boolean(),itemsPerPage:y.number(),nextPage:y.number().optional()}),Lm=y.object({name:y.string(),kind:y.string(),line:y.number(),character:y.number(),endLine:y.number(),childCount:y.number(),containerName:y.string().optional()}),Im=y.string(),la=y.object({name:y.string(),kind:y.string(),uri:y.string(),line:y.number(),endLine:y.number(),selectionLine:y.number().optional()}),Om=y.string(),km=y.object({direction:y.enum(["incoming","outgoing"]),item:la,ranges:y.array(y.object({line:y.number(),character:y.number()})),rangeCount:y.number(),rangeSampleCount:y.number(),contentPreview:y.string().optional()}),vm=y.string(),Fm=y.object({complete:y.boolean(),truncatedByDepth:y.boolean(),cycleCount:y.number(),failedRequestCount:y.number(),dynamicCallsExcluded:y.literal(!0),stdlibCallsExcluded:y.number().optional()}),Mm=y.object({uri:y.string(),count:y.number(),firstLine:y.number(),firstCharacter:y.number(),lines:y.array(y.number()),hasDefinition:y.boolean().optional()}),Nm=y.string(),Hm=y.discriminatedUnion("kind",[y.object({kind:y.literal("definition"),locations:y.array(y.union([vn,Fn]))}),y.object({kind:y.literal("typeDefinition"),locations:y.array(y.union([vn,Fn]))}),y.object({kind:y.literal("implementation"),locations:y.array(y.union([vn,Fn]))}),y.object({kind:y.literal("references"),locations:y.array(y.union([vn,Fn])).optional(),byFile:y.array(y.union([Mm,Nm])).optional(),totalReferences:y.number(),totalFiles:y.number(),empty:Xr.optional()}),...["callers","callees","callHierarchy"].map(e=>y.object({kind:y.literal(e),root:y.union([la,Om]).optional(),direction:y.enum(["incoming","outgoing","both"]),calls:y.array(y.union([km,vm])),incomingCalls:y.number(),outgoingCalls:y.number(),completeness:Fm,empty:Xr.optional()})),y.object({kind:y.literal("hover"),markdown:y.string().optional(),text:y.string().optional(),range:Tm.optional()}),y.object({kind:y.literal("documentSymbols"),symbols:y.array(y.union([Lm,Im])),totalSymbols:y.number().optional(),topLevelSymbols:y.number().optional(),empty:Xr.optional()}),y.object({kind:y.literal("empty"),category:ca,reason:y.string()})]),ra=y.object({type:y.string(),uri:y.string(),format:y.enum(["structured","compact"]).optional(),resolvedSymbol:_m.optional(),lsp:xm,payload:Hm,pagination:Am.optional(),summary:y.record(y.string(),y.unknown()).optional(),warnings:y.array(y.string()).optional(),hints:y.array(y.string()).optional()}),y_=y.object({base:y.string().optional(),shared:y.record(y.string(),y.union([y.string(),y.number(),y.boolean()])).optional(),hints:y.array(y.string()).optional(),results:y.array(y.union([y.object({id:y.string().min(1),status:y.literal("empty"),data:ra}),y.object({id:y.string().min(1),status:y.literal("error"),data:bm}),y.object({id:y.string().min(1),data:ra})]))});import{z as Dm}from"zod";import{LocalBinaryInspectQuerySchema as Gm}from"@octocodeai/octocode-core/schemas";var $m={entryPageNumber:J.default(1),matchStringContextLines:F(0,50).default(3),charLength:F(1,5e4).optional(),page:J.default(1)},ua=Dm.object({...Gm.shape,...$m}),Mn=ua.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".'})}),da=Y(ua,{maxQueries:5});import{incrementToolCharSavings as Jm}from"octocode-shared";function He(e){return t=>{}}function pa(e,t){return n=>t}async function ma(e,t={}){if(!Array.isArray(e))throw H("promiseUtils",Ze.PROMISES_NOT_ARRAY.code).catch(He("promise utility session logging")),new Error(Ze.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw H("promiseUtils",Ze.TIMEOUT_NOT_POSITIVE.code).catch(He("promise utility session logging")),new Error(Ze.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw H("promiseUtils",Ze.CONCURRENCY_NOT_POSITIVE.code).catch(He("promise utility session logging")),new Error(Ze.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>(H("promiseUtils",qe.NOT_A_FUNCTION.code).catch(He("promise utility session logging")),Promise.reject(new Error(qe.NOT_A_FUNCTION.message(l)))));if(r<i.length)return Bm(i,r,n,o);let s=i.map((c,l)=>fa(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 fa(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{H("promiseUtils",qe.TIMEOUT.code).catch(()=>{}),l(new Error(qe.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 Bm(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){H("promiseUtils",qe.FUNCTION_UNDEFINED.code).catch(He("promise utility session logging")),o[c]={success:!1,error:new Error(qe.FUNCTION_UNDEFINED.message),index:c};continue}try{let d=await fa(l,c,n,r);o[c]=d}catch(d){o[c]={success:!1,error:d instanceof Error?d:new Error(String(d)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}import{maskSensitiveData as ha}from"octocode-security/mask";import{ContentSanitizer as ga}from"octocode-security/contentSanitizer";import{getConfigSync as Um}from"octocode-shared";function zm(){try{return Um().output.format}catch{return"yaml"}}function nt(e){if(e==null)return e;if(typeof e=="string"){let t=ga.sanitizeContent(e);return ha(t.content)}if(Array.isArray(e))return e.map(t=>nt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=nt(r);return t}return e}function Qm(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
19
+
20
+ `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Hn(e,t){let n=Zr(e)??{},r=zm(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;r==="json"?i=JSON.stringify(Nn(n,t||o),null,2):i=U.jsonToYamlString(n,{keysPriority:t||o});let s=ga.sanitizeContent(i);return ha(s.content)}function Nn(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Nn(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Nn(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Nn(n[o],t));return r}var jm=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"]);function Vm(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=>jm.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Zr(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=>Zr(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(Vm(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Zr(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}function Wm(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):""}var qr=["path","uri"];function Jr(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Jr(o,t,n+1);return}let r=e;for(let o of qr){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 of Object.values(r))o&&typeof o=="object"&&Jr(o,t,n+1)}function ya(e){let t=[];for(let i of e)Jr(i?.data,t,0);if(t.length===0)return;let n=Wm(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 Km(e,r),n}function Km(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)){let a=i[s];typeof a=="string"?!qr.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function Ym(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 Xm(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var Zm=new Set([...qr,"owner","repo","name","id"]);function Ra(e){let t=Ym(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(Zm.has(i))continue;let s=n[i];Xm(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 qm=3,ba=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,ef=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,tf=5e3;function nf(e,t,n){if(e<=1)return ba;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(ef/o),s=Math.max(tf,Math.min(i,ba));return n?Math.max(s,n):s}async function X(e,t,n,r){let o=n.concurrency??qm,{results:i,errors:s}=await af(e,t,o,n.minQueryTimeoutMs);return rf(n,i,s,e,r)}function rf(e,t,n,r,o){let i=["results","hints","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let C=g.result.status;c[g.queryIndex]={id:Ta(g.originalQuery,g.queryIndex),...C!==void 0?{status:C}:{},data:lf(g.result)}}),n.forEach(g=>{let C=r[g.queryIndex];C&&(c[g.queryIndex]={id:Ta(C,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),C=Sa(g.text,o),E=Ca(g.structuredContent,C.pagination);return Ea(e.toolName,t,n,C.text.length),{content:[{type:"text",text:C.text}],structuredContent:E,isError:g.isError??(l.length>0&&l.every(I=>I.status==="error"))}}let d=e.peerHints?Pa(l):[],u={results:l};if(Array.isArray(u.results)){let g=ya(u.results);g&&(u.base=g);let C=Ra(u.results);C&&(u.shared=C)}let m=e.peerHints?Pa(Array.isArray(u.results)?u.results:[]):[],p=e.peerHints?Array.from(new Set([...d,...m])):d;p.length>0&&(u.hints=p);let f=Hn(u,a),h=Sa(f,o),R=Ca(nt(u),h.pagination);return Ea(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:R,isError:l.length>0&&l.every(g=>g.status==="error")}}function eo(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 of(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=eo(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function sf(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=eo(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 Sa(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=eo(e,s,i),c=a<o,l=of(e,s,i),d=sf(e,i),u=e.slice(s,a);return{text:`${c?`# Response page ${l}/${d}. Next: responseCharOffset=${a}
22
+ `:`# Response page ${l}/${d}.
23
+ `}${u}`,pagination:{currentPage:l,totalPages:d,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Ca(e,t){if(!t)return e;let n=t.charOffset+1,r=t.charOffset+t.charLength;return{...e,responsePagination:t,hints:[...Array.isArray(e.hints)?e.hints.filter(o=>typeof o=="string"):[],t.hasMore?`Response page ${t.currentPage}/${t.totalPages} (chars ${n}-${r} of ${t.totalChars}). Next: responseCharOffset=${t.nextCharOffset}`:`Response page ${t.currentPage}/${t.totalPages} (chars ${n}-${r} of ${t.totalChars}).`]}}function Pa(e){let t=new Set,n=[];for(let r of e){let o=r.data,i=o&&Array.isArray(o.hints)?o.hints:[];for(let s of i)typeof s=="string"&&s.trim().length>0&&!t.has(s)&&(t.add(s),n.push(s));o&&"hints"in o&&delete o.hints}return n}function Ea(e,t,n,r){let o=t.reduce((i,s)=>i+(q(s.result)??$(s.result)),0)+n.reduce((i,s)=>i+$(s),0);try{Jm(e,o,r)}catch{}}async function af(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(d=>({result:d,queryIndex:l,originalQuery:c})));return(await ma(s,{timeout:nf(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})}),{results:o,errors:i}}function cf(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.trim().length>0);return t.length>0?t:void 0}function lf(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))if(!t.has(r))if(r==="hints"){let i=cf(o);i&&(n[r]=i)}else n[r]=o;return n}function Ta(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 wa={empty:(e={})=>{let t=e;if(t.mode==="structural")return["No structural matches. The pattern must be a complete code fragment for the target language; use $X for a single node, $$$ARGS for a list.","For relational rules (inside/has/not), add `stopBy: end` so the sub-rule walks all ancestors/descendants \u2014 without it the rule silently matches nothing.","Verify the file extension is one the engine parses (ts/tsx/js/py/go/rs/java/c/cpp/cs/sh), and widen the path."];let n=typeof t.path=="string"?t.path:void 0,r=typeof t.langType=="string"?t.langType:typeof t.type=="string"?t.type:void 0,o=Array.isArray(t.include)?t.include:[],i=Array.isArray(t.excludeDir)?t.excludeDir:[],s=typeof t.keywords=="string"?t.keywords:void 0,a=r||o.length>0||i.length>0,c=typeof t.searchEngine=="string"?t.searchEngine:void 0;if(!s&&!n&&!a)return[];let l=a?["Remove include/exclude/langType first, then retry a shorter or literal term."]:["Try a shorter partial term, fixedString=true for literals, or search a parent directory."];return c==="grep"?["grep fallback active \u2014 perlRegex patterns (lookaheads, backreferences) unsupported; use fixedString:true or simplify the pattern.",...l]:l},error:(e={})=>e.errorType==="size_limit"?[`Too many results${e.matchCount?` (${e.matchCount} matches)`:""} \u2014 narrow, add a filter, or use fixedString=true.`]:e.errorType==="not_found"?["Path not found \u2014 verify with localViewStructure."]:[]};var _a={empty:(e={})=>{let t=e;return(typeof t.path=="string"?t.path:void 0)?["Confirm path with `localFindFiles`."]:[]},error:(e={})=>{if(e.errorType==="size_limit"){let t=e,n=typeof t.fileSize=="number"?` (~${Math.round(t.fileSize/1024)}KB)`:"",r=typeof t.totalLines=="number"?t.totalLines:void 0,o=r?Math.max(1,r-200):void 0,i=[`File${n} too large \u2014 use matchString or startLine+endLine for a slice.`,'Or minify="symbols" for a skeleton index, then startLine/endLine.'];return o&&r&&i.push(`Tail: startLine=${o}, endLine=${r}.`),i}if(e.errorType==="directory"){let t=e;return[`${typeof t.path=="string"?`'${t.path}'`:"Path"} is a directory \u2014 use \`localViewStructure\` to explore it.`]}return e.errorType==="not_found"?["Use `localFindFiles` to locate the correct path."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]}};var xa={empty:(e={})=>{let t=e,n=Array.isArray(t.extensions)?t.extensions.filter(i=>typeof i=="string"):[],r=typeof t.pattern=="string"?t.pattern:void 0,o=[...r?[`pattern="${r}"`]:[],...n.length>0?[`extensions=${n.join(",")}`]:[]];return o.length===0?[]:[`No entries matched ${o.join(" + ")} \u2014 remove filters or increase depth/recursive.`]},error:(e={})=>e.errorType==="not_found"?["Path must be absolute \u2014 use localFindFiles to discover the correct path."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]};var Aa={empty:(e={})=>{let t=e,n=Array.isArray(t.names)&&t.names.length>0?t.names:void 0,r=typeof t.modifiedWithin=="string"?t.modifiedWithin:void 0,o=typeof t.sizeGreater=="string"?t.sizeGreater:void 0,i=typeof t.sizeLess=="string"?t.sizeLess:void 0,s=[];return n&&s.push(`names=${JSON.stringify(n)}`),r&&s.push(`modifiedWithin="${r}"`),o&&s.push(`sizeGreater="${o}"`),i&&s.push(`sizeLess="${i}"`),s.length===0?[]:[`No metadata match for ${s.join(", ")} \u2014 remove one filter or broaden names.`,"For content text, switch to `localSearchCode`."]},error:(e={})=>e.errorType==="not_found"?["Verify path with `localViewStructure` at the parent directory."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]};var La={empty:(e={})=>{let t=e,n=Array.isArray(t.keywords)?t.keywords:void 0,r=typeof t.owner=="string"?t.owner:void 0,o=typeof t.repo=="string"?t.repo:void 0,i=typeof t.extension=="string"||typeof t.filename=="string"||typeof t.path=="string";if(t.nonExistentScope===!0)return[`"${r&&o?`${r}/${o}`:r||"target"}" doesn't exist or isn't accessible \u2014 check spelling.`];if(e.hasOwnerRepo&&r&&o)return[i?"Remove path/filename/extension first, then retry keywords.":`No results in ${r}/${o} \u2014 large or popular repos often require narrowing: add extension, filename, or path to reduce scope. Repo may also be unindexed (new/private/recently renamed). Fall back to ghGetFileContent with a known path, or ghViewRepoStructure to discover paths.`,"GitHub code search indexes the default branch only."];let s=[];return n&&n.length===1&&typeof n[0]=="string"&&/^@[\w-]+\/[\w.-]+$|^[a-z][\w]*[-.][\w.-]+$/.test(n[0])&&s.push(`"${n[0]}" looks like a package name \u2014 try \`npmSearch\`.`),s.length===0&&n&&n.length>0&&s.push('Scope to owner/repo, split into one-keyword queries, or try a shorter exact term. For large repos (react, webpack, electron), narrow with extension="ts" or path="src".'),s},error:(e={})=>{let t=[];return e.isRateLimited&&t.push(`Rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:""}`),e.status===401&&t.push("GITHUB_TOKEN missing/expired."),e.status===403&&!e.isRateLimited&&t.push("Token lacks `repo` scope."),t}};var Ia={empty:(e={})=>{let t=e;return(typeof t.path=="string"?t.path:void 0)?["Verify it's a file, not a directory \u2014 use `ghViewRepoStructure`."]:[]},error:(e={})=>{if(e.errorType==="size_limit"){let t=e,n=typeof t.fileSize=="number"?`${t.fileSize}KB `:"",r=typeof t.totalLines=="number"?t.totalLines:void 0,o=r?Math.max(1,r-200):void 0,i=[`Large file ${n}\u2014 use startLine+endLine or matchString for a slice.`,'Or minify="symbols" for a skeleton index, then startLine/endLine.'];return o&&r&&i.push(`Tail: startLine=${o}, endLine=${r}.`),i}if(e.errorType==="not_found"){let t=e;return["Verify path with `ghViewRepoStructure`.",...(typeof t.branch=="string"?t.branch:void 0)?["Omit `branch` to use the default branch."]:[]]}return e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks `repo` scope."]:[]}};var Oa={empty:(e={})=>{let t=e;return t.wasFilteredToEmpty===!0?["All entries were filtered by the ignored-paths list (node_modules, .git, dist, etc.). Path is valid \u2014 navigate to a specific subdirectory."]:(typeof t.path=="string"&&t.path?t.path:void 0)?["Try the parent path, or omit `path` to list from root."]:[]},error:(e={})=>{if(e.isRateLimited)return[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`];if(e.status===401)return["GITHUB_TOKEN is missing or expired."];if(e.status===403)return["Token lacks `repo` scope."];if(e.status===404){let t=e,n=typeof t.owner=="string"?t.owner:void 0,r=typeof t.repo=="string"?t.repo:void 0;return[`${n&&r?`'${n}/${r}'`:"the repository"} not found \u2014 check spelling or use \`ghSearchRepos\`.`]}return[]}};var ka={empty:(e={})=>{let t=e;if((typeof t.type=="string"?t.type:"prs")==="commits"){let p=typeof t.path=="string"?t.path:void 0;return p?p.endsWith("/")?[`No commits found under "${p}". Check the directory prefix or widen since/until.`]:[`No commits found for "${p}". Check path spelling or widen since/until.`,"File may have been renamed \u2014 re-query with its previous name."]:["No commits found. Try widening since/until or removing the author filter."]}let r=typeof t.state=="string"?t.state:void 0,o=typeof t.owner=="string"?t.owner:void 0,i=typeof t.repo=="string"?t.repo:void 0,s=typeof t.author=="string"?t.author:void 0,a=typeof t.query=="string"?t.query:void 0,c=typeof t.prNumber=="number"?t.prNumber:void 0,d=(Array.isArray(t.prMatch)?t.prMatch:void 0)?.includes("title")??!1,u=o&&i?`${o}/${i}`:void 0;if(c!==void 0&&u)return[`PR #${c} not found in ${u}. Verify the PR number, or search by title using keywordsToSearch with match:["title"].`];let m=[];return r&&m.push(`state=${r}`),s&&m.push(`author=${s}`),a&&m.push(`query="${a}"`),m.length===0?[]:[r==="merged"?"No merged PRs matched \u2014 widen the date range or remove author/label filters.":"Remove filters one at a time to find what is too narrow.",...a&&!d?['For title-only matching use match:["title"] with sort:"best-match".']:a?[]:["Add a keyword (keywordsToSearch) to narrow by title or body text."]]},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks repo scope \u2014 check GITHUB_TOKEN permissions."]:[]};var va={empty:(e={})=>{let t=e,n=typeof t.query=="string"?t.query:void 0,r=Array.isArray(t.keywords)?t.keywords:void 0,o=typeof t.language=="string"?t.language:void 0,i=typeof t.owner=="string"?t.owner:void 0,s=typeof t.topic=="string"?t.topic:void 0,a=o||i||s,c=n??(r&&r.length>0?String(r[0]):void 0);if(!c&&!a)return[];let l=[a?"Remove owner/language/topic first, then retry fewer keywords.":'Try fewer/simpler keywords, or use match:["name"] for exact-name lookup.'];return c&&/^@[\w-]+\/[\w.-]+$|^[a-z][\w]*[-.][\w.-]+$/.test(c)&&l.push(`"${c}" looks like a package \u2014 use \`npmSearch\` instead.`),l},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks `public_repo` scope."]:[]};var Fa={empty:(e={})=>{let t=e;return(typeof t.sparsePath=="string"?t.sparsePath:typeof t.path=="string"?t.path:void 0)?["Omit `sparsePath` to check out the full repo.","Confirm path with `ghViewRepoStructure` before cloning sparse."]:[]},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`,"Use `ghViewRepoStructure` to inspect the tree without cloning."]:e.errorType==="permission"?["Token lacks read access \u2014 verify GITHUB_TOKEN has `repo` scope."]:e.errorType==="not_found"?["Check spelling or omit `branch` to use the default branch."]:e.errorType==="timeout"?["Clone timed out \u2014 use `sparsePath` for a subdirectory only."]:[]};function uf(e){let t=[];if(e.includes("-")&&(t.push(e.replace(/-/g,"_")),t.push(e.replace(/-/g,""))),e.includes("_")&&t.push(e.replace(/_/g,"-")),e.startsWith("@")){let n=e.split("/").pop();n&&t.push(n)}return e.endsWith("js")||t.push(e+"js"),[...new Set(t)].filter(n=>n!==e).slice(0,3)}var Ma={empty:(e={})=>{let t=e,n=typeof t.name=="string"?t.name:void 0;if(!n)return[];let r=uf(n);return["Check spelling and remove any version suffix.","Not on npm? Use `ghSearchRepos` instead.",...r.length?[`Try: ${r.join(", ")}`]:[]]},error:(e={})=>e.isRateLimited?[`npm registry rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.originalError?["npm registry unreachable \u2014 use `ghSearchRepos` instead."]:[]};var Na={empty:(e={})=>{let t=typeof e.symbolName=="string"?e.symbolName:"",n=e,r=typeof n.type=="string"?n.type:void 0;return!t&&!r?[]:r==="documentSymbols"?["Verify uri with localFindFiles/localSearchCode, then retry."]:r==="references"?["references is bounded to the current package (open TS server files) \u2014 cross-package calls will not appear.",'Use type="callers" for cross-package incoming calls.']:["Re-anchor with localSearchCode to get uri+symbolName+lineHint; use documentSymbols if the symbol is ambiguous."]},error:(e={})=>e.errorType==="lsp_unavailable"?["Language server unavailable \u2014 use localSearchCode for references and localGetFileContent for source slices."]:e.errorType==="symbol_not_found"?["Run localSearchCode for the exact symbol line, then retry with updated uri+lineHint."]:[]};function rt(e,t){return t?[...{documentSymbols:["Use returned line values as lineHint for definition, references, or callers."],hover:['type="definition" to jump to source, type="callers" for cross-package usage.'],definition:['localGetFileContent for context, type="callers" for cross-package impact, type="references" for same-package usages.'],typeDefinition:['localGetFileContent for the type, type="implementation" for concrete implementations.'],implementation:['localGetFileContent for implementation, type="callers" for call sites.'],references:["groupByFile=true for compact summary, localGetFileContent for context.","Scope: bounded by files open in the TS server (current package). Use callers/callHierarchy for cross-package blast radius."],callers:["Increase depth for a wider tree, localGetFileContent for context."],callees:['Increase depth, type="definition" on returned calls for source.'],callHierarchy:["Increase depth, localGetFileContent on call sites for context."]}[e]??[]]:[...{definition:["Re-anchor with localSearchCode and retry."],hover:['Try type="definition" instead.'],typeDefinition:['Try type="hover" for the inferred type.'],references:["references is bounded to the current package (open TS server files) \u2014 cross-package calls will not appear.",'Use type="callers" for cross-package incoming calls.'],callers:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" for same-package usages instead.',"Use localSearchCode for dynamic references."],callees:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" or localSearchCode instead.',"Use localSearchCode for dynamic calls."],callHierarchy:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" for same-package usages instead.',"Use localSearchCode for dynamic references."],documentSymbols:['Use localSearchCode with "export|function|class|const" as a fallback.'],implementation:["symbolName must be a method/property of an interface or abstract class \u2014 not the class name.",'Use type="documentSymbols" to list members, then retry with a member name.']}[e]??[]]}var Ha={[W.LOCAL_RIPGREP]:wa,[W.LOCAL_FETCH_CONTENT]:_a,[W.LOCAL_VIEW_STRUCTURE]:xa,[W.LOCAL_FIND_FILES]:Aa,[W.GITHUB_SEARCH_CODE]:La,[W.GITHUB_FETCH_CONTENT]:Ia,[W.GITHUB_VIEW_REPO_STRUCTURE]:Oa,[W.GITHUB_SEARCH_PULL_REQUESTS]:ka,[W.GITHUB_SEARCH_REPOSITORIES]:va,[W.GITHUB_CLONE_REPO]:Fa,[W.PACKAGE_SEARCH]:Ma,[ge]:Na};function Da(e){return e in Ha}function Ga(e,t,n){let r=Ha[e]?.[t];return r?r(n||{}).filter(i=>typeof i=="string"):[]}function se(e,t,n){if(!Da(e))return[];let r=Ga(e,t,n);return[...new Set(r)]}var G={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"};var $a={[G.PATH_VALIDATION_FAILED]:{code:G.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[G.FILE_ACCESS_FAILED]:{code:G.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[G.FILE_READ_FAILED]:{code:G.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[G.FILE_TOO_LARGE]:{code:G.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[G.BINARY_FILE_UNSUPPORTED]:{code:G.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[G.NO_MATCHES]:{code:G.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[G.OUTPUT_TOO_LARGE]:{code:G.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[G.COMMAND_NOT_AVAILABLE]:{code:G.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[G.COMMAND_EXECUTION_FAILED]:{code:G.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[G.COMMAND_TIMEOUT]:{code:G.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[G.TOOL_EXECUTION_FAILED]:{code:G.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"}};var be=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=$a[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 to(e){return e instanceof be}function Ba(e,t=G.TOOL_EXECUTION_FAILED,n){if(to(e))return e;if(e instanceof Error)return new be(t,e.message,n,e);let r=String(e);return new be(t,r,n)}function Ua(e){let t=[];if(e.scopesSuggestion&&t.push(e.scopesSuggestion),e.rateLimitRemaining!==void 0&&e.rateLimitReset!==void 0){let n=e.rateLimitReset;if(!isNaN(n)){let r=new Date(n);t.push(`Rate limit: ${e.rateLimitRemaining} remaining, resets at ${r.toISOString()}`)}}return e.retryAfter!==void 0&&t.push(`Retry after ${e.retryAfter} seconds`),t}function df(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function _(e,t,n={}){let{toolName:r,hintContext:o,extra:i,customHints:s,hintSourceError:a}=n,c={status:"error"},l=[];if(a&&l.push(...Ua(a)),df(e))c.error=e,a||l.push(...Ua(e));else if(to(e)){if(c.error=e.message,c.errorCode=e.errorCode,r){let u=se(r,"error",{originalError:e.message,errorType:pf(e),...o});l.push(...u)}}else if(typeof e=="string")c.error=e;else if(e instanceof Error){let u=Ba(e);if(c.error=u.message,c.errorCode=u.errorCode,r){let m=se(r,"error",{originalError:u.message,...o});l.push(...m)}}else c.error="Unknown error occurred";s&&s.length>0&&l.push(...s),i?.hints&&Array.isArray(i.hints)&&l.push(...i.hints);let d=l.filter(u=>typeof u=="string"&&u.trim().length>0);if(d.length>0&&(c.hints=d),i){let{hints:u,...m}=i;Object.assign(c,m)}return n.rawResponse===void 0?c:D(c,n.rawResponse)}function pf(e){switch(e.errorCode){case"fileTooLarge":case"outputTooLarge":return"size_limit";case"fileAccessFailed":case"fileReadFailed":return mf(e)?"directory":"not_found";case"pathValidationFailed":return"permission";default:return}}function mf(e){if(e.context?.errorCode==="EISDIR")return!0;let t=e.cause;return typeof t=="object"&&t!==null&&t.code==="EISDIR"}function ye(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t},a=i==="empty"?se(r,"empty",o?.hintContext):[],c=o?.prefixHints||[],l=o?.extraHints||[],d=[...new Set([...c,...a,...l])].filter(u=>typeof u=="string"&&u.trim().length>0);return d.length>0&&(s.hints=d),o?.rawResponse===void 0?s:D(s,o.rawResponse)}function Dn(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},r=Array.isArray(e.hints)?e.hints:[];return _(n,t,{hintSourceError:n,customHints:r,rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function he(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return H(r||n||"unknown_tool",Rr.EXECUTION_FAILED.code).catch(()=>{}),_(i,t)}async function we({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return he(o,t,r,e)}}import{promises as Lf}from"fs";import{securityRegistry as If}from"octocode-security/registry";import za from"path";import{pathValidator as ff}from"octocode-security/pathValidator";import{redactPath as Kt}from"octocode-security/pathUtils";var ke={pathValidationFailed:(e,t,n)=>new be(G.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Kt(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Kt(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 be(G.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new be(G.FILE_READ_FAILED,`Failed to read file: ${Kt(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new be(G.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 be(G.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Kt(e)}`,{path:e}),outputTooLarge:(e,t)=>new be(G.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new be(G.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 be(G.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new be(G.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{getConfigSync as hf}from"octocode-shared";function gf(e,t,n,r){let o=[],i=e!==r?` (resolved to: ${r})`:"";return o.push(`CWD: ${n}`),t?.includes("outside allowed")?o.push(`Fix: Use absolute path within workspace, e.g. path="${n}/..."${i}`):t?.includes("Permission denied")?o.push("Fix: Check file/directory permissions"):t?.includes("Symlink")||t?.includes("symlink")?o.push("Fix: Symlink target may be outside allowed directories"):(t?.includes("ENOENT")||t?.includes("not found"))&&o.push(`Fix: Path not found. Use absolute path, e.g. path="${n}/..."${i}`),o}function Re(e,t){if(!e.path?.trim()){let s=ke.pathValidationFailed("","path is required");return{isValid:!1,errorResult:_(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||hf().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=za.isAbsolute(r)?r:za.resolve(n,r),i=ff.validate(o);if(!i.isValid){let s=ke.pathValidationFailed(e.path,i.error),a=gf(e.path,i.error,n,o);return{isValid:!1,errorResult:_(s,e,{toolName:t,hintContext:{errorType:"permission",path:e.path,originalError:i.error},extra:{cwd:n,resolvedPath:o},customHints:a})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}import{validateCommand as Rf}from"octocode-security/commandValidator";import{spawn as Qa}from"child_process";var Gn=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],$n=[...Gn,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],ja=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],yf=10*1024*1024,Va=5e3;function Wa(e={},t=Gn){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 mt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Gn,maxOutputSize:a=yf}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},d=()=>l.stdoutChunks.join(""),u=()=>l.stderrChunks.join(""),m={cwd:o,env:Wa(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=Qa(e,t,m)}catch(g){c({stdout:"",stderr:"",exitCode:null,success:!1,error:g instanceof Error?g:new Error(`Failed to spawn command '${e}'`)});return}let f,h=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Va),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),R=()=>{clearTimeout(h),f!==void 0&&(clearTimeout(f),f=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}R(),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",g=>{if(l.killed)return;let C=g.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stdoutChunks.push(C)}),p.stderr?.on("data",g=>{if(l.killed)return;let C=g.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stderrChunks.push(C)}),p.on("close",g=>{l.killed||(R(),c({stdout:d(),stderr:u(),exitCode:g,success:g===0}))}),p.on("error",g=>{l.killed||(l.killed=!0,R(),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:g}))})})}function no(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Gn}=r,a;try{a=Qa(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Wa({},s)})}catch{o(!1);return}let c,l=()=>{clearTimeout(d),c!==void 0&&(clearTimeout(c),c=void 0)},d=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Va),o(!1)}},n);a.on("close",u=>{l(),i||o(u===0)}),a.on("error",()=>{l(),i||o(!1)})})}var Yx=1*1024*1024;function Bn(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}}async function _e(e,t=[],n={}){let r=Rf(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Bn(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}=n,l=await mt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(l.error)throw l.error;return{success:l.success,code:l.exitCode,stdout:l.stdout,stderr:l.stderr}}var Ka=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Ya=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Xa=[".dmg",".rar",".cpgz"],bf=[".aar",".yaa"];function ft(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function Sf(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},d={command:"7z",args:i},u={command:"7zz",args:i},m={command:"aa",args:s};return ft(bf,e)?[m]:ft(Xa,e)?[d,u,l,c,a]:ft(Ya,e)?[l,d,u,c,a]:ft(Ka,e)?[a,c,l,d,u]:[c,a,l,d,u]}function Cf(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 ft(Xa,e)?[s,a,o,r,n]:ft(Ya,e)?[o,s,a,r,n]:ft(Ka,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Za(e){let t=[];for(let n of e){let r=await _e(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 Pf(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
25
+ `).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
26
+ `)}async function Ja(e,t){let n=await Za(Sf(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?Pf(n.stdout,n.commandUsed):n.stdout).split(`
27
+ `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function qa(e,t){return Za(Cf(e,t))}var Ef={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"]}},Tf=[{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"}],wf={"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 _f(e){let t=e.toLowerCase();for(let{ext:n,format:r}of Tf)if(t.endsWith(n))return r}async function xf(e){let t=await _e("file",["--mime-type","-b",e]);if(t.success)return wf[t.stdout.trim().toLowerCase()]}async function Af(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 _e(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 _e(r.command,r.args)).stderr,commandUsed:r.command}}async function ec(e,t){let n;if(t!=="auto"?n=t:n=_f(e)??await xf(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=Ef[n],o=await Af(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`}}async function tc(e){let[t,n]=await Promise.all([_e("file",["-b",e]),_e("xxd",["-p","-l","32",e])]);if(!t.success&&!n.success)return{success:!1,error:"file and xxd both unavailable or failed"};let r=t.success?t.stdout.trim():void 0,o=n.success?n.stdout.replace(/\s+/g,"").trim():void 0,i=o?(o.match(/.{1,2}/g)??[]).join(" "):void 0;return{success:!0,fileType:r,magicBytes:i}}async function nc(e,t,n){let r=["-a"];n&&r.push("-t","x"),r.push("-n",String(t),e);let o=await _e("strings",r);if(!o.success)return{success:!1,error:o.stderr||"strings failed \u2014 is the binary installed?"};let i=o.stdout.split(`
28
+ `).map(a=>a.trim()).filter(Boolean);return i.length===0?{success:!0,strings:[],totalFound:0}:{success:!0,strings:[...i].sort((a,c)=>c.length-a.length),totalFound:i.length}}var Of=S.LOCAL_BINARY_INSPECT,kf=["file","xxd","strings","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],rc=!1;function vf(){if(!rc){try{If.addAllowedCommands(kf)}catch{}rc=!0}}var Ff=1e3,Mf=8,Nf=200;function oc(e,t,n){let r=e.split(`
29
+ `),o=new RegExp(t,"i"),i=new Set;for(let a=0;a<r.length;a++)if(o.test(r[a]??""))for(let c=Math.max(0,a-n);c<=Math.min(r.length-1,a+n);c++)i.add(c);let s=Array.from(i).sort((a,c)=>a-c).map(a=>r[a]??"");return s.length?s.join(`
30
+ `):null}function ic(e,t,n,r){let s=wt(e,t??0,n??r);return{content:s.paginatedContent,isPartial:s.hasMore,nextCharOffset:s.hasMore?s.nextCharOffset:void 0}}async function Hf(e,t){let n=await tc(e);return n.success?{status:"success",mode:"identify",path:e,fileType:n.fileType,magicBytes:n.magicBytes}:_(n.error??"identify failed",t)}async function Df(e,t){let n=t.verbose??!1,r=await Ja(e,n);if(!r.success){let m=r.missingCommands?.length?[`Install a missing backend: ${r.missingCommands.join(", ")}`]:[];return _(r.stderr||"All archive backends failed",t,{customHints:[...m,'Run mode="identify" first to confirm this is an archive.']})}let o=r.entries??[],i=Math.min(t.maxEntries??Ff,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,d=a?Math.ceil(s.length/a):1,u=a?c<d:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:d,hasMore:u,entriesPerPage:a,totalEntries:s.length}}}}async function Gf(e,t){let n=t.archiveFile,r=await qa(e,n);if(!r.success){let a=r.missingCommands?.length?[`Install a missing backend: ${r.missingCommands.join(", ")}`]:[];return _(r.stderr||"Extraction failed",t,{customHints:[...a,'Run mode="list" first \u2014 entry names are case-sensitive.']})}let o=r.stdout;if(!o)return _("Entry is empty",t);if(t.matchString){let a=oc(o,t.matchString,t.matchStringContextLines??3);if(!a)return _(`No lines match "${t.matchString}" in the extracted entry`,t);o=a}let i=$e(),s=ic(o,t.charOffset,t.charLength,i);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,content:s.content,contentLength:o.length,isPartial:s.isPartial,...s.nextCharOffset!==void 0&&{hints:[`charOffset=${s.nextCharOffset}`]}}}async function $f(e,t){let n=await ec(e,t.format??"auto");if(!n.success)return _(n.error??"Decompression failed",t,{customHints:['For multi-entry archives (.tar.gz, .zip etc.) use mode="list" or mode="extract".',"Set format explicitly: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse"]});let r=n.content??"";if(!r)return _("Decompressed file is empty",t);if(t.matchString){let s=oc(r,t.matchString,t.matchStringContextLines??3);if(!s)return _(`No lines match "${t.matchString}" in the decompressed content`,t);r=s}let o=$e(),i=ic(r,t.charOffset,t.charLength,o);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,content:i.content,contentLength:r.length,isPartial:i.isPartial,...i.nextCharOffset!==void 0&&{hints:[`charOffset=${i.nextCharOffset}`]}}}async function Bf(e,t){let n=t.minLength??Mf,r=t.includeOffsets??!1,o=await nc(e,n,r);if(!o.success)return _(o.error??"strings extraction failed",t,{customHints:['Ensure the "strings" CLI is installed (binutils on Linux, available via brew on macOS).']});let s=(o.strings??[]).slice(0,Nf);return{status:"success",mode:"strings",path:e,strings:s,totalFound:o.totalFound??0,returned:s.length}}async function sc(e){vf();let t=Re(e,Of);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await Lf.stat(n)).isFile())return _(`Path is not a regular file: ${n}`,e)}catch{return _(`File not found: ${n}`,e)}switch(e.mode){case"identify":return Hf(n,e);case"list":return Df(n,e);case"extract":return Gf(n,e);case"decompress":return $f(n,e);case"strings":return Bf(n,e);default:return _(`Unknown mode: ${String(e.mode)}`,e)}}async function ac(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Mn.safeParse(n);if(!r.success){let a=r.error.issues.map(c=>c.message).join("; ");return _(`Validation error: ${a}`,n)}let o=await sc(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 D(o,s),o}}),{toolName:S.LOCAL_BINARY_INSPECT,peerHints:!0},e)}import{getDirectorySizeBytes as Rh}from"octocode-shared";function ro(e){return e.data!==void 0&&!e.error}import{maskSensitiveData as cc}from"octocode-security/mask";var oo=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function Uf(){return Sr().provider??dn()}function zf(e){let t=Sr(),n=t.provider??dn(),{baseUrl:r,token:o}=t;try{let i=jr(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=cc(s);throw new oo(n,`Failed to initialize ${n} provider: ${a}`)}}function ve(e){let t;return()=>t??=zf(e)}function Un(e,t){return e.capabilities[t]}async function ot(e,t){let n=await t();return ro(n)?{ok:!0,response:n}:{ok:!1,result:Dn(n,e)}}async function lc(e,t){let n=t??Uf(),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:cc(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)ro(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}import{existsSync as lh}from"fs";import{join as uh}from"path";import{getOctocodeDir as dh}from"octocode-shared";import{existsSync as Zt,readFileSync as Qf,writeFileSync as jf,mkdirSync as Vf,rmSync as Xt,readdirSync as Wf,statSync as Kf}from"node:fs";import{join as Ue}from"node:path";import{createHash as Yf}from"node:crypto";import{getDirectorySizeBytes as Xf}from"octocode-shared";var Zf=1440*60*1e3,MA=600*1e3,Jf=2*1024*1024*1024,qf=50,dc=".octocode-clone-meta.json";function pc(e){return Ue(e,"repos")}function eh(e){return e?`__sp_${Yf("sha256").update(e).digest("hex").substring(0,6)}`:""}function zn(e,t,n,r,o){let i=`${r}${eh(o)}`;return Ue(pc(e),t,n,i)}function th(e){return typeof e=="object"&&e!==null}function nh(e){if(!th(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")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),t}function io(e){let t=Ue(e,dc);if(!Zt(t))return null;try{return nh(JSON.parse(Qf(t,"utf-8")))}catch{return null}}function Qn(e,t){try{jf(Ue(e,dc),JSON.stringify(t,null,2),"utf-8")}catch{}}function mc(e){return Date.now()<new Date(e.expiresAt).getTime()}function jn(e){let t=io(e);return t?mc(t)?Zt(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function rh(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Zf}function oh(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Jf}function ih(){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 qf}function Vn(e,t,n,r,o,i){let s=new Date;return{clonedAt:s.toISOString(),expiresAt:new Date(s.getTime()+rh()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{}}}function Wn(e){let t=Ue(e,"..");try{Zt(t)||Vf(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 so(e){try{Zt(e)&&Xt(e,{recursive:!0,force:!0})}catch{}}function Yt(e){try{return Kf(e).isDirectory()}catch{return!1}}function ht(e){try{return Wf(e)}catch{return[]}}function*fc(e){for(let t of ht(e)){let n=Ue(e,t);if(Yt(n))for(let r of ht(n)){let o=Ue(n,r);if(Yt(o))for(let i of ht(o)){let s=Ue(o,i);Yt(s)&&(yield s)}}}}function uc(e){for(let t of[...ht(e)]){let n=Ue(e,t);if(Yt(n)){for(let r of[...ht(n)]){let o=Ue(n,r);if(Yt(o)&&ht(o).length===0)try{Xt(o,{recursive:!0,force:!0})}catch{}}if(ht(n).length===0)try{Xt(n,{recursive:!0,force:!0})}catch{}}}}function sh(e){let t=0;for(let n of fc(e))try{let r=io(n);(!r||!mc(r))&&(Xt(n,{recursive:!0,force:!0}),t++)}catch{}return t}function ah(e){let t=[];for(let n of fc(e)){let r=io(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??Xf(n)})}return t}function ch(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{Xt(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Kn(e){let t=pc(e);if(!Zt(t))return 0;let n=0;try{n+=sh(t)}catch{return n}uc(t);let r=ch(ah(t),oh(),ih());return n+=r,r>0&&uc(t),n}var hc=120*1e3,ph=30*1e3,gc=[...$n,"GIT_TERMINAL_PROMPT"];async function yc(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await gh();let a=e.branch??await Oe(r,o,t),c=dh(),l=zn(c,r,o,a,i),d=jn(l);if(!s&&d.hit&&d.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Kn(c),so(l),Wn(l);let u=hh(t,n);if(i){if(await fh(r,o,a,l,i,u),!lh(uh(l,i)))throw so(l),new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the directory path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await mh(r,o,a,l,u);let m=Vn(r,o,a,"clone",i);return Qn(l,m),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}async function mh(e,t,n,r,o){let i=bc(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Rc(e,t),r),await ao(i,hc,`full clone of ${e}/${t}`,o)}async function fh(e,t,n,r,o,i){let s=bc(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Rc(e,t),r),await ao(s,hc,`sparse clone of ${e}/${t}`,i),await ao(["-C",r,"sparse-checkout","set","--",o],ph,`sparse-checkout set ${o}`,void 0)}function Rc(e,t){return`https://github.com/${e}/${t}.git`}function bc(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function hh(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function gh(){try{if(!(await mt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:gc,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 yh(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 ao(e,t,n,r){let o=await mt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:gc,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=yh(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var bh="Served from 24-hour cache.",Sh=["Verify the owner/repo (and branch) exist \u2014 use ghSearchRepos to confirm the repository name.","For private repositories, ensure the GitHub token is set and has repo read access."];async function Sc(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>we({toolName:S.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Un(s,"cloneRepo"))return he(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",S.GITHUB_CLONE_REPO);let a;try{a=await yc(o,n,s.token)}catch(d){let u=d instanceof Error?d.message:String(d);return _(`Clone failed for ${o.owner}/${o.repo}: ${u}`,o,{customHints:Sh})}let c={owner:o.owner,repo:o.repo,localPath:a.localPath,...a.cached?{cached:!0}:{},...o.branch!==a.branch?{resolvedBranch:a.branch}:{}},l=[];return a.cached&&l.push(bh),l.push(`Use localViewStructure with path="${a.localPath}" to explore, then localGetFileContent to read files.`),ye(o,c,!0,S.GITHUB_CLONE_REPO,{extraHints:l,rawResponse:Rh(a.localPath)})}}),{toolName:S.GITHUB_CLONE_REPO,keysPriority:["resolvedBranch","localPath","cached","error"],peerHints:!0},e)}import{writeFileSync as Ch,mkdirSync as Cc,existsSync as Yn,rmSync as Ph,readdirSync as Eh,statSync as Th}from"node:fs";import{join as co,dirname as wh,resolve as Pc,sep as Ec}from"node:path";import{getOctocodeDir as _h}from"octocode-shared";var xh=50,Ah=5*1024*1024,Lh=300*1024,Ih=5,Oh=1e4,kh=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"]);async function wc(e,t,n,r,o,i=!1){let s=_h(),a=zn(s,e,t,r),c=Pc(co(a,n));if(!c.startsWith(a+Ec)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=jn(a);if(l.hit){if(l.meta.source==="clone"){if(Yn(c)){let E=Tc(c,a);return{localPath:c,files:E.files,fileCount:E.fileCount,totalSize:E.totalSize,cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}throw new Error(`Path "${n}" not found in the cloned repository (${e}/${t}@${r}). To refresh the clone, use ghCloneRepo with forceRefresh: true.`)}if(!i&&Yn(c)){let E=Tc(c,a);return{localPath:c,files:E.files,fileCount:E.fileCount,totalSize:E.totalSize,cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}}let d=await ne(o),{data:u}=await d.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(u))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let m=u.filter(C=>{if(C.type!=="file"||!C.download_url||C.size>Lh)return!1;let E=Nh(C.name);return!kh.has(E)}).slice(0,xh),p=o?.token,f=await vh(m,Ih,p),h=0,R=[];for(let{entry:C,content:E}of f){if(h+E.length>Ah)break;h+=E.length,R.push({entry:C,content:E})}Kn(s),Wn(a),Yn(c)&&Ph(c,{recursive:!0,force:!0}),Cc(c,{recursive:!0,mode:448});let b=[];for(let{entry:C,content:E}of R){let L=Pc(co(a,C.path));if(!L.startsWith(a+Ec))continue;let I=wh(L);Yn(I)||Cc(I,{recursive:!0,mode:448}),Ch(L,E,"utf-8"),b.push({path:C.path,size:E.length,type:"file"})}let g=Vn(e,t,r,"directoryFetch");return Qn(a,g),{localPath:c,files:b,fileCount:b.length,totalSize:h,cached:!1,expiresAt:g.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function vh(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 Mh(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var Fh=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function Mh(e,t){try{let o=new URL(e);if(!Fh.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(),Oh);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 Tc(e,t){let n=[],r=0;function o(i){let s;try{s=Eh(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=co(i,a);try{let l=Th(c);if(l.isDirectory())o(c);else if(l.isFile()){let d=c.substring(t.length+1);r+=l.size,n.push({path:d,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function Nh(e){let t=e.lastIndexOf(".");return t===-1?"":e.substring(t).toLowerCase()}function _c(e,t){return e&&t?`${e}/${t}`:void 0}function Lt(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,l=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${l} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function xc(e){return{keywords:e.keywords??[],projectId:_c(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 Ac(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 Hh(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Lc(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}=Hh(a),d=`${c}/${l}`,u=s,m=o.get(d);if(m||(m={id:d,owner:c,repo:l,matches:[]},o.set(d,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&u.url?{url:u.url}:{}});continue}let p=!0,f=!1;for(let h of s.matches){if(!h.context)continue;let R={path:s.path,value:h.context};h.positions?.length>0&&(R.matchIndices=h.positions.map(([b,g])=>({start:b,end:g,lineOffset:(h.context??"").substring(0,b).split(`
31
+ `).length-1}))),r&&p&&u.url&&(R.url=u.url,p=!1),m.matches.push(R),f=!0}f||m.matches.push({path:s.path,pathOnly:!0,...r&&u.url?{url:u.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!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,...Ac(e.pagination),hasMore:e.pagination.hasMore}),i}function Ic(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 Oc(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function Dh(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function kc(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Dh),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:_c(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,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 Gh(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function $h(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 Bh(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:$h(e)}}function vc(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=Gh(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=Bh(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(d=>({...d,...d.bodyPagination&&{bodyPagination:d.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}:{},...Ac(e.pagination),hasMore:e.pagination.hasMore}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function Fc(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,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 Mc(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 Nc(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??dt.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 Hc(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([u],[m])=>u==="."?-1:m==="."?1:u.localeCompare(m)).map(([u,m])=>({dir:u,files:m.files,folders:m.folders})),c=e.fileSizeMap,l={};if(c){for(let[u,m]of Object.entries(c))if(n[u]){let p=new Set(n[u].files);for(let[f,h]of Object.entries(m))p.has(f)&&(l[f]=h)}}let d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.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}function gt(e){let t=new Set,n=[];for(let r of e)typeof r=="string"&&r.trim().length>0&&!t.has(r)&&(t.add(r),n.push(r));return n}function Uh(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function Xn(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=Uh(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r,s=Array.isArray(n.data.hints)?n.data.hints.filter(a=>typeof a=="string"&&a.trim().length>0):void 0;t.push({id:n.id,error:i,...s&&s.length>0?{hints:s}:{}})}return t}function Zn(e,t,n){let r=Hn(e,[...t]);return{structuredContent:nt(e),text:r,isError:n}}function Gc(e){return typeof e=="object"&&e!==null}function Ve(e){return typeof e=="string"&&e.length>0?e:void 0}function ze(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function zh(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function Qh(e){return gt(e.flatMap(t=>{let n=t.data.hints;return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}))}var jh=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function Vh(e){if(!Gc(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 jh){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Wh(e,t){return`${e}/${t}`}function Kh(e,t,n){let r=Wh(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 Yh(e,t){return{path:Ve(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",...ze(e.fileSize)!==void 0?{fileSize:ze(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:ze(e.totalLines),sourceChars:ze(e.sourceChars),sourceBytes:ze(e.sourceBytes),resolvedBranch:Ve(e.resolvedBranch),pagination:Vh(e.pagination),...e.isPartial===!0?{isPartial:!0}:{},startLine:ze(e.startLine),endLine:ze(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:Ve(e.lastModified),lastModifiedBy:Ve(e.lastModifiedBy),warnings:zh(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Ve(e.searchedFor)}}function Dc(e,t){let n=t.pagination,r=n?.charOffset??0,o=n?.charLength??0,i=r+o,s=n?.currentPage&&n.totalPages?`Page ${n.currentPage}/${n.totalPages}`:"Content page",a=typeof n?.totalChars=="number"&&o>0?` (chars ${r+1}-${i} of ${n.totalChars})`:"";return`${s}${a}. Next: charOffset=${i} for ${e}:${t.path}`}function Xh(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Gc).map(o=>({path:Ve(o.path)??"",size:ze(o.size)??0,type:Ve(o.type)??"file"}));return{path:String(t.path??""),localPath:Ve(e.localPath)??"",fileCount:ze(e.fileCount)??r.length,totalSize:ze(e.totalSize)??0,...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Ve(e.resolvedBranch)}}function Zh(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=Kh(n,s,a),l=r.data;if(i.type==="directory"){let u=c.directories??[];u.push(Xh(l,i)),c.directories=u;return}let d=c.files??[];d.push(Yh(l,i)),c.files=d}),Array.from(n.values())}function Jh(e){let t=[];for(let n of e){for(let r of n.files??[]){if(r.pagination?.hasMore&&typeof r.pagination.charOffset=="number"){let o=r.pagination.charLength??0,i=r.pagination.charOffset+o,s=r.pagination.nextBlockChar;if(typeof s=="number"){let a=s-i;t.push(`${Dc(n.id,r)}. Page cut mid-block at char ${i}. Next top-level definition starts at char ${s}. Re-request with charLength=${o+a} to extend this page to the next boundary, or use charOffset=${i} to continue page-by-page.`)}else t.push(Dc(n.id,r))}r.isPartial&&!r.matchRanges?.length&&typeof r.endLine=="number"&&typeof r.totalLines=="number"&&r.endLine<r.totalLines&&t.push(`File content is partial (lines ${r.startLine??1}\u2013${r.endLine} of ${r.totalLines}). Use startLine=${r.endLine+1} to read the next section of ${n.id}:${r.path}.`)}for(let r of n.directories??[])r.cached&&t.push(`Directory ${n.id}:${r.path} served from cache.`)}return gt(t)}function qh(e,t){let n=e.toLowerCase();if(t===404||n.includes("not found")||n.includes("404"))return["Verify owner/repo/path/branch.","Use ghViewRepoStructure to confirm the path."];if(t===403||n.includes("forbidden")||n.includes("403"))return["Check token permissions or repository visibility."];if(t===429||n.includes("rate limit"))return["Retry after reset or authenticate with a higher-limit token."]}function eg(e,t){return Xn(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error,hints:qh(r.error)}})}function $c(){return({queries:e,results:t,config:n})=>{let r=Zh(t,e),o=eg(t,e),i=gt([...n.peerHints?Qh(t):[],...Jh(r)]),s={results:r};return i.length>0&&(s.hints=i),o&&o.length>0&&(s.errors=o),Zn(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","hints","errors"],r.length===0&&!!(o&&o.length>0))}}async function Bc(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{let s=An.safeParse(o);if(!s.success){let l=s.error.issues.map(d=>d.message).join("; ");return _(l,o)}let a=s.data,c=r();return a.type==="directory"?tg(a,n,c):ng(a,c)}catch(s){return he(s,o)}},{toolName:S.GITHUB_FETCH_CONTENT,peerHints:!0,finalize:$c()},e)}async function tg(e,t,n){if(!un())return he(new Error("Directory fetch requires ENABLE_LOCAL=true and ENABLE_CLONE=true. Directory mode saves files to disk using the same cache as ghCloneRepo."),e,"Clone not enabled",S.GITHUB_FETCH_CONTENT);if(!Un(n,"fetchDirectoryToDisk"))return he(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",S.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return _("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Oe(e.owner,e.repo,t),o=await wc(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i={localPath:o.localPath,fileCount:o.fileCount,totalSize:o.totalSize,files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{}};return ye(e,i,!0,S.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??$(o)})}async function ng(e,t){let n=await ot(e,()=>t.provider.getFileContent(Fc(e)));if(n.ok===!1)return n.result;let r=n.response.hints,o={...Mc(n.response.data,e),...r?.length?{hints:r}:{}},i=!!(n.response.data.matchNotFound===!0||n.response.data.content&&n.response.data.content.length>0);return ye(e,o,i,S.GITHUB_FETCH_CONTENT,{rawResponse:n.response.rawResponseChars,hintContext:{path:e.path,branch:e.branch,isPartial:n.response.data.isPartial,endLine:n.response.data.endLine}})}function rg(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{}}}function og(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 ig(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function sg(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,{id:`${n.owner}/${n.repo}:${r.path}`,owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function ag(e,t,n){return t.length===0?[]:[{id:e.length===1&&typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",data:{files:sg(t),...n?{pagination:n}:{}}}]}function cg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lg(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${cg(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function ug(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?ig(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:lg(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:dg(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 dg(e,t){return{...e,matches:t}}function pg(e){return gt(e.flatMap(t=>{let n=t.data.hints;return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}))}function mg(e){return e.some(t=>t.matches.some(n=>n.pathOnly))}function Uc(){return({queries:e,results:t,config:n})=>{let r=[],o,i=0,s=[];t.forEach((b,g)=>{if(b.status==="error")return;let C=rg(b);if(C.results.reduce((I,k)=>I+k.matches.length,0)===0){let I=b.data.hints,k=Array.isArray(I)?I.filter(j=>typeof j=="string"&&j.trim().length>0):[];s.push({id:b.id,hints:k,...C.nonExistentScope?{nonExistentScope:!0}:{}})}let L=C.results;r.push({id:b.id,groups:L}),C.pagination&&(o=C.pagination,i+=1)});let a=Array.from(new Set(e.flatMap(b=>{let g=b.keywords;return Array.isArray(g)?g.filter(C=>typeof C=="string"):[]}))),c=ug(og(r),a),l=o&&i===1?Lt(o,"matches"):[],d=Xn(t),u=mg(c)?['Some match="file" results are path-only because GitHub did not return text matches; use ghGetFileContent with matchString or startLine/endLine to inspect content.']:[],m=gt([...n.peerHints?pg(t):[],...l,...u]),p=o&&i===1?o:void 0,f=e.some(b=>b.concise===!0),h=ag(e,c,p);if(f)for(let b of h)b.data.files=b.data.files.map(g=>`${g.owner}/${g.repo}:${g.path}`);let R={results:h};if(m.length>0&&(R.hints=m),s.length>0){let b=new Set(m);R.emptyQueries=s.map(({id:g,hints:C,nonExistentScope:E})=>{let L=C.filter(I=>!b.has(I));return{id:g,...L.length>0?{hints:L}:{},...E?{nonExistentScope:E}:{}}})}return d.length>0&&(R.errors=d),Zn(R,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","hints","emptyQueries","errors"],c.length===0&&d.length>0)}}function fg(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function hg(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search.",hints:['Use owner="<org-or-user>" with repo="<repository>" \u2014 GitHub code search cannot scope to a bare repository name.','If you only know the repo name, first use ghSearchRepos with keywords=["<repo>"] to find its owner.']}}async function zc(e){let{queries:t}=e,n=ve(e.authInfo);return X(t,async(r,o)=>{try{let i=hg(r);if(i)return _(i.error,r,{customHints:i.hints});if(!fg(r))return _("At least one search term or scope filter is required.",r);let s=n(),a=await ot(r,()=>s.provider.searchCode(xc(r)));if(a.ok===!1)return a.result;let c=Lc(a.response.data,r),l={hasOwnerRepo:!!(r.owner&&r.repo),owner:r.owner,repo:r.repo,nonExistentScope:c.nonExistentScope,match:r.match,extension:r.extension,filename:r.filename,path:r.path,keywords:r.keywords,totalMatches:c.pagination?.totalMatches,hasMore:c.pagination?.hasMore,currentPage:c.pagination?.currentPage??1,totalPages:c.pagination?.totalPages??1,matchedPaths:c.results.flatMap(p=>p.matches.map(f=>f.path))},d=new Set(c.results.flatMap(p=>p.matches.map(f=>`${p.owner}/${p.repo}:${f.path}`))).size,u=[];if(c.results.length>0){let p=Array.isArray(r.keywords)&&typeof r.keywords[0]=="string"?r.keywords[0]:"<keyword>";u.push(`Found matches in ${d} file${d===1?"":"s"} \u2014 matchIndices[].lineOffset is the 0-based line within the snippet; use ghGetFileContent(path, matchString="${p}") to land on the matched region (returns lineHint for lspGetSemantics).`)}if(c.pagination){let{totalPages:p,perPage:f,totalMatches:h,reportedTotalMatches:R,reachableTotalMatches:b}=c.pagination,g=R??h,C=b??Math.min(h,p*f);g>C&&u.push(`GitHub caps code-search at ${C} results \u2014 ${g-C} of ${g} reported matches are unreachable; narrow with path/extension/filename to see the rest.`)}if(typeof r.path=="string"&&!r.filename&&/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/.test(r.path)){let p=r.path.match(/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/),f=p?p[1]:r.path;u.push(`path="${r.path}" looks like a file path \u2014 auto-extracted filename="${f}" for the query. Use explicit filename="${f}" + path="<dir>" for clarity.`)}return ye(r,c,c.results.length>0,S.GITHUB_SEARCH_CODE,{hintContext:l,rawResponse:a.response.rawResponseChars,extraHints:u})}catch(i){return he(i,r)}},{toolName:S.GITHUB_SEARCH_CODE,peerHints:!0,finalize:Uc()},e)}function gg(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 yg(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 Rg(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Qc(e){let{content:t,reviewMode:n}=e,r=gg(t,n),o=yg(t,n),i=Rg(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}:{}}}function jc(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function po(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function qn(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function mo(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 tr(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 Wc(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Kc(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function bg(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function er(e,t,n){return bg({...Kc(e,t),...n})}function Vc(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return er(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function lo(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return er(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Sg(e,t,n){return{target:Kc(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 Jn(e){return String(e.path??e.filename??"")}function Cg(e,t){return{path:Jn(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function Pg(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 Eg(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=Pg(r,n.comments),i=po(t),s=i?o.filter(l=>qn(l.body,i)):o,{items:a,pagination:c}=mo(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let d=tr(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}:{},...d?{body:d.content,bodyPagination:d.pagination}:{bodyPreview:Wc(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function Tg(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=po(t);return{reviews:(o?r.filter(s=>qn(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=tr(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 wg(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=mo(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 _g(e){return e.split(`
32
+ `).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(`
33
+ `)}function xg(e){return e.replace(/\n{3,}/g,`
34
+
35
+ `)}function Ag(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(Jn(p))):o,a=po(t),c=a?s.filter(p=>qn(Jn(p),a)||qn(p.patch,a)):s,{items:l,pagination:d}=mo(c,t.filePage??t.page??1,t.itemsPerPage??20),u=n.patches.mode!=="none",m=l.map(p=>{let f=Cg(p,!1);if(!u||typeof p.patch!="string")return f;let h=r&&!a?_g(p.patch):p.patch,R=tr(h,t.charOffset??0,t.charLength??12e3);return{...f,patch:R?.content??"",...R?{patchPagination:R.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:d}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(Jn).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function it(e){return typeof e=="object"&&e!==null}function uo(e){if(it(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function fo(e){if(it(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function Lg(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function Ig(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!it(n))continue;let r=fo(n.patchPagination);if(r?.hasMore)return r}}function Og(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!it(n))continue;let r=fo(n.bodyPagination);if(r?.hasMore)return r}}function kg(e,t,n,r){let o={},i=fo(e.bodyPagination),s=uo(e.filePagination),a=uo(e.commentPagination),c=uo(e.commitPagination),l=Ig(e),d=Og(e),u=Lg(n);i&&(o.body={...i,nextQuery:Vc(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:lo(t,r,u,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:lo(t,r,{comments:n.comments},"commentPage",a)}),d?.hasMore&&d.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...d,nextQuery:er(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:d.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:lo(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Vc(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return it(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?er(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function vg(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Yc(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?xg(s):s,c=n.body?tr(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,d=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,f={...{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:Wc(typeof e.body=="string"?e.body:void 0)}:{},...d?{next:Sg(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...Ag(e,t,n,r),...Eg(e,t,n),...Tg(e,t,n),...wg(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},h=kg(f,t,n,i);return vg(f),h&&(f.contentPagination=h),f}function Xc(e,t){let n=e[0];if(!n)return[];let r=["PR response includes a `next` map \u2014 re-call with next.target + one content key (e.g. next.getBody, next.getAllPatches, next.getComments) to fetch a surface."],o=it(n.contentPagination)?n.contentPagination:{},i={body:{label:"body charOffset",field:"charOffset"},changedFiles:{label:"changedFiles filePage",field:"filePage"},comments:{label:"comments commentPage",field:"commentPage"},commentBody:{label:"comment body commentBodyOffset",field:"commentBodyOffset"},commits:{label:"commits commitPage",field:"commitPage"},patches:{label:"patches charOffset",field:"charOffset"},filePaths:{label:"file paths filePage",field:"filePage"}};for(let[s,{label:a,field:c}]of Object.entries(i)){let l=o[s];if(!it(l)||l.hasMore!==!0)continue;let u=(it(l.nextQuery)?l.nextQuery:{})[c];typeof u=="number"&&r.push(`More PR ${a}=${u}.`)}return t.patches.mode==="none"&&r.push('Patches not included \u2014 request content.patches={mode:"all"} or {mode:"selected",files:[...]}.'),t.comments||r.push("Comments not included \u2014 request content.comments={discussion:true,reviewInline:true}."),r}function Fg(e){return e?e.includes('rel="next"'):!1}function Zc(e,t){if(e)return!t||e.length<=t?e:e.slice(0,t)}async function Jc(e,t){try{let n=await ne(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=Fg(i),a=o.data.map(d=>{let u=d.commit.author,m=d.commit.committer,p=m?.date??u?.date??"",f=d.commit.message,h=f.split(`
36
+ `)[0]??f;return{sha:d.sha,date:p,message:f,messageHeadline:h,url:d.html_url,author:{name:u?.name??"unknown",email:u?.email??"",...d.author?.login?{login:d.author.login}:{}},...m?{committer:{name:m.name??"unknown",email:m.email??"",...d.committer?.login?{login:d.committer.login}:{}}}:{}}}),c={page: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(d,u)=>{try{let m=o.data[u]?.sha??d.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let f=e.path,h=p.data.files?.find(R=>R.filename===f||R.previous_filename===f);if(h)return{...d,additions:h.additions,deletions:h.deletions,status:h.status,...h.patch!==void 0?{patch:Zc(h.patch,e.charLength)}:{},...h.previous_filename?{previousFilename:h.previous_filename}:{}}}else{let f=e.path,h=(p.data.files??[]).filter(R=>!f||R.filename.startsWith(f)).map(R=>({filename:R.filename,status:R.status,additions:R.additions,deletions:R.deletions,...R.patch!==void 0?{patch:Zc(R.patch,e.charLength)}:{},...R.previous_filename?{previousFilename:R.previous_filename}:{}}));return{...d,files:h}}}catch{}return d}));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 Z(n)}}async function qc(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{let s=Ln.safeParse(o);if(!s.success){let O=s.error.issues.map(K=>K.message).join("; ");return _(`Validation error: ${O}`,o)}if(s.data.type==="commits"){let O=s.data;if(!O.owner||!O.repo)return _("owner and repo are required for commits mode.",o);let K=O.path,pe=K&&!K.endsWith("/")?"file":"repo";if(pe==="file"&&!K)return _("path is required when querying a specific file in commits mode.",o);let Se=await Jc({type:pe,owner:O.owner,repo:O.repo,path:K,branch:O.branch,since:O.since,until:O.until,author:O.author,page:Number(O.page)||1,perPage:Number(O.perPage)||30,includeDiff:!!O.includeDiff,charLength:typeof O.charLength=="number"?O.charLength:void 0},n);if(Tt(Se)){let cn=Se.status===429||Se.error?.toString().toLowerCase().includes("rate limit")||!1;return _(Se,o,{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,hintContext:{type:"commits",path:K,isRateLimited:cn,status:Se.status,retryAfter:Se.retryAfter},hintSourceError:Se})}let{commits:De,pagination:vt}=Se.data,Vo=De.length>0,hr=[];vt.hasMore&&vt.nextPage&&hr.push(`${De.length} commit${De.length===1?"":"s"} returned \u2014 re-call with page:${vt.nextPage} for more.`);let Wo=/#(\d+)/;if(Vo){let cn=De.find(ln=>{let Ft=ln.messageHeadline;return typeof Ft=="string"&&Wo.test(Ft)});if(cn){let ln=cn.messageHeadline,Ft=Wo.exec(ln);Ft&&hr.push(`Merge commits embed PR refs \u2014 e.g. "${ln}" \u2192 use ghHistoryResearch(owner:"${O.owner}", repo:"${O.repo}", prNumber:${Ft[1]}) to read that PR's body, diffs, comments, and reviews.`)}}return ye(o,Se.data,Vo,S.GITHUB_SEARCH_PULL_REQUESTS,{hintContext:{type:"commits",path:K,matchCount:De.length,hasMorePages:vt.hasMore},extraHints:hr,rawResponse:Se.rawResponseChars})}let a=r(),c={...s.data},l=Qc(c),d=[],u=c.prNumber!==void 0;!u&&jc(l)&&d.push('Broad PR search returns metadata only. Re-call with prNumber and content selectors (body, changedFiles, patches, comments, commits) or reviewMode="full" to fetch PR content.'),u||(c.content=void 0,c.reviewMode=void 0);let m=!u&&((c.keywordsToSearch?.length??0)>0||!!c.query);if(m&&!c.created&&(c.state==="merged"||c.merged===!0)&&!c.sort&&!c.order?d.push(`To find the PR that first introduced a feature: sort:"created" order:"asc". Use match:["title"] for title-only and query:'"exact phrase"' for phrase matching.`):m&&!c.created&&!c.sort&&!c.order&&d.push('Archaeology tip: add state:"merged" sort:"created" order:"asc" to find the oldest matching merged PR. Use match:["title"] for title-only matching.'),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return _("At least one valid search parameter, filter, or PR number is required.",o);let h=await ot(c,()=>a.provider.searchPullRequests(kc(c)));if(h.ok===!1)return h.result;let R=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:b,resultData:g,pagination:C}=vc(h.response.data,{includeFileChanges:R}),E=c.prNumber!==void 0?void 0:C;c.prNumber!==void 0&&delete g.pagination;let L=!u&&(!!o.content||!!o.reviewMode),I={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},k=c.minify==="standard",j=u,P=b.map(O=>Yc(O,c,L?I:l,k,j));g.pull_requests=P,!u&&c.concise===!0&&(g.pull_requests=P.map(O=>{let K=O;return`#${K.number} ${K.title}`}));let x=P.length>0,A=E?Lt({currentPage:E.currentPage,totalPages:E.totalPages,hasMore:E.hasMore,totalMatches:E.totalMatches,entriesPerPage:E.perPage},"PRs"):[],B=x?[`Found ${P.length} PR${P.length===1?"":"s"}.`,...j?Xc(P,l):[]]:[],N=[],M=b.filter(O=>(typeof O.changedFilesCount=="number"?O.changedFilesCount:Array.isArray(O.fileChanges)?O.fileChanges.length:0)>30);if(M.length>0){let O=M.map(pe=>`#${pe.number}`).join(", "),K=Math.max(...M.map(pe=>typeof pe.changedFilesCount=="number"?pe.changedFilesCount:Array.isArray(pe.fileChanges)?pe.fileChanges.length:0));N.push(`Large PR(s) ${O} have ${K}+ file changes.`)}let oe=l.body||l.changedFiles||l.patches.mode!=="none"||!!l.comments||l.reviews||!!l.commits;!R&&!(u&&oe)&&b.filter(K=>typeof K.changedFilesCount=="number"&&K.changedFilesCount>0).length>0&&N.push('Metadata mode: changedFiles details omitted (changedFilesCount available). Re-call with prNumber + content.changedFiles=true for file paths, content.patches={mode:"selected",files:["src/foo.ts"]} for targeted diffs, or reviewMode="full" for all content in one call.');let ce=u&&typeof c.matchString=="string"&&c.matchString.trim()?[`matchString filter active \u2014 pagination totals count only items matching "${c.matchString.trim()}"; drop matchString for the full set.`]:[],Q=Mg({data:g,pullRequests:b,extraHints:[...B,...A,...d,...N,...ce]},c);return ye(c,Q.data,x,S.GITHUB_SEARCH_PULL_REQUESTS,{hintContext:{matchCount:P.length,state:c.state,owner:c.owner,repo:c.repo,author:c.author,keywords:c.keywordsToSearch,prNumber:c.prNumber,prMatch:c.match},extraHints:Q.extraHints,rawResponse:h.response.rawResponseChars})}catch(s){return he(s,o)}},{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"],peerHints:!0},e)}function Mg(e,t){return{data:e.data,extraHints:e.extraHints}}function el(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}function Ng(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 Hg(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(Ng)},extraHints:n?["Minimal owner/repo list \u2014 re-run without concise (or ghViewRepoStructure) to dive into a chosen repo."]:[]}}function go(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function yo(e){return!!(e.keywords&&e.keywords.length>0)}function Dg(e){return!!(yo(e)||go(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 tl(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Gg(e){let t=go(e),n=yo(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:tl(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:tl(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function $g(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 Bg(e,t){return[...e].sort((n,r)=>{let o=Ug(n,r,t.sort);if(o!==0)return o;let i=nl(r,t)-nl(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:ho(n).localeCompare(ho(r))})}function Ug(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 el(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function nl(e,t){let n=zg(t),r=ho(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(d=>d.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((d,u)=>o===u||r===u?d+80:o.includes(u)||r.includes(u)?d+40:s.includes(u)?d+35:i.includes(u)?d+10:d,0)+(c&&a===c?20:0)}function zg(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function ho(e){return`${e.owner}/${e.repo}`}function Qg(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore}}function jg(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function Vg(e){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages} for merged topic+keyword results (~${e.totalMatches??0} upper-bound total). Next: page=${e.currentPage+1}.`]:[]}function rl(e){return e.flatMap(t=>{let n=t.label==="topics"?"Topic search":t.label==="keywords"?"Keyword search":"Search",r=t.response.error||"Provider error";return`${n} failed: ${r}`})}function Wg(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??$(n.response.data??n.response)),0)}var Kg=100;function Yg(e,t,n=!1,r=0){if(t)return n&&r>Kg&&!e.owner&&!e.language&&!e.stars?['Large result set with no owner/language/stars filter \u2014 add owner="<org>" to scope to a specific org, language="<lang>" to restrict by language, or stars=">100" to surface established repos.']:void 0;let o=go(e),i=yo(e),s=typeof e.stars=="string"?e.stars:void 0,a=typeof e.created=="string"?e.created:void 0,c=typeof e.updated=="string"?e.updated:void 0,l=[];o&&i?l.push("No match for topics AND keywords. Drop topics, then keywords."):o?l.push("No topic match. Drop one, try synonyms, or use keywords."):i&&l.push("No keyword match. Drop the rarest, try synonyms, or use topics.");let d=[];if(s&&d.push(`stars="${s}"`),a&&d.push(`created="${a}"`),c&&d.push(`updated="${c}"`),d.length>0&&l.push(`Filters (${d.join(", ")}) \u2014 try widening/removing.`),l.length!==0)return l}async function ol(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{if(!Dg(o))return _("At least one repository search term or filter is required.",o);let s=r(),a=Gg(o),{successes:c,failures:l}=await lc(a.map(O=>({meta:{label:O.label,query:O.query},operation:()=>s.provider.searchRepos(Ic(O.query))}))),d=c.map(O=>({label:O.meta.label,query:O.meta.query,response:O.response})),u=l.map(O=>({label:O.meta.label,query:O.meta.query,response:O.response}));if(d.length===0){let O=u[0];return O?Dn(O.response,o):he(new Error("Repository search produced no provider results"),o)}let m=o.limit,p=Bg($g(d.flatMap(O=>Oc(O.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,h=d.some(O=>O.response.data.nonExistentScope),R=f.length===0&&h?[`Owner "${o.owner??"?"}" doesn't exist or isn't searchable \u2014 verify spelling/access, not filters.`]:[],b=d.length===1?d[0]:void 0,g=d.length>1,C=g?jg(d):b?.response.data.pagination,E=C?g?Vg(C):Lt(C,"repos"):[],L=C?Qg(C):void 0,I=o.page,k=C?.totalPages??0,j=typeof I=="number"&&k>0&&I>k&&f.length===0,P=j?[`page ${I} exceeds totalPages ${k} \u2014 last page is ${k}.`]:[],x=f.length>0,A=!!C?.hasMore,B=C?.totalMatches??C?.reachableTotalMatches??0,N=j?void 0:Yg(o,x,A,B),M=a.length>1&&d.length===1?[`Only ${b?.label??"one"} search succeeded; pagination reflects that subset.`,...rl(u)]:rl(u),oe=Hg({repositories:f,pagination:L},o),ae=[];if(x){let O=f[0];O?.owner&&O?.repo&&ae.push(`Top result: ${O.owner}/${O.repo} \u2014 use ghViewRepoStructure to browse or ghSearchCode to search within it.`),f.length>=3&&ae.push("Use multiple ghViewRepoStructure queries in parallel to compare the layouts of top results.")}let Q=[...P,...R,...oe.extraHints,...M,...E,...N||[],...ae];return ye(o,oe.data,x,S.GITHUB_SEARCH_REPOSITORIES,{extraHints:Q,hintContext:j?{}:{keywords:o.keywords,owner:o.owner,language:o.language,topic:o.topicsToSearch?.[0]},rawResponse:Wg([...d,...u])})}catch(s){return he(s,o)}},{toolName:S.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"],peerHints:!0},e)}var Xg=5;function Zg(e){if(!e||typeof e!="object")return[];let t=[],n=[];for(let r of Object.values(e)){let o=r;if(Array.isArray(o.folders))for(let i of o.folders)typeof i=="string"&&t.push(`${i}/`);if(Array.isArray(o.files))for(let i of o.files)typeof i=="string"&&n.push(i)}return[...t,...n]}function Jg(e,t){return Zg(e).slice(0,t)}function qg(e){return!e.owner||!e.repo?void 0:`${e.truncated||e.hasMore?"Structure page is partial":"Structure complete"} - use ghSearchCode(owner="${e.owner}", repo="${e.repo}") to find patterns, or ghGetFileContent to read specific files.`}function ey(e,t,n){if(!n)return[];let r=Jg(e,Xg);if(r.length===0)return[];let o=t>r.length?` (+${t-r.length} more)`:"";return[`Next paths: ${r.join(", ")}${o}`]}function ty(e){let t=e.currentPage??1,n=e.totalPages??t+1,r=e.totalEntries,o=e.entriesPerPage,i=typeof r=="number"&&typeof o=="number"?` (showing ${Math.min(t*o,r)} of ${r})`:"";return`Page ${t}/${n}${i}. Next: page=${t+1}`}function ny(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}:{},...Array.isArray(e.hints)?{hints:e.hints}:{}}}function ry(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Ut(o))continue;let i=r.files.filter(a=>!Pt(a)),s=r.folders.filter(a=>!Ut(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function il(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await ot(o,()=>s.provider.getRepoStructure(Nc(o,c)));if(l.ok===!1)return ny(l.result,o);let d=Object.keys(l.response.data.structure??{}).length>0,u=ry(l.response.data.structure),m=Object.keys(u).length>0,p=d&&!m,f=!!l.response.data.summary?.truncated,h=Hc(l.response.data,o,u,c),R="branchFallback"in h?h.branchFallback:void 0,b=l.response.data.hints||[],g=R?[`WARNING: Branch '${String(R.requestedBranch)}' not found. Showing '${String(R.actualBranch)}' (default branch). Re-query with the correct branch name if branch-specific results are required.`]:[],C=Object.values(u).reduce((x,A)=>x+A.files.length+A.folders.length,0),E=h.pagination,L=!!E?.hasMore,I=m&&!L?qg({owner:o.owner,repo:o.repo,truncated:f,hasMore:!1}):void 0,k=L?[ty(E??{})]:[...b,...I?[I]:[]],j=[];if(L){let x=E?.currentPage??1,A=E?.totalPages;j.push(`Tree paginated (page ${x}${A?` of ${A}`:""}); use page=${x+1} to fetch the remaining entries.`)}else f&&j.push(`Tree truncated at maxDepth=${o.maxDepth??"default"}; re-query with a deeper maxDepth or a more specific path to see the rest.`);let P=oy({data:h,entryCount:C,wasTruncated:f,extraHints:k},o);return ye(o,P.data,m,S.GITHUB_VIEW_REPO_STRUCTURE,{hintContext:{entryCount:C,path:o.path,depth:o.maxDepth,branch:o.branch,wasFilteredToEmpty:p,flagFiles:Object.values(u).flatMap(x=>x.files.filter(A=>/(Mode|Config|Flag|Feature)\.[A-Za-z0-9]+$/.test(A)))},prefixHints:g,extraHints:[...j,...P.extraHints],rawResponse:l.response.rawResponseChars})}catch(s){return he(s,o,"Failed to explore repository structure")}},{toolName:S.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"],peerHints:!0},e)}function oy(e,t){let n=ey(e.data.structure,e.entryCount,e.wasTruncated);return{data:e.data,extraHints:[...n,...e.extraHints]}}import{existsSync as sl}from"fs";import{delimiter as iy,dirname as sy,join as al}from"path";function cl(){return process.platform==="win32"?"npm.cmd":"npm"}function ay(){let e=sy(process.execPath);return al(e,cl())}function cy(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function ly(){let e=(process.env.PATH??"").split(iy).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...cy()])]}function uy(){let e=ay();if(sl(e))return{command:process.execPath,argsPrefix:[e]};let t=cl();for(let n of ly()){let r=al(n,t);if(sl(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var dy=["view","search","ping","config","whoami"],py=[...$n,...ja];async function Jt(e,t,n={}){if(!dy.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Bn(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=uy(),c=await mt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:py});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var qt=new Map,my=5,Ro=3e4;function en(e){try{return new URL(e).host||e}catch{return e}}var bo=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 ll(e,t=Date.now()){let n=qt.get(en(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Ro)throw new bo(en(e),Ro-r);n.state="half-open"}}function So(e){let t=qt.get(en(e));t&&(t.failures=0,t.state="closed")}function ul(e,t=Date.now()){let n=en(e),r=qt.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=my&&(r.state="open",r.openedAt=t)),qt.set(n,r)}function dl(e,t=Date.now()){let n=qt.get(en(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Ro:!1}var fy=6e4;function pl(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function hy(e,t,n,r){e&&et({limit_type:"primary",retry_after_seconds:pl(r),api_method:t,api_url:n,provider:e}).catch(He("fetch rate-limit session logging"))}function gy(e,t,n,r,o){e.body?.cancel?.().catch(He("response body cancellation")),H("fetchWithRetries",Je.FETCH_HTTP_ERROR.code).catch(He("fetch retry session logging"));let i=new Error(Je.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&ei(r),e.status===429&&hy(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function yy(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=pl(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function st(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=fy,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:d}=t,u=e;if(a){let R=e.includes("?")?"&":"?";u=`${e}${R}version=${encodeURIComponent(ct)}`}let m={"User-Agent":`Octocode-MCP/${ct}`,...i},p=globalThis.fetch;if(!p)throw H("fetchWithRetries",Je.FETCH_NOT_AVAILABLE.code).catch(He("fetch retry session logging")),new Error(Je.FETCH_NOT_AVAILABLE.message);ll(u);let f,h=n+1;for(let R=1;R<=h;R++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(u,{method:s,headers:m,signal:c});if(!b.ok)throw gy(b,s,u,d,l);if(b.status===204)return So(u),null;let g=await b.json();return So(u),g}catch(b){let g=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(g&&g.retryable===!1)throw b;if(f=b instanceof Error?b:new Error(String(b)),R===h)break;let C=yy(R,r,o,g);await new Promise(E=>setTimeout(E,C))}}throw ul(u),await H("fetchWithRetries",Je.FETCH_FAILED_AFTER_RETRIES.code),new Error(Je.FETCH_FAILED_AFTER_RETRIES.message(h,f?.message||""))}import{z as T}from"zod";var nr=T.looseObject({name:T.string(),version:T.string(),repository:T.union([T.string(),T.object({url:T.string().optional(),type:T.string().optional(),directory:T.string().optional()})]).optional(),main:T.string().optional(),module:T.string().optional(),type:T.string().optional(),exports:T.unknown().optional(),types:T.string().optional(),typings:T.string().optional(),description:T.string().optional(),keywords:T.array(T.string()).optional(),license:T.union([T.string(),T.object({type:T.string().optional()})]).optional(),homepage:T.string().optional(),author:T.union([T.string(),T.object({name:T.string().optional(),email:T.string().optional(),url:T.string().optional()})]).optional(),maintainers:T.array(T.object({name:T.string().optional(),email:T.string().optional()})).optional(),engines:T.record(T.string(),T.string()).optional(),dependencies:T.record(T.string(),T.string()).optional(),devDependencies:T.record(T.string(),T.string()).optional(),peerDependencies:T.record(T.string(),T.string()).optional(),time:T.record(T.string(),T.string().optional()).optional()}),Ry=T.looseObject({package:T.looseObject({name:T.string().nullish(),version:T.string().nullish(),description:T.string().nullish(),links:T.looseObject({npm:T.string().nullish(),homepage:T.string().nullish(),repository:T.string().nullish()}).nullish()}),score:T.looseObject({final:T.number().nullish(),detail:T.looseObject({quality:T.number().nullish(),popularity:T.number().nullish(),maintenance:T.number().nullish()}).nullish()}).nullish()}),ml=T.looseObject({objects:T.array(Ry),total:T.union([T.number(),T.string()]).optional()}),fl=T.union([T.string(),T.boolean(),T.number(),T.null(),T.record(T.string(),T.unknown())]);var or="https://registry.npmjs.org",by=3e3,rr=null;async function Sl(){if(rr)return rr;try{let e=await Jt("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 rr=t,t}}catch{}return rr=or,or}function yt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var Sy="https://api.npmjs.org/downloads/point/last-week";function Le(e){return e===void 0?0:$(e)}async function Cl(e){try{let t=`${Sy}/${encodeURIComponent(e)}`,n=await st(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:Le(n)}}catch{return{rawResponseChars:0}}}function ir(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Pl(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 Cy(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function Py(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 hl(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 gl(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 Ey(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Co(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=yt(e.repository):(e.repository.url&&(r=yt(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:Ey(e),...o?{repositoryDirectory:o}:{},...hl(e.exports)?{exports:hl(e.exports)}:{},...gl(e.bin,e.name)?{bin:gl(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 Ty(e){return typeof e.links?.repository=="string"?yt(e.links.repository):typeof e.repository=="string"?yt(e.repository):typeof e.repository?.url=="string"?yt(e.repository.url):null}function wy(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:Ty(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 El(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function Tl(e){try{let t=await Sl(),n=El(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await st(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Le(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await st(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Le(i)}}catch{return{rawResponseChars:0}}}async function Po(e,t,n){let[r,o]=await Promise.all([Cl(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Tl(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 sr(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function _y(e,t){try{let n=await Jt("view",[e,"--json"],{timeout:by});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,...sr(c)?{}:{errorDetail:c},rawResponseChars:Le(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=Le(o),s=nr.safeParse(o);return s.success?{pkg:Co(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,...sr(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function xy(e,t){try{let n=await Sl(),r=El(e),o=`${n}/${r}/latest`,i;try{i=await st(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let d=l instanceof Error?l.message:String(l);return d.includes("404")||d.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:d,rawResponseChars:0}}let s=Le(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=nr.safeParse(i);return a.success?{pkg:Co(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,...sr(r)?{}:{errorDetail:r},rawResponseChars:0}}}function Ay(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function wl(e,t){let n=0,r;for(let o of Ay(e)){let i;try{i=await st(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);sr(l)||(r=l);continue}if(n+=Le(i),!i||typeof i!="object")continue;let s=nr.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Co(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Eo(e,t=!1){let[n,r]=await Promise.allSettled([_y(e,t),xy(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?Po(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function Ly(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Eo(e,t);if(!r){if(o){let s=Pl(o);if(s&&n){let a=await wl(e,t);if(a.pkg){let c=await Po(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 Iy(e,t,n,r=0){let o=Math.max(t+r,t),i=await Jt("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:Le(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=Le(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let d=[...a].sort((f,h)=>{let R=f?.score?.final??0;return(h?.score?.final??0)-R}).slice(r,r+t),u=await Promise.all(d.map(async f=>{if(!f||typeof f!="object")return null;let h=f;if(!h.name)return null;if(n){let R=await Eo(h.name,!0);if(R.pkg)return R}return{pkg:wy(h),rawResponseChars:0}})),m=u.map(f=>f?.pkg).filter(f=>!!f),p=u.reduce((f,h)=>f+(h?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function Oy(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${or}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await st(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`NPM registry search failed: ${f instanceof Error?f.message:String(f)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Le(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=ml.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 d=[...c.data.objects].sort((f,h)=>{let R=f.score?.final??0;return(h.score?.final??0)-R}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),u=await Promise.all(d.map(async f=>{if(n){let h=await Eo(f.name,!0);if(h.pkg)return h}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?yt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=u.map(f=>f.pkg).filter(f=>!!f),p=u.reduce((f,h)=>f+h.rawResponseChars,0);return{packages:m,totalFound:Py(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 yl(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 st(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:Le(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Le(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"?yt(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:Le(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Rl(e,t,n,r=0){try{let o=await Iy(e,t,n,r);if(!("error"in o))return o}catch{}return Oy(e,t,n,r)}async function bl(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}):Cl(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Tl(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 _l(e,t,n,r=0){let o=Pe("npm-search",{name:e,limit:t,metadata:n,from:r});return Ee(o,async()=>{if(dl(or)){if(r===0&&t===1&&ir(e)){let d=await wl(e,n);if(d.pkg){let u=await Po(e,d.pkg,d.rawResponseChars);return{packages:u.pkg?[u.pkg]:[],totalFound:u.pkg?1:0,rawResponseChars:u.rawResponseChars}}}let l=await yl(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&&ir(e)){let l=await Ly(e,n,t===1);if("error"in l){if(!Pl(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Rl(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return bl(s);let a=Cy(e);if(a!==e){let l=await Rl(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return bl(l)}let c=await yl(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)})}async function To(e){try{let t=await Jt("view",[e,"deprecated","--json"]);if(t.error||t.exitCode!==0)return null;let n=t.stdout.trim();if(!n||n==="undefined"||n==="")return{deprecated:!1};try{let r=JSON.parse(n),o=fl.safeParse(r),i=o.success?o.data:n;return{deprecated:!0,message:typeof i=="string"?i:"This package is deprecated"}}catch{return{deprecated:!0,message:n}}}catch{return null}}async function xl(e){let t=ir(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return _l(e.name,n,!0,r)}function ky(e){return"error"in e}function It(e){return"npmUrl"in e}function wo(e){return It(e)&&e.path?e.path:e.name}function Al(e){return It(e)?e.repoUrl:e.repository}function vy(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function Fy(e){if(!e)return{};let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);return t?.[1]&&t[2]?{owner:t[1],repo:t[2].replace(/\.git$/,"").replace(/\/$/,"")}:{}}function My(e){let t=wo(e),n=Al(e),r={name:t};It(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.weeklyDownloads=e.weeklyDownloads)),n&&(r.repository=n);let o=vy(It(e)?e.repositoryDirectory:void 0);return o&&(r.repositoryDirectory=o),r}function Ny(e,t){let n=[],r=wo(e);t?.deprecated&&n.push(`DEPRECATED: ${r} \u2014 ${t.message??"use an alternative"}`);let o=It(e)?e.source:void 0;o==="cdn"?n.push("Metadata from npm CDN cache \u2014 verify version when registry access is restored."):o==="web"&&n.push("Metadata from npms.io fallback \u2014 verify version when registry access is restored."),n.push(`Install: npm install ${r}`);let i=Al(e),{owner:s,repo:a}=Fy(i);return s&&a?n.push(`Browse source: use ghViewRepoStructure owner=${s} repo=${a}`):i?n.push(`Repository: ${i} \u2014 use ghSearchRepos to find on GitHub.`):n.push(`No repository URL for "${r}" \u2014 use ghSearchRepos to find the source repo.`),n}function Hy(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=Math.max(1,Math.ceil(t/i));return{currentPage:o,totalPages:s,perPage:i,totalFound:t,returned:n,hasMore:o<s}}function Dy(e){if(e.totalFound===0||e.totalPages<=1)return[];if(e.currentPage>e.totalPages)return[`Requested page ${e.currentPage}/${e.totalPages} is past the end. Retry page=${e.totalPages}.`];let t=(e.currentPage-1)*e.perPage+1,n=Math.min(t+e.returned-1,e.totalFound);return e.hasMore?[`Page ${e.currentPage}/${e.totalPages} (showing ${t}-${n} of ${e.totalFound} packages). Next: page=${e.currentPage+1}`]:[]}function Gy(e,t){return[`Found ${e}${t>e?` of ${t}`:""} packages. Re-run with an exact name for source details, install command, and repo navigation.`]}async function Ll(e){return X(e.queries,async t=>{try{if(!t.packageName)return _("Package name is required for package search",t);let n=await xl({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(ky(n))return _(n.error,t,{rawResponse:n,customHints:[...n.hints??[],...se(S.PACKAGE_SEARCH,"error",{originalError:n.error})]});let r=n.packages,o=r.map(My),i=o.length>0,s=r.length>1||n.totalFound>1,a=Hy(t,n.totalFound,o.length,s),c=null;if(!s&&i&&r[0]){let u=It(r[0])?r[0].source:void 0;u!=="cdn"&&u!=="web"&&(c=await To(wo(r[0])))}let l=[...Dy(a),...i?s?Gy(o.length,n.totalFound):Ny(r[0],c):se(S.PACKAGE_SEARCH,"empty",{name:t.packageName})];return ye(t,{packages:o,pagination:a},i,S.PACKAGE_SEARCH,{extraHints:l,rawResponse:n.rawResponseChars??n})}catch(n){return _(n,t,{customHints:se(S.PACKAGE_SEARCH,"error",{originalError:n instanceof Error?n.message:String(n)})})}},{toolName:S.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"],peerHints:!0},e)}import{open as $y,readFile as By,stat as Uy}from"fs/promises";import{ContentSanitizer as zy}from"octocode-security/contentSanitizer";var Ie={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 Ol(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Il(e,t,n){return{...e,...Ol(t,n)}}function Qy(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;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.",hints:["fullContent and matchString are mutually exclusive. Pick one \u2014 matchString is more token-efficient when you know what to look for."]};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.",hints:["fullContent and startLine/endLine are mutually exclusive. Pick one extraction mode so line ranges are never silently ignored."]};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.",hints:["matchString and startLine/endLine are mutually exclusive. Use matchString for search-driven extraction or startLine/endLine for a known range."]};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.`,hints:[`Add endLine to complete the range, e.g. endLine=${e.startLine+50}.`,"Use matchString for search-driven extraction when you do not know the exact end line."]}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`,hints:["Add startLine to complete the range, e.g. startLine=1.","Use matchString for search-driven extraction when you do not know the exact start line."]}:null}async function jy(e,t){try{return{fileStats:await Uy(t)}}catch(n){let r=ke.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:_(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t},hintContext:{path:e.path}})}}}function Vy(e,t){return t>Ie.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function Wy(e,t,n){let r=ke.fileTooLarge(e.path,n,Ie.LARGE_FILE_THRESHOLD_KB);return _(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t},hintContext:{fileSize:n*1024,isLarge:!0}})}function Ky(e,t){let n=ke.binaryFileUnsupported(e.path);return _(n,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t},customHints:["Binary or non-UTF-8 content."]})}async function Yy(e){let n=Buffer.alloc(8192),r;try{r=await $y(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 d=l===9||l===10||l===13;l<32&&!d&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(pa("binary sample handle close",void 0))}}async function Xy(e,t){try{return{content:await By(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?ke.fileAccessFailed(e.path,r):ke.fileReadFailed(e.path,r);return{errorResult:_(i,e,{toolName:S.LOCAL_FETCH_CONTENT,hintContext:{path:e.path},extra:{resolvedPath:t}})}}}function Zy(e,t){let n=[`No matches for "${e.matchString}" in ${e.path} (${t} line${t===1?"":"s"} scanned).`];return e.matchStringIsRegex?n.push("Regex is per-line only \u2014 verify the pattern fits on one line."):n.push('Try matchStringIsRegex=true for pattern matching (e.g. "export.*function").'),e.matchStringCaseSensitive&&n.push("caseSensitive=true is active \u2014 disable for fuzzier matching."),{status:"empty",errorCode:G.NO_MATCHES,totalLines:t,hints:n}}function Jy(e,t,n){let r=bn(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Zy(e,n)};let o=r.lines.join(`
37
+ `),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,d,u;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(l=m.start,d=p.end,r.matchRanges.length>1&&(u=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:d,matchRanges:u,warnings:[c]}}function qy(e){return e.startLine!==void 0&&e.endLine!==void 0}function eR(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:G.NO_MATCHES,hints:[...se(S.LOCAL_FETCH_CONTENT,"empty"),`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:G.NO_MATCHES,hints:[...se(S.LOCAL_FETCH_CONTENT,"empty"),`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(`
38
+ `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function tR(e,t,n){let r=t.split(`
39
+ `),o=r.length;return e.matchString?Jy(e,r,o):qy(e)?eR(e,r,o):{resultContent:t,isPartial:!1}}function nR(e){if(e.isPartial===!0&&e.matchRanges===void 0&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.totalLines=="number"&&e.endLine<e.totalLines){let t=e.totalLines-e.endLine;return[`More content: use startLine=${e.endLine+1} to continue (${t} line${t===1?"":"s"} remaining)`]}return[]}function rR(e,t){return t.matchRanges!==void 0?["Use the matched line numbers as lineHint anchors for lspGetSemantics, or increase contextLines for more surrounding code."]:e.minify==="symbols"?[]:["Use localSearchCode to find related occurrences, or lspGetSemantics with a symbolName + lineHint from this file."]}function oR(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r,hints:se(S.LOCAL_FETCH_CONTENT,"empty")};let a=[...t.warnings??[]],c=String(e.path),l=i?U.applyContentViewMinification(t.resultContent,c):t.resultContent,d=e.charLength,u=e.charOffset??0,m=d,p=!1,f=u;m===void 0&&l.length>o&&(m=o,p=!0,a.push(`Auto-paginated: Content (${l.length} chars) exceeds ${o} char limit`));let h="char-limit",R=m;if(m!==void 0){let P=Rn(l,f,m,c);h=P.chunkMode,R=P.length}let b=wt(l,f,R,m!==void 0?{pageSize:m}:void 0),g=t.isPartial||b.hasMore,C=nR({isPartial:g,startLine:t.actualStartLine,endLine:t.actualEndLine,totalLines:r,matchRanges:t.matchRanges}),E=rR(e,t),L=m||p?ps(b,{toolName:S.LOCAL_FETCH_CONTENT}):[],I,k=[];if(b.hasMore&&h==="char-limit"&&gn(b.paginatedContent)){let P=b.charOffset+b.charLength;if(I=yn(l,P,c),I!==void 0){let x=I-P;k.push(`Page cut mid-block at char ${P}. Next top-level definition at char ${I}. Re-request with charLength=${(R??b.charLength)+x} to extend this page to the next boundary, or use charOffset=${P} to continue page-by-page.`)}}let j=[];if(r>2e3&&e.minify!=="symbols"&&!e.matchString&&!e.startLine&&!e.endLine&&!e.fullContent&&b.hasMore){let P=Math.max(1,r-200);j.push(`Large file (${r} lines) \u2014 minify:"symbols" for an export index, or startLine=${P} for the tail.`)}return e.minify!=="none"&&r>300&&!e.matchString&&j.push('If you need exact comment text (// \u2026 or /* \u2026 */), test assertions, or doc-strings, re-fetch with minify:"none" and add matchString to anchor on the relevant section.'),{path:c,content:b.paginatedContent,...s!=="standard"&&{contentView:s},...g&&{isPartial:g},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()},...(m!==void 0||u>0||p)&&{pagination:{...Mi(b),chunkMode:h,...I!==void 0&&{nextBlockChar:I}}},...a.length>0&&{warnings:a},hints:[...C,...k,...L,...j,...E]}}function iR(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function kl(e){let t=$e();try{let n=Re(e,S.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=Qy(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await jy(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await Yy(o))return D(Ky(e,o),c);if(Vy(e,l))return D(Wy(e,o,l),c);let{content:d,errorResult:u}=await Xy(e,o);if(u||d===void 0)return u;let m=zy.sanitizeContent(d,i),p=m.content,f=p.length,h=Buffer.byteLength(p,"utf-8"),R=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,b=e.minify,g=b==="standard"||b==="symbols",C=g?"standard":"none",E;if(b==="symbols"){let P=U.extractSignatures(p,i);if(P===null&&(E=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),P!==null){let x=p.split(`
40
+ `).length,A=U.applyContentViewMinification(P,i),B=[U.SIGNATURES_ONLY_HINT];return e.matchString&&B.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),R&&B.push(R),D({path:e.path,content:A,contentView:"symbols",isSkeleton:!0,totalLines:x,...Ol(f,h),hints:B},f)}}let L=p.split(`
41
+ `).length,I=tR(e,p,t),k=P=>{let x=[...E?[E]:[],...R?[R]:[]];if(x.length===0)return P;let A=P.warnings??[];return{...P,warnings:[...A,...x]}};if(I.earlyResult){let P=I.earlyResult.content,x=g&&typeof P=="string"?{...I.earlyResult,content:U.applyContentViewMinification(P,i)}:I.earlyResult;return D(Il(k(_o(iR(x,C),e,L)),f,h),f)}let j=oR(e,I,s,L,t,g,C);return D(Il(k(_o(j,e,L)),f,h),f)}catch(n){return _(n,e,{toolName:S.LOCAL_FETCH_CONTENT})}}function _o(e,t,n){return e}async function vl(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=In.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await kl(r.data)}}),{toolName:S.LOCAL_FETCH_CONTENT,peerHints:!0},e)}function Ot(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 tn(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 aR=["node_modules","dist",".git","coverage","build",".next",".nuxt",".svelte-kit",".turbo",".cache",".parcel-cache","out","target",".octocode",".cursor",".vscode",".idea",".claude",".context"];function cR(e,t){let n=t??aR,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}function lR(e){let{query:t,currentPage:n,totalPages:r,shownCount:o,totalFiles:i,wasFileCapped:s,maxFiles:a,discoveredFileCount:c,hasConfigFiles:l,extraHints:d=[]}=e,u=t,m=[];Array.isArray(u.names)&&u.names.length>0&&m.push(`names: ${u.names.join(", ")}`),u.entryType&&m.push(`entryType: ${u.entryType==="f"?"files":u.entryType==="d"?"directories":String(u.entryType)}`);let p=f=>typeof f=="string"&&!Nl.test(f)?" (skipped: invalid format)":"";return u.modifiedBefore&&m.push(`modified before: ${u.modifiedBefore}${p(u.modifiedBefore)}`),u.modifiedWithin&&m.push(`modified within: ${u.modifiedWithin}${p(u.modifiedWithin)}`),u.sizeGreater&&m.push(`size > ${u.sizeGreater}`),u.sizeLess&&m.push(`size < ${u.sizeLess}`),Array.isArray(u.excludeDir)&&u.excludeDir.length>0&&m.push(`excluding: ${u.excludeDir.join(", ")}`),[...d,...m.length>0?[`Active filters \u2014 ${m.join(" | ")}`]:[],...n<r?[`Page ${n}/${r} (${o} of ${i}). Next: page=${n+1}`]:[],...r>0&&n>r?[`Requested page ${n} is outside available range (1-${r}). Use page=${r} for the last page.`]:[],...s?[`Results capped at ${a} of ${c} discovered. All ${a} are reachable via page; to see the rest, narrow with names/entryType/time filters. Note: sorting applies only within the capped set \u2014 limit is a pre-sort discovery cap.`]:[],...i===0?se(S.LOCAL_FIND_FILES,"empty",{fileCount:i,hasConfigFiles:l,path:t.path,names:t.names,modifiedWithin:t.modifiedWithin,sizeGreater:t.sizeGreater,sizeLess:t.sizeLess}):[u.entryType==="f"?`Found ${i} file${i===1?"":"s"}. Use localSearchCode to search or localGetFileContent to read.`:u.entryType==="d"?`Found ${i} director${i===1?"y":"ies"}. Use localViewStructure to browse or localSearchCode to search.`:`Found ${i} entr${i===1?"y":"ies"} \u2014 pass entryType="f" for files, entryType="d" for directories. Use localSearchCode or localGetFileContent.`]]}async function Fl(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Re(e,S.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:cR(i.path,i.excludeDir)},a=mR(s),c=e.limit??1e4,l=U.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),d=l.totalDiscovered,u=l.wasCapped,m=l.entries.map(N=>uR(N,r)),p=e.sortBy||"modified";dR(m,p,r);let f=[],h=pR(m,t,n),R=h.length,b=e.itemsPerPage||20,g=e.page||1,C=Math.max(1,Math.ceil(R/b)),E=(g-1)*b,L=Math.min(E+b,R),k=h.slice(E,L),j=/\.(config|rc|env|json|ya?ml|toml|ini)$|^(\..*rc|config\.|\.env)/i,P=k.some(N=>j.test(N.path.split("/").pop()||"")),x=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],A=[...a,...x],B={...R===0?{status:"empty"}:{},path:i.path,files:k,pagination:{currentPage:g,totalPages:C,filesPerPage:b,totalFiles:R,hasMore:g<C,...u?{totalFilesFound:d}:{}},...A.length>0&&{warnings:A},hints:lR({query:e,currentPage:g,totalPages:C,shownCount:k.length,totalFiles:R,wasFileCapped:u,maxFiles:c,discoveredFileCount:d,hasConfigFiles:P,extraHints:f})};return D(Ml(B,e,{totalFiles:R}),l.entries.reduce((N,M)=>N+M.path.length,0))}catch(o){return _(o,e,{toolName:S.LOCAL_FIND_FILES})}}function uR(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 Ml(e,t,n){return e}function dR(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 pR(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=Ot(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var Nl=/^\d+[hdwm]$/;function mR(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!Nl.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}async function Hl(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=On.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await Fl(r.data)}}),{toolName:S.LOCAL_FIND_FILES,peerHints:!0},e)}import{existsSync as Ke,readFileSync as fR}from"node:fs";import{dirname as xo,join as We}from"node:path";import{spawnSync as hR}from"node:child_process";import{fileURLToPath as gR}from"node:url";import{securityRegistry as yR}from"octocode-security/registry";import{normalizeCommandName as RR}from"octocode-security/commandValidator";var rn=xo(gR(import.meta.url)),nn=null;function ar(){return nn!==null||(nn=CR(),SR(nn)),nn}var bR=/^rg(-[a-z0-9-]+)?$/i;function SR(e){let t=RR(e);if(!(t==="rg"||!bR.test(t)))try{yR.addAllowedCommands([t])}catch{}}function CR(){let e=PR();if(e)return e;let t=ER();if(t)return t;let n=wR();if(n)return n;let r=_R();if(r)return r;let o=xR();if(o)return o;throw new Error("ripgrep (rg) is unavailable. Install it via: npm i -g octocode-mcp OR brew install ripgrep OR apt install ripgrep")}function PR(){let e=process.env.OCTOCODE_RG_PATH;return e&&Ke(e)?e:null}function ER(){let e=Dl();if(!e)return null;let t=TR();if(t)try{let s=JSON.parse(fR(t,"utf8")).rg?.find(a=>a.platform===e);if(s){let a=We(xo(t),s.file);if(Ke(a))return a}}catch{}let n=process.platform==="win32"?".exe":"",r=[`rg-${e}${n}`,`rg${n}`],o=[We(rn,"runtime","rg"),We(rn,"..","runtime","rg"),We(rn,"..","..","runtime","rg")];for(let i of o)for(let s of r){let a=We(i,s);if(Ke(a))return a}return null}function TR(){let e=[We(rn,"runtime-assets.json"),We(rn,"..","runtime-assets.json")];for(let t of e)if(Ke(t))return t;return null}function wR(){try{let e=process.execPath;if(/[/\\](node|bun)(\.exe)?$/.test(e))return null;let t=xo(e),n=process.platform==="win32"?".exe":"",r=We(t,`rg${n}`);if(Ke(r))return r;let o=Dl();if(o){let i=We(t,`rg-${o}${n}`);if(Ke(i))return i}}catch{}return null}function _R(){if(process.env.OCTOCODE_DISABLE_VSCODE_RIPGREP==="1")return null;try{let e=gr("@vscode/ripgrep");if(e.rgPath&&typeof e.rgPath=="string"&&Ke(e.rgPath))return e.rgPath}catch{}try{let e=process.env.npm_config_arch||process.arch,t=process.platform==="win32"?"rg.exe":"rg",n=`@vscode/ripgrep-${process.platform}-${e}`,r=gr.resolve(`${n}/bin/${t}`);if(Ke(r))return r}catch{}return null}function xR(){try{let t=process.platform==="win32"?"where.exe":"which",n=hR(t,["rg"],{encoding:"utf8",timeout:3e3});if(n.status===0&&n.stdout){let r=(n.stdout.trim().split(`
42
+ `)[0]??"").trim();if(r&&Ke(r))return r}}catch{}return null}function Dl(){let e=process.platform,t=process.arch;return e==="darwin"&&t==="arm64"?"darwin-arm64":e==="darwin"&&t==="x64"?"darwin-x64":e==="linux"&&t==="arm64"?"linux-arm64":e==="linux"&&t==="x64"?"linux-x64":e==="win32"&&t==="x64"?"windows-x64":null}var cr=new Map,AR=parseInt(process.env.OCTOCODE_COMMAND_CHECK_TIMEOUT_MS||"5000",10)||5e3,LR={rg:{name:"ripgrep",versionFlag:"--version",tool:"localSearchCode"}};async function Gl(e,t=!1){if(!t&&cr.has(e))return cr.get(e);let n=LR[e];try{let r=ar(),o=await no(r,[n.versionFlag],AR),i={available:o,command:e,...o?{}:{error:`${n.name} (${e}) bundled binary is unavailable`}};return cr.set(e,i),i}catch(r){let o={available:!1,command:e,error:r instanceof Error?r.message:`Failed to check ${e} availability`};return cr.set(e,o),o}}var lr=class{command;args=[];constructor(t){this.command=t}addFlag(t){return this.args.push(t),this}addOption(t,n){return this.args.push(t,String(n)),this}addArg(t){return this.args.push(t),this}build(){return{command:this.command,args:[...this.args]}}reset(){return this.args=[],this}getArgs(){return[...this.args]}};var ur=class extends lr{constructor(){super(ar()),this.addFlag("--no-config")}simple(t,n){return this.addFlag("-n"),this.addFlag("--column"),this.addFlag("-S"),this.addOption("--color","never"),this.addOption("--sort","path"),this.addArg("--"),this.addArg(t),this.addArg(n),this}filesOnly(){return this.addFlag("-l"),this}context(t){return this.addOption("-C",t),this}include(t){return this.addOption("-g",t),this}exclude(t){return this.addOption("-g",`!${t}`),this}excludeDir(t){return this.addOption("-g",`!${t}/`),this}type(t){return this.addOption("-t",t),this}fixedString(){return this.addFlag("-F"),this}perlRegex(){return this.addFlag("-P"),this}maxMatches(t){return this.addOption("-m",t),this}fromQuery(t){return this._applyMatchFlags(t),this._applyContextFlags(t),this.addFlag("-n"),this.addFlag("--column"),this._applyOutputModeFlags(t),this._applyFilterFlags(t),this._isPlainTextOutput(t)||this.addFlag("--json"),this._applyExecutionFlags(),this._applySortFlags(t),this._applyDiagnosticFlags(t),this.addArg("--"),this.addArg(t.keywords??""),this.addArg(t.path),this}_isPlainTextOutput(t){return!!(t.filesOnly||t.filesWithoutMatch||t.countLinesPerFile||t.countMatchesPerFile)}_applyMatchFlags(t){t.fixedString?this.addFlag("-F"):t.perlRegex&&this.addFlag("-P"),t.caseSensitive?this.addFlag("-s"):t.caseInsensitive?this.addFlag("-i"):this.addFlag("-S"),t.wholeWord&&this.addFlag("-w"),t.invertMatch&&this.addFlag("-v")}_applyContextFlags(t){t.contextLines!==void 0&&t.contextLines>0&&this.addOption("-C",t.contextLines)}_applyOutputModeFlags(t){t.filesOnly?this.addFlag("-l"):t.filesWithoutMatch?this.addFlag("--files-without-match"):t.countMatchesPerFile?this.addFlag("--count-matches"):t.countLinesPerFile&&this.addFlag("-c")}_applyFilterFlags(t){if(t.langType&&this.addOption("-t",t.langType),t.include&&t.include.length>0){let n=this._consolidateGlobs(t.include);for(let r of n)this.addOption("-g",r)}if(t.exclude&&t.exclude.length>0)for(let n of t.exclude)this.addOption("-g",`!${n}`);if(t.excludeDir&&t.excludeDir.length>0)for(let n of t.excludeDir)this.addOption("-g",`!${n}/`);t.noIgnore&&this.addFlag("--no-ignore"),t.hidden&&this.addFlag("--hidden"),t.multiline&&(this.addFlag("-U"),t.multilineDotall&&this.addFlag("--multiline-dotall"))}_applyExecutionFlags(){this.addOption("-j",4)}_applySortFlags(t){let n=t.sort||"path";t.sortReverse?(this.clearSortOption(),this.addOption("--sortr",n)):(this.clearSortrOption(),this.addOption("--sort",n))}_applyDiagnosticFlags(t){this.addOption("--color","never")}_consolidateGlobs(t){let n=/^\*\.([a-zA-Z0-9]+)$/,r=[],o=[];for(let s of t){let a=s.match(n);a&&a[1]?r.push(a[1]):o.push(s)}let i=[];return r.length>1?i.push(`*.{${r.join(",")}}`):r.length===1&&i.push(`*.${r[0]}`),i.push(...o),i}clearSortOption(){let t=this.args.indexOf("--sort");t!==-1&&t<this.args.length-1&&this.args.splice(t,2)}clearSortrOption(){let t=this.args.indexOf("--sortr");t!==-1&&t<this.args.length-1&&this.args.splice(t,2)}};import{validateRipgrepQuery as HR}from"@octocodeai/octocode-core/schemas/runtime";function $l(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=U.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={matchCount:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}function IR(e){return e.trim().split(`
43
+ `).filter(Boolean).filter(n=>!Bl(n)).map(n=>({path:n,matchCount:1,matches:[]}))}function OR(e){return e.trim().split(`
44
+ `).filter(Boolean).filter(n=>!Bl(n)).map(n=>{let r=n.lastIndexOf(":");if(r===-1)return{path:n,matchCount:1,matches:[]};let o=n.slice(0,r),i=parseInt(n.slice(r+1),10);return{path:o,matchCount:isNaN(i)?1:i,matches:[]}})}function Bl(e){return/^\d+\s/.test(e)&&/\b(?:files|bytes|seconds|matches|searched|printed|spent)\b/.test(e)}function Ul(e,t){let n=t.countLinesPerFile||t.countMatchesPerFile,r=t.filesOnly||t.filesWithoutMatch;if(n){let o=OR(e),i=o.reduce((s,a)=>s+(a.matchCount??0),0);return{files:o,stats:{matchCount:i}}}else return r?{files:IR(e),stats:{}}:$l(e,t)}async function kt(e,t,n,r,o){let i=e;i.sort((ce,Q)=>vR(ce,Q,t));let s=i,a=!1;t.maxFiles&&i.length>t.maxFiles&&(s=i.slice(0,t.maxFiles),a=!0);let c=s.length,l=!!(t.filesOnly||t.filesWithoutMatch),d=!!(t.countLinesPerFile||t.countMatchesPerFile),u=l||d,m=s.reduce((ce,Q)=>ce+(Q.matchCount??0),0),p=u?o?.matchCount??m:m,f=t,h=f.itemsPerPage||Ie.DEFAULT_FILES_PER_PAGE,R=f.page||1,b=Math.ceil(c/h),g=(R-1)*h,C=Math.min(g+h,c),E=s.slice(g,C),L=f.maxMatchesPerFile||Ie.DEFAULT_MATCHES_PER_PAGE,I=E.map(ce=>{let Q=ce.matches?.length??0,O=Math.ceil(Q/L),K=Math.max(1,f.matchPage||1),pe=(K-1)*L,Se=Math.min(pe+L,Q),De=u?void 0:ce.matches?.slice(pe,Se);return{path:ce.path,...l?{}:{matchCount:d?ce.matchCount||1:Q},...De!==void 0&&{matches:De},pagination:!u&&Q>L?{currentPage:K,totalPages:O,matchesPerPage:L,totalMatches:Q,hasMore:K<O}:void 0}}),k=R<b?[`Page ${R}/${b} (${I.length} of ${c} files${l?"":`, ${p} matches`}). Next: page=${R+1}`]:b>0&&R>b?[`Page ${R} is outside range (1\u2013${b}). Use page=${b}.`]:[];a&&k.push(`Results limited to ${t.maxFiles} files (found ${i.length} matching)`);let j=I.filter(ce=>ce.pagination?.hasMore);j.length>0&&k.push(`Note: ${j.length} file(s) have more matches \u2014 use matchPage=${(f.matchPage||1)+1} with maxMatchesPerFile to continue matches inside those files`);let P=kR(I,t,p),x=t,A=[],B=x.include;Array.isArray(B)&&B.length>0&&A.push(`include: ${B.join(", ")}`);let N=x.exclude;Array.isArray(N)&&N.length>0&&A.push(`exclude: ${N.join(", ")}`);let M=x.excludeDir;Array.isArray(M)&&M.length>0&&A.push(`excludeDir: ${M.join(", ")}`);let oe=x.langType;oe&&A.push(`langType: ${oe}`),x.caseSensitive&&A.push("case-sensitive"),x.wholeWord&&A.push("whole-word"),A.length>0&&P.unshift(`Active filters \u2014 ${A.join(" | ")}`);let ae={files:I,pagination:{currentPage:R,totalPages:b,filesPerPage:h,totalFiles:c,...l?{}:{totalMatches:p},hasMore:R<b,...a?{totalFilesFound:i.length}:{}},...r.length>0?{warnings:r}:{},hints:[...c>0&&!u?["Use localGetFileContent with the full path (prepend base to each returned path) and line numbers to read surrounding code.","Pass line numbers as lineHint to lspGetSemantics for definitions, references, or call flow."]:[],...c>0&&u?["Use localGetFileContent to read listed files, or rerun localSearchCode without filesOnly/count mode for matched snippets."]:[],...k,...P]};return zl(ae,t,{totalMatches:p,totalFiles:c})}function zl(e,t,n){return e}function kR(e,t,n){let r=[];if(n>100||e.length>20){let o=[];!t.langType&&!t.include&&o.push("add langType or include"),t.excludeDir?.length||o.push("add excludeDir"),(t.keywords?.length??0)<5&&o.push("lengthen pattern"),o.length>0&&r.push(`Large result set (${n} matches in ${e.length} files). Narrow: ${o.join(", ")}.`)}return r}function vR(e,t,n){let r=(t.matchCount??0)-(e.matchCount??0);return r!==0?r:e.path.localeCompare(t.path)}function dr(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};if(!e.fixedString){let o=FR(r);o&&t.push(`invalid regex: ${o}`)}return!e.fixedString&&MR(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&NR(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function FR(e){try{return new RegExp(e),null}catch(t){return t instanceof Error?t.message:"unknown regex parse error"}}function MR(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function NR(e){return/\(\?[=!<]/.test(e)}async function Ql(e){let t=[],n=HR(e);if(!n.isValid)return _(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=tt.safeParse(e);if(!r.success){let R=r.error.issues.map(b=>b.message);return _(new Error(`Query validation failed: ${R.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return _(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}});let s=Re(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=dr({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return _(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],d=new ur,{command:u,args:m}=d.fromQuery(a).build(),p=await _e(u,m);if(p.code===null){let R=Ie.DEFAULT_EXEC_TIMEOUT_MS;return D({status:"error",error:`Search timed out after ${R/1e3} seconds.`,errorCode:G.COMMAND_TIMEOUT,searchEngine:"rg",hints:[`Search timed out after ${R/1e3} seconds.`,"Try a more specific path or add langType/include filters to narrow the search.","Use filesOnly=true for faster discovery.","Consider excluding large directories with excludeDir.",...l]},p.stdout.length+p.stderr.length)}if(p.code===1||p.success&&!p.stdout.trim())return D({status:"empty",searchEngine:"rg",warnings:[...t,...l],hints:se(S.LOCAL_RIPGREP,"empty",{keywords:o.keywords,path:o.path,langType:o.langType,include:o.include,excludeDir:o.excludeDir,fixedString:o.fixedString,caseSensitive:o.caseSensitive,mode:o.mode})},p.stdout.length);if(!p.success){let b=p.code===2&&/No such file or directory/.test(p.stderr)?`Search path not found: ${o.path}. Verify it with localViewStructure or localFindFiles.`:`Ripgrep failed (exit code ${p.code}): ${p.stderr}`;return _(new Error(b),o,{toolName:S.LOCAL_RIPGREP,rawResponse:p.stdout.length+p.stderr.length})}let f=Ul(p.stdout,o);!a.filesOnly&&p.stdout.length>Ie.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p.stdout.length/1024)}KB).`);let h=await kt(f.files,o,"rg",[...t,...l],f.stats);return D(h,p.stdout.length)}var DR="Using grep fallback because bundled ripgrep is unavailable; advanced ripgrep-only options may be ignored.";async function Vl(e,t){let n=[],r=tt.safeParse(e);if(!r.success){let h=r.error.issues.map(R=>R.message);return _(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n}})}let o=r.data;if(!o.path)return _(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n}});let s=Re(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=dr({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return _(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...n,...c.warnings]}});let l=BR(n,c.warnings,t,o),{args:d,outputMode:u}=GR(a),m=await _e("grep",d);if(m.code===null){let h=Ie.DEFAULT_EXEC_TIMEOUT_MS;return D({status:"error",error:`Search timed out after ${h/1e3} seconds.`,errorCode:G.COMMAND_TIMEOUT,searchEngine:"grep",hints:[`Search timed out after ${h/1e3} seconds.`,"Try a more specific path or add include/exclude filters to narrow the search.","Use filesOnly=true for faster discovery.",...l]},m.stdout.length+m.stderr.length)}if(m.code===1||m.success&&!m.stdout.trim())return D({status:"empty",searchEngine:"grep",warnings:l,hints:[...se(S.LOCAL_RIPGREP,"empty",{keywords:o.keywords,path:o.path,langType:o.langType,include:o.include,excludeDir:o.excludeDir,fixedString:o.fixedString,caseSensitive:o.caseSensitive,mode:o.mode,searchEngine:"grep"}),"Try with ripgrep for better results when bundled ripgrep is repaired."]},m.stdout.length);if(!m.success)return _(new Error(`grep fallback failed (exit code ${m.code}): ${m.stderr}`),o,{toolName:S.LOCAL_RIPGREP,rawResponse:m.stdout.length+m.stderr.length});let p=UR(m.stdout,u),f=await kt(p.files,o,"grep",l,{matchCount:p.matchCount});return D({...f,searchEngine:"grep"},m.stdout.length)}function GR(e){let t=["-R","-H"];e.fixedString?t.push("-F"):e.perlRegex&&t.push("-E"),(e.caseInsensitive||$R(e))&&t.push("-i"),e.wholeWord&&t.push("-w"),e.invertMatch&&t.push("-v"),t.push("-I");let n=e.contextLines;n!==void 0&&n>0&&t.push("-C",String(n));let r=e.filesOnly?"files":e.countLinesPerFile||e.countMatchesPerFile?"count":"matches";r==="files"?t.push("-l"):r==="count"?t.push("-c"):t.push("-n");for(let o of e.include??[])t.push(`--include=${o}`);for(let o of e.exclude??[])t.push(`--exclude=${o}`);for(let o of e.excludeDir??[])t.push(`--exclude-dir=${o}`);return e.langType&&t.push(`--include=*.${e.langType}`),t.push("--",e.keywords??"",e.path),{args:t,outputMode:r}}function $R(e){return e.caseSensitive!==!0&&e.caseInsensitive!==!0&&(e.keywords??"")===(e.keywords??"").toLowerCase()}function BR(e,t,n,r){let o=[DR];n&&o.push(`Ripgrep unavailable: ${n}`),o.push(...e,...t);let i=[];return r.filesWithoutMatch&&i.push("filesWithoutMatch"),r.countMatchesPerFile&&i.push("countMatchesPerFile uses grep -c line counts"),r.hidden&&i.push("hidden"),r.noIgnore&&i.push("noIgnore"),r.multiline&&i.push("multiline"),r.multilineDotall&&i.push("multilineDotall"),(r.sort||r.sortReverse)&&i.push("sort"),i.length>0&&o.push(`grep fallback ignored/degraded options: ${i.join(", ")}.`),o}function UR(e,t){if(t==="files"){let i=jl(e).map(s=>({path:s,matchCount:1,matches:[]}));return{files:i,matchCount:i.length}}if(t==="count"){let i=jl(e).map(zR).filter(a=>a!==void 0),s=i.reduce((a,c)=>a+(c.matchCount??0),0);return{files:i,matchCount:s}}let n=new Map;for(let i of e.split(`
45
+ `)){if(!i.trim()||i==="--")continue;let s=QR(i);if(!s)continue;let a=n.get(s.path)??{path:s.path,matchCount:0,matches:[]},c=a.matches??=[];c.push({value:s.value,line:s.line,column:0}),a.matchCount=c.length,n.set(s.path,a)}let r=[...n.values()],o=r.reduce((i,s)=>i+(s.matchCount??0),0);return{files:r,matchCount:o}}function jl(e){return[...new Set(e.trim().split(`
46
+ `).filter(Boolean))]}function zR(e){let t=Wl(e);if(!t)return;let n=Number.parseInt(t.numberText,10);if(!(!Number.isFinite(n)||n<=0))return{path:t.path,matchCount:n,matches:[]}}function QR(e){let t=Wl(e);if(!t)return;let n=Number.parseInt(t.numberText,10);if(Number.isFinite(n))return{path:t.path,line:n,value:t.rest}}function Wl(e){let t=e.indexOf(":");if(t===-1)return;let n=e.indexOf(":",t+1);if(n!==-1)return{path:e.slice(0,t),numberText:e.slice(t+1,n),rest:e.slice(n+1)}}import{readFile as jR,stat as Kl}from"node:fs/promises";var VR=["ts","tsx","js","jsx","mjs","cjs","py","go","rs","java","c","h","cpp","cc","cxx","hpp","hh","hxx","cs","sh","bash","zsh"],WR=["node_modules","dist",".git","build","coverage",".next","out","target"],KR=2e3,YR=1e6;function XR(e){if(!e)return;let n=e.replace(/\$+[A-Za-z0-9_]*/g," ").match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)??[],r;for(let o of n)(!r||o.length>r.length)&&(r=o);return r}async function ZR(e,t){if((await Kl(e)).isFile())return[e];let o=(t.include?.length?t.include:void 0)??VR.map(a=>`*.${a}`),i=t.excludeDir?.length?t.excludeDir:WR;return U.queryFileSystem({path:e,recursive:!0,entryType:"f",names:o,excludeDir:i,limit:t.maxFiles??KR}).entries.map(a=>a.path)}async function Yl(e){let t=Re(e,S.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath,r=e.pattern,o=e.rule,i=XR(r),s;try{s=await ZR(n,e)}catch(h){return _(h,e,{toolName:S.LOCAL_RIPGREP})}let a=[],c=[],l=0,d=0,u=0,m;for(let h of s){if(m)break;let R;try{if((await Kl(h)).size>YR)continue;R=await jR(h,"utf8")}catch{continue}if(i&&!R.includes(i)){u++;continue}let b;try{b=U.structuralSearch(R,h,r,o)}catch(g){let C=g instanceof Error?g.message:String(g);if(C.includes("does not support"))continue;m=C;break}d++,b.length!==0&&(l+=b.length,a.push({path:h,matchCount:b.length,matches:b.map(g=>({line:g.startLine,value:g.text.split(`
47
+ `,1)[0],column:g.startCol}))}))}if(m)return _(new Error(`Invalid structural ${o?"rule":"pattern"}: ${m}`),e,{toolName:S.LOCAL_RIPGREP,customHints:[o?"Check the YAML rule shape. Relational sub-rules (inside/has) need `stopBy: end` to walk all ancestors/descendants, else they silently match nothing.":"Check the pattern syntax. Use $X for a single node, $$$ARGS for a list. The pattern must be a complete code fragment for the target language."]});i?u>0&&c.push(`Pre-filter on "${i}" skipped parsing ${u} file(s); parsed ${d}.`):c.push(`No literal anchor in the ${o?"rule":"pattern"} \u2014 parsed all ${d} candidate file(s) with no text pre-filter.`);let f=await kt(a,e,"rg",c,{matchCount:l});if(l>0){let h=Array.isArray(f.hints)?[...f.hints]:[];return h.push("Structural matches return node ranges \u2014 pass matches[].line as the lspGetSemantics lineHint to navigate semantically."),{...f,hints:h}}return f}function JR(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 Xl(e){let t=JR(e);if(t.mode==="structural")return await Yl(t);t.contextLines===void 0&&(t.contextLines=2);try{let n=await Gl("rg");return n.available?await Ql(t):await Vl(t,n.error)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:G.OUTPUT_TOO_LARGE,hints:["Output exceeded 10MB - your pattern matched too broadly. Think about why results exploded:","Is the pattern too generic? Make it specific to target what you actually need","Searching everything? Add langType filters or path restrictions to focus scope","For node_modules: Target specific packages rather than searching the entire directory","Need file names only? FIND_FILES searches metadata without reading content","Strategy: Start with filesOnly=true to see what matched, then narrow before reading content"]}:_(n,t,{toolName:S.LOCAL_RIPGREP})}}async function Zl(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=tt.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await Xl(r.data)}}),{toolName:S.LOCAL_RIPGREP,peerHints:!0},e)}var qR=new Set(["+","*","?"]),eb=1e3;function tb(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Jl(e,t){let n=e[t];return n===void 0?!1:qR.has(n)||n==="{"&&ob(e,t)}function nb(e,t,n){let r=n.pop()??!1,o=Jl(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?eu(e,t+1):t+1})}function rb(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:eu(e,t)})}function ql(e){if(e.length>eb)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=tb(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=nb(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Jl(e,r)){let i=rb(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function ob(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 eu(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function ib(e){return e.startsWith(".")?e.slice(1):e}function tu(e,t){let n=e;if(t.pattern){let o=t.pattern;if(o.includes("*")||o.includes("?")||o.includes("[")){let s=o.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");s=s.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let a=`^${s}$`;if(!ql(a).safe)return n=n.filter(d=>(d.name.includes("/")?d.name.split("/").pop():d.name).includes(o)),n;let l=new RegExp(a,"i");n=n.filter(d=>{let u=d.name.includes("/")?d.name.split("/").pop():d.name;return l.test(u)})}catch{n=n.filter(a=>(a.name.includes("/")?a.name.split("/").pop():a.name).includes(o))}}else n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(o))}let r=t.extensions&&t.extensions.length>0?t.extensions.map(ib):[];return r.length>0&&(n=n.filter(o=>o.type==="directory"||o.extension&&r.includes(o.extension))),t.directoriesOnly&&(n=n.filter(o=>o.type==="directory")),t.filesOnly&&(n=n.filter(o=>o.type==="file")),n}function nu(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 ru(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}function ou(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+tn(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Ot(r)})`}function iu(e,t){let n=e.length,r=t.itemsPerPage||Ie.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);return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:i<o}}}function su(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function au(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`]}async function cu(e){try{let t=Re(e,S.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return sb(e,t.sanitizedPath,n)}catch(t){let n=ke.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode,hints:se(S.LOCAL_VIEW_STRUCTURE,"error")}}}function sb(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=cb(e),s=r&&e.limit&&!ab(e,i)?e.limit*2:1e4,a;try{a=U.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,entryType:lb(e),limit:s})}catch(A){return pb(A,e,t)}let c=a.entries.map(A=>ub(A,n,e.details??!1)),l=tu(c,e),d=e.sortBy??"name";l=l.sort((A,B)=>{let N=0;switch(d){case"size":{let M=A.sizeBytes??(A.size?tn(A.size):0),oe=B.sizeBytes??(B.size?tn(B.size):0);N=M-oe;break}case"time":n&&A.modified&&B.modified?N=A.modified.localeCompare(B.modified):N=A.name.localeCompare(B.name);break;case"extension":N=(A.extension||"").localeCompare(B.extension||"");break;default:N=A.name.localeCompare(B.name);break}return e.reverse?-N:N}),e.limit&&(l=l.slice(0,e.limit));let u=l.length,{paginatedEntries:m,endIdx:p,pagination:f}=iu(l,e),R=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(A=>({...ru(A),path:A.path??`${t.replace(/\/$/,"")}/${A.name}`}))}:{path:t,...nu(m)},b=[...a.warnings,...au({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.`]:[]],g=u===0,C=typeof e.pattern=="string"?e.pattern:void 0,E=(e.extensions?.length??0)>0||!!C,L=l.filter(A=>A.type==="file").length,I=E&&L===0&&!g,k={entryCount:u,path:e.path,extensions:e.extensions,pattern:C},j=g||I?se(S.LOCAL_VIEW_STRUCTURE,"empty",k):["Use localSearchCode to search or localGetFileContent to read discovered files."],P=su(l,m.length,f,p),x=ou(l);return D(lu({...g?{status:"empty"}:{},...R,summary:x,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b},hints:[...j,...P]},e),a.entries.reduce((A,B)=>A+B.path.length,0))}function ab(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t||(e.extensions?.length??0)>0)}function cb(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function lb(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function ub(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:Ot(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=db(e.permissions)),o}function db(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 pb(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=ke.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return _(a,t,{toolName:S.LOCAL_VIEW_STRUCTURE,customHints:o?[`Path not found: ${n}`]:i?[`Permission denied: ${n}`]:[`Cannot access path: ${n}`]})}function lu(e,t){return e}async function uu(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=kn.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await cu(r.data)}}),{toolName:S.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"],peerHints:!0},e)}import{acquirePooledClient as Ru,isLanguageServerAvailable as bu}from"octocode-lsp/manager";import{resolveWorkspaceRootForFile as Su}from"octocode-lsp/workspaceRoot";import{safeReadFile as mb}from"octocode-lsp/validation";var du={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0};function on(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function pu(e,t,n){if(t<=0)return e;let r=await mb(e.uri);if(!r)return e;let o=r.split(/\r?\n/),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,d)=>{let u=s+d+1;return`${u===i+1?">":" "}${String(u).padStart(4," ")}| ${l}`}).join(`
48
+ `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function fb(e,t){return Promise.all(e.map(async n=>({...n,from:await pu(n.from,t,n.fromRanges)})))}async function hb(e,t){return Promise.all(e.map(async n=>({...n,to:await pu(n.to,t)})))}async function Ao(e,t,n,r,o){if(n<=0||!e)return{calls:[],...du};try{let i=await e.getIncomingCalls(t),s=o>0?await fb(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=on(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Ao(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 Lo(e,t,n,r,o){if(n<=0||!e)return{calls:[],...du};try{let i=await e.getOutgoingCalls(t),s=o>0?await hb(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=on(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Lo(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}}}import{readFile as gb}from"node:fs/promises";import{SymbolResolver as yb,SymbolResolutionError as Rb}from"octocode-lsp/resolver";import{LSP_ERROR_CODES as mu}from"octocode-lsp/lspErrorCodes";async function Io(e,t){let n=e.uri,r=Re({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{return{ok:!0,value:{uri:o,absolutePath:o,content:await gb(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:mu.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function fu(e,t){let n=await Io(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 yb({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:bb(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof Rb)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:mu.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 bb(e){return{start:e,end:{line:e.line,character:e.character}}}var Sb=40,Cu=40,Cb=10,Pb=8;async function Pu(e){return X(e.queries||[],async t=>we({toolName:ge,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await kb(t);return Eb(Tb(t,n))}}),{toolName:ge,peerHints:!0,minQueryTimeoutMs:3e4},e)}function Eb(e){return D(e,$(e))}function Tb(e,t){return e.format!=="compact"||!wb(t)?t:_b(t)}function wb(e){return Rt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Rt(e.payload)}function _b(e){return{...e,format:"compact",payload:xb(e.payload)}}function xb(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(hu)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(Lb)}:{locations:(e.locations??[]).map(hu)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Eu(e.root)}:{},direction:e.direction,calls:e.calls.map(Ib),...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(Ab)};case"hover":case"empty":return e}}function Ab(e){if(!Rt(e))return String(e);let t=xe(e,"line"),n=xe(e,"character"),r=xe(e,"endLine"),o=Xe(e,"kind"),i=Xe(e,"name"),s=xe(e,"childCount"),a=Xe(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function hu(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${wu(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function Lb(e){if(!Rt(e))return String(e);let t=Xe(e,"uri"),n=xe(e,"firstLine"),r=xe(e,"firstCharacter"),o=xe(e,"count"),i=Tu(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 Ib(e){if(!Rt(e))return String(e);let t=Xe(e,"direction"),n=Eu(e.item),r=Tu(e,"ranges").map(Ob).join(","),o=xe(e,"rangeCount"),i=xe(e,"rangeSampleCount"),s=Xe(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${wu(s,180)}`:""].filter(Boolean).join(" ")}function Eu(e){if(!Rt(e))return String(e);let t=Xe(e,"name"),n=Xe(e,"kind"),r=Xe(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 Ob(e){return Rt(e)?`${xe(e,"line")}:${xe(e,"character")}`:String(e)}function Rt(e){return typeof e=="object"&&e!==null}function Xe(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 Tu(e,t){let n=e[t];return Array.isArray(n)?n:[]}function wu(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 kb(e){if(e.type==="documentSymbols")return vb(e);let t=await fu(e,ge);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed",s=Array.isArray(t.error.hints)?t.error.hints:void 0;return Qb(e,i,s)}let n=e.workspaceRoot??await Su(t.value.uri);if(!await bu(t.value.uri,n))return Ye(e.type,t.value,"Language server unavailable");let o=await Ru(n,t.value.uri);if(!o)return Ye(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?Oo(e,t.value,"definition","definitionProvider",await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?Oo(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?Oo(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?Fb(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):Ye(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?Mb(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?Nb(e,t.value,o):Ye(e.type,t.value,"callHierarchyProvider unsupported",!0)}}async function vb(e){let t=await Io(e,ge);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Su(t.value.uri),r=await bu(t.value.uri,n),o=r?await Ru(n,t.value.uri):null,i=o?o.hasCapability("documentSymbolProvider")?await o.documentSymbols(t.value.uri,t.value.content):[]:[],s=!!o?.hasCapability("documentSymbolProvider"),a=Hb(Array.isArray(i)?i:[]),c=$b(Array.isArray(i)?i:[]),{pageItems:l,pagination:d}=mr(a,e.page??1,e.itemsPerPage??Sb),u=Bb(a,f=>f.kind),p=s?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(s?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...s?{provider:"documentSymbolProvider"}:{}},summary:{totalSymbols:a.length,returnedSymbols:l.length,topLevelSymbols:c,kinds:u},payload:{kind:"documentSymbols",symbols:l,...p?{empty:p}:{}},pagination:d,hints:[...d.hasMore?[pr(d,"symbols")]:[],...rt("documentSymbols",s)]}}function Oo(e,t,n,r,o){let i=o.length>0,s=o.map(Pr),{pageItems:a,pagination:c}=mr(s,e.page??1,e.itemsPerPage??Cu);return{type:e.type,uri:t.uri,resolvedSymbol:bt(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}:{},hints:[...i&&c.hasMore?[pr(c,"locations")]:[],...rt(e.type,i)]}}function Fb(e,t,n){let r=n.map(l=>{let d=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...d?{isDefinition:!0}:{}}}),o=e.groupByFile?jb(r):void 0,i=o??r.map(Pr),{pageItems:s,pagination:a}=mr(i,e.page??1,e.itemsPerPage??Cu),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider"},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,hints:[...a.hasMore?[pr(a,o?"reference files":"references")]:[],...rt("references",!0)]}}async function Mb(e,t,n){let r=Vb(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"},hints:rt(e.type,o)}}async function Nb(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Ye(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 Ao(n,o,i,new Set([on(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Lo(n,o,i,new Set([on(o)]),e.contextLines??0):s,l=g=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(g.to.uri),d=c.calls.filter(l).length,u=c.calls.filter(g=>!l(g)),m=[...a.calls.map(g=>({direction:"incoming",...g})),...u.map(g=>({direction:"outgoing",...g}))],p=m.map(g=>g.direction==="incoming"?Ub(g,e.contextLines??0):zb(g,e.contextLines??0)),{pageItems:f,pagination:h}=mr(p,e.page??1,e.itemsPerPage??Cb),R=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:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:vo(o),direction:R,calls:f,incomingCalls:a.calls.length,outgoingCalls:u.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...d>0&&{stdlibCallsExcluded:d}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:h,hints:[...h.hasMore?[pr(h,"calls")]:[],...rt(e.type,!0),...a.truncatedByDepth||c.truncatedByDepth?["Calls exist beyond the traversal depth \u2014 increase depth to follow the chain further."]:[]]}}function pr(e,t){let n=Math.min(e.currentPage*e.itemsPerPage,e.totalResults)-(e.currentPage-1)*e.itemsPerPage,r=e.nextPage??e.currentPage+1;return`Page ${e.currentPage}/${e.totalPages} (${n} of ${e.totalResults} ${t}). Next: page=${r}`}function mr(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 Hb(e){let t=[];for(let n of e)_u(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function _u(e,t,n){if(!e||typeof e!="object")return;let r=e,o=Gb(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:ko(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)&&Db.has(ko(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)_u(s,t,i)}}var Db=new Set(["file","module","namespace","package","class","enum","interface","struct"]);function Gb(e){if(gu(e.range))return e.range;let t=e.location;return t&&gu(t.range)?t.range:void 0}function gu(e){if(!e||typeof e!="object")return!1;let t=e;return yu(t.start)&&yu(t.end)}function yu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function $b(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Bb(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function Ub(e,t){let n=xu(e.fromRanges);return{direction:"incoming",item:vo(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Au(e.from,t)}}function zb(e,t){let n=xu(e.fromRanges);return{direction:"outgoing",item:vo(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Au(e.to,t)}}function vo(e){return{name:e.name,kind:ko(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 xu(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>=Pb))break}return n}function Au(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function ko(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 Lu(e,t){return/unavailable/i.test(t)?"serverUnavailable":/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 Qb(e,t,n){let r=e.uri??"";return{type:e.type,uri:r,lsp:{},payload:{kind:"empty",category:Lu(e.type,t),reason:t},hints:n?.length?n:rt(e.type,!1)}}function Ye(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Lu(e,n),reason:n},hints:rt(e,!1)}}function jb(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 Vb(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=>Wb(r)).join(`
49
+ `).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 Wb(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 Fo={hasTool(e){return Mr(e)},getDescription(e){return Fr[e]??""},getToolName(e){return S[e]??String(e)}};var Iu=(e,t=Fo)=>t.getDescription(e);function Kb(e,t){return t.getToolName(e)}function Fe(e,t,n){let r=Kb(t,e);return{...n,name:r,description:Iu(r,e)}}function Yb(e=Fo){let t=Fe(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:xs,inputSchema:As,executionFn:zc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=Fe(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:An,inputSchema:Ts,executionFn:Bc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=Fe(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Ds,inputSchema:Gs,executionFn:il,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=Fe(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Fs,inputSchema:Ms,executionFn:ol,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=Fe(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Ln,inputSchema:Os,executionFn:qc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=Fe(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Us,inputSchema:zs,executionFn:Ll,security:"remote",requiresServerRuntime:!0}}),a=Fe(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Wr,inputSchema:Cs,executionFn:Sc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=Fe(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:tt,inputSchema:Js,executionFn:Zl,security:"basic"}}),l=Fe(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:kn,inputSchema:ta,executionFn:uu,security:"basic"}}),d=Fe(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:On,inputSchema:Ys,executionFn:Hl,security:"basic"}}),u=Fe(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:In,inputSchema:Vs,executionFn:vl,security:"basic"}}),m={name:ge,description:Iu(ge,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:sa,inputSchema:aa,executionFn:Pu,security:"basic",requiresServerRuntime:!0}},p=Fe(e,"LOCAL_BINARY_INSPECT",{isDefault:!1,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Mn,inputSchema:da,executionFn:ac,security:"basic"}});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:d,LOCAL_FETCH_CONTENT:u,LSP_GET_SEMANTIC_CONTENT:m,LOCAL_BINARY_INSPECT:p,ALL_TOOLS:[t,n,r,o,i,s,a,c,l,d,u,m,p]}}var Ae=Yb(),lv=Ae.GITHUB_SEARCH_CODE,uv=Ae.GITHUB_FETCH_CONTENT,dv=Ae.GITHUB_VIEW_REPO_STRUCTURE,pv=Ae.GITHUB_SEARCH_REPOSITORIES,mv=Ae.GITHUB_SEARCH_PULL_REQUESTS,fv=Ae.PACKAGE_SEARCH,hv=Ae.GITHUB_CLONE_REPO,gv=Ae.LOCAL_RIPGREP,yv=Ae.LOCAL_VIEW_STRUCTURE,Rv=Ae.LOCAL_FIND_FILES,bv=Ae.LOCAL_FETCH_CONTENT,Sv=Ae.LSP_GET_SEMANTIC_CONTENT,Cv=Ae.LOCAL_BINARY_INSPECT,Ou=Ae.ALL_TOOLS;import{ContentSanitizer as Xb}from"octocode-security";import{maskSensitiveData as ku}from"octocode-security/mask";function fr(e){let t=e;if(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let r=Xb.sanitizeContent(n.text),o=r.hasSecrets?ku(r.content):ku(n.text);return{...n,text:o}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:nt(t.structuredContent)}}catch{}return t}var Zb="TOOL_CALLBACK_EXCEPTION";function vu(e,t){let n=Jb(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
50
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:Zb,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return fr(r)}catch{return r}}function Jb(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:qb(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 qb(e){try{return JSON.stringify(e)}catch{return}}import{withSecurityValidation as eS,withBasicSecurityValidation as tS}from"octocode-security";function Fu(e,t){let n=eS(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function Mu(e,t){let n=tS(r=>e(r),t);return(r,o)=>n(r,o)}import{releaseAllPooledClients as nS}from"octocode-lsp/manager";var Do=["GitHub","Local","LSP","Package","Other"],Nu=new Map([W.GITHUB_SEARCH_CODE,W.GITHUB_SEARCH_REPOSITORIES,W.GITHUB_SEARCH_PULL_REQUESTS,W.GITHUB_FETCH_CONTENT,W.GITHUB_VIEW_REPO_STRUCTURE,W.GITHUB_CLONE_REPO,W.LOCAL_RIPGREP,W.LOCAL_FIND_FILES,W.LOCAL_FETCH_CONTENT,W.LOCAL_VIEW_STRUCTURE,ge,W.PACKAGE_SEARCH].map((e,t)=>[e,t])),Qe=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},Mo=null,No=null,rS=["id","mainResearchGoal","researchGoal","reasoning"],Bo=new Set([...rS]),oS=["id","researchGoal","reasoning"],Hu=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function iS(e){return async t=>e(t)}function sS(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:iS(t.executionFn),security:t.security,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var Du=Ou.map(sS),aS=Du.map(Bu);function Uo(e){let t=Qo(e);return t?Bu(t):void 0}function sn(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")?"Local":e.startsWith("lsp")?"LSP":e===W.PACKAGE_SEARCH?"Package":"Other"}function cS(e){return[...e].sort((t,n)=>{let r=Do.indexOf(sn(t)),o=Do.indexOf(sn(n));if(r!==o)return r-o;let i=Nu.get(t)??Number.MAX_SAFE_INTEGER,s=Nu.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function lS(e){let t=Uo(e);if(!t)return"{}";try{return JSON.stringify(Ho.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(Ho.toJSONSchema(t.schema),null,2)}}function uS(e){return JSON.stringify(e??{},null,2)}function dS(e){let t=sn(e),n=[...oS];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function pS(){return Hu.map(e=>({...e}))}function mS(){return JSON.stringify(Object.fromEntries(Hu.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function fS(e,t){return t?.tools?.[e]?.description??e}function zo(e){let t=Uo(e);if(!t)return[];let n=Ho.toJSONSchema(t.schema);if(!an(n))return[];let r=at(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Bo.has(i)&&!$o(r[i])):[]);return Go(r,o)}function hS(e){let t=zo(e),n=t.filter(i=>i.required),r=n.length>0?n:t.slice(0,4),o={};for(let i of r)o[i.name]=ES(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===ge&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function gS(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Qe("Tool input must be valid JSON.")}return Gu(e,r,n)}function Gu(e,t,n={}){let r=RS(e,t,n),o=Qo(e);if(!o)throw new Qe(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Qe("Tool input does not match the expected schema.",yS(i.error));return i.data}function yS(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function RS(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(at(t)&&Array.isArray(t.queries))r=t.queries;else if(at(t))r=[t];else throw new Qe('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Qe("At least one query is required.");let o=at(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,l)=>{i=!0,n.onUnknownFields?.(c,l)}},a=r.map((c,l)=>bS(e,l,CS(e,c,l,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new Qe("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function bS(e,t,n,r){let o={...n},i=sn(e),s=r.sourceLabel??"direct tool execution",a=SS(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function SS(e,t){return`Execute ${e} via ${t}`}function CS(e,t,n,r={}){if(!at(t))throw new Qe("Tool input must be a JSON object or an array of objects.");let o=new Set([...zo(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Bo]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function PS(e){let t=[],n=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return n!==void 0&&r!==void 0?t.push(`${n}-${r}`):n!==void 0?t.push(`>=${n}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function $u(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let t=an(e.items)?e.items:void 0;return`array<${t?$u(t):"value"}>`}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Go(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Bo.has(o))continue;let s=an(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:$u(s),constraints:PS(s),description:typeof s.description=="string"?s.description:void 0}),at(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(d=>typeof d=="string"?!$o(s.properties?.[d]):!1):[]);r.push(...Go(s.properties,l,a))}let c=s.type==="array"&&an(s.items)?s.items:void 0;if(c&&at(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(d=>typeof d=="string"?!$o(c.properties?.[d]):!1):[]);r.push(...Go(c.properties,l,a))}}return r}function ES(e,t){if(t.startsWith("array<"))return[e];if(t==="integer"||t==="number")return 1;if(t==="boolean")return!0;if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;switch(e){case"path":return".";case"owner":return"bgauryy";case"repo":return"octocode";case"name":case"packageName":return"react";default:return e}}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function an(e){return at(e)}function $o(e){return an(e)&&"default"in e}async function TS(e,t){let n=Qo(e);if(!n)throw new Error(`Unknown tool: ${e}`);let r=wS(n,t);try{return await _S(n),e===W.GITHUB_CLONE_REPO&&!un()?fr({content:[{type:"text",text:`error: ghCloneRepo is disabled
51
+ message: Set ENABLE_CLONE=true (and ENABLE_LOCAL=true) to enable repository cloning.
52
+ hints:
53
+ - To browse without cloning, use ghViewRepoStructure to list files or ghGetFileContent to read specific files.`}],structuredContent:{status:"error",tool:e,code:"TOOL_DISABLED",error:{message:"ghCloneRepo is disabled \u2014 set ENABLE_CLONE=true (and ENABLE_LOCAL=true) to enable repository cloning."},hints:["To browse without cloning, use ghViewRepoStructure to list files or ghGetFileContent to read specific files."]},isError:!0}):await xS(n,r)}finally{e===ge&&await nS()}}function Bu(e){return{name:e.name,schema:e.schema,inputSchema:e.inputSchema}}function Qo(e){return Du.find(t=>t.name===e)}function wS(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function _S(e){e.requiresServerRuntime&&(Mo||(Mo=Xo()),await Mo),e.requiresProviders&&(No||(No=bs().then(()=>{})),await No)}async function xS(e,t){try{let n=e.security==="remote"?await AS(e,t):await LS(e,t);return fr(n)}catch(n){return vu(e.name,n)}}async function AS(e,t){return Fu(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function LS(e,t){return Mu(e.execute,e.name)(t)}import{completeMetadata as IS}from"@octocodeai/octocode-core";var jo=null;function OS(){return jo||(jo=IS),jo}async function kS(){return OS()}export{Do as DIRECT_TOOL_CATEGORIES,aS as DIRECT_TOOL_DEFINITIONS,Qe as DirectToolInputError,hS as buildDirectToolExampleQuery,TS as executeDirectTool,Uo as findDirectToolDefinition,Qm as formatCallToolResultForOutput,uS as formatDirectToolMetadataSchemaText,mS as formatDirectToolOutputSchemaText,lS as formatDirectToolSchemaText,dS as getDirectToolAutoFilledFields,sn as getDirectToolCategory,fS as getDirectToolDescription,zo as getDirectToolDisplayFields,pS as getDirectToolOutputFields,kS as loadToolContent,Gu as prepareDirectToolInput,gS as prepareDirectToolInputFromJsonText,cS as sortDirectToolNames};