@octocodeai/octocode-tools-core 18.2.0 → 19.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -19
- package/dist/chunks/direct/chunk-3AA4F3QO.js +10 -0
- package/dist/chunks/direct/chunk-43RVQWTG.js +8 -0
- package/dist/chunks/direct/chunk-7DYE654A.js +8 -0
- package/dist/chunks/direct/chunk-A4WMBDEC.js +8 -0
- package/dist/chunks/direct/chunk-AWZG43MA.js +8 -0
- package/dist/chunks/direct/chunk-BICVXQ5F.js +8 -0
- package/dist/chunks/direct/chunk-BMM5H6QF.js +11 -0
- package/dist/chunks/direct/chunk-C6HFNIDL.js +8 -0
- package/dist/chunks/direct/chunk-CBCZVCTZ.js +8 -0
- package/dist/chunks/direct/chunk-CBIKUVP6.js +11 -0
- package/dist/chunks/direct/chunk-CKB2ME2J.js +8 -0
- package/dist/chunks/direct/chunk-DBI23PBG.js +9 -0
- package/dist/chunks/direct/chunk-DBSQWRFS.js +9 -0
- package/dist/chunks/direct/chunk-DKGYPFGX.js +8 -0
- package/dist/chunks/direct/chunk-EOLHXX5I.js +8 -0
- package/dist/chunks/direct/chunk-IFPXDKUV.js +8 -0
- package/dist/chunks/direct/chunk-J3WYA3IJ.js +8 -0
- package/dist/chunks/direct/chunk-MCMOWPYL.js +8 -0
- package/dist/chunks/direct/chunk-MPTAIBY7.js +8 -0
- package/dist/chunks/direct/chunk-NQRDACK3.js +8 -0
- package/dist/chunks/direct/chunk-O5ETB2W5.js +8 -0
- package/dist/chunks/direct/chunk-OA6NU4KO.js +8 -0
- package/dist/chunks/direct/chunk-QKDE2HIF.js +10 -0
- package/dist/chunks/direct/chunk-RRSY2ZPX.js +13 -0
- package/dist/chunks/direct/chunk-UKQLRZEW.js +8 -0
- package/dist/chunks/direct/chunk-USZL65FN.js +8 -0
- package/dist/chunks/direct/chunk-WH6GL3J2.js +8 -0
- package/dist/chunks/direct/chunk-Y5OCKUQX.js +9 -0
- package/dist/chunks/direct/chunk-ZO44CZN5.js +8 -0
- package/dist/chunks/direct/chunk-ZSXRT7JL.js +12 -0
- package/dist/chunks/direct/chunk-ZUNPQVMO.js +8 -0
- package/dist/chunks/direct/execution-3T4B776P.js +9 -0
- package/dist/chunks/direct/execution-5BJNS7D7.js +8 -0
- package/dist/chunks/direct/execution-5O6QHKBR.js +8 -0
- package/dist/chunks/direct/execution-A4NK3BQO.js +8 -0
- package/dist/chunks/direct/execution-K4UOPXRQ.js +9 -0
- package/dist/chunks/direct/execution-SWWZOOA7.js +13 -0
- package/dist/chunks/direct/execution-X4MUJL4L.js +8 -0
- package/dist/chunks/direct/execution-XA6PXPRB.js +8 -0
- package/dist/chunks/direct/historyExecutions-6F3AA5PY.js +14 -0
- package/dist/direct.d.ts +6 -1
- package/dist/direct.js +2 -46
- package/dist/github/canonicalRepo.d.ts +2 -1
- package/dist/github/client.d.ts +3 -8
- package/dist/github/codeSearch/compactFragment.d.ts +7 -0
- package/dist/github/codeSearch.d.ts +2 -3
- package/dist/github/commit.d.ts +8 -0
- package/dist/github/commitDetail.d.ts +20 -0
- package/dist/github/commitSearch.d.ts +17 -0
- package/dist/github/compare.d.ts +15 -0
- package/dist/github/directoryFetch/cacheMetadata.d.ts +25 -0
- package/dist/github/directoryFetch/helpers.d.ts +1 -3
- package/dist/github/directoryFetch/snapshot.d.ts +10 -0
- package/dist/github/fileContentProcess.d.ts +0 -1
- package/dist/github/fileContentRaw/cache.d.ts +9 -0
- package/dist/github/fileContentRaw/fetch.d.ts +1 -1
- package/dist/github/githubAPI.d.ts +19 -2
- package/dist/github/history/commitFiles.d.ts +12 -0
- package/dist/github/issues/fetchers.d.ts +1 -1
- package/dist/github/issues/types.d.ts +3 -1
- package/dist/github/prContentFetcher/collectionPaging.d.ts +27 -0
- package/dist/github/prContentFetcher/comments.d.ts +7 -5
- package/dist/github/prContentFetcher/commits.d.ts +13 -14
- package/dist/github/prContentFetcher/flags.d.ts +0 -1
- package/dist/github/prContentFetcher/transform.d.ts +1 -1
- package/dist/github/prTransformation.d.ts +3 -1
- package/dist/github/queryBuilders/codeAndRepo.d.ts +2 -1
- package/dist/github/repoSearch.d.ts +2 -1
- package/dist/github/repoStructure/fetchOrchestration.d.ts +1 -1
- package/dist/github/repoStructurePagination.d.ts +1 -1
- package/dist/github/repoStructureTree.d.ts +4 -2
- package/dist/graph/advancedOperations.d.ts +2 -2
- package/dist/graph/buildFileGraph.d.ts +8 -13
- package/dist/graph/coverage.d.ts +6 -0
- package/dist/graph/diagnosticSnapshot.d.ts +10 -0
- package/dist/graph/fileImportLinker.d.ts +28 -0
- package/dist/graph/importResolver.d.ts +1 -1
- package/dist/graph/languageImportResolver.d.ts +5 -0
- package/dist/graph/metadataImports.d.ts +7 -0
- package/dist/graph/packageExportTargets.d.ts +11 -0
- package/dist/graph/rustCargoMetadata.d.ts +31 -0
- package/dist/graph/rustCargoProcess.d.ts +16 -0
- package/dist/graph/rustModules.d.ts +7 -0
- package/dist/graph/rustWorkspace.d.ts +5 -0
- package/dist/graph/types.d.ts +94 -3
- package/dist/graph/workspacePackageResolver.d.ts +7 -2
- package/dist/index.d.ts +46 -19
- package/dist/index.js +36 -45
- package/dist/providers/github/GitHubProvider.d.ts +3 -1
- package/dist/providers/github/githubContent.d.ts +3 -2
- package/dist/providers/github/githubPullRequests.d.ts +3 -2
- package/dist/providers/github/githubSearch.d.ts +6 -3
- package/dist/providers/github/githubStructure.d.ts +3 -2
- package/dist/providers/providerQueries.d.ts +4 -0
- package/dist/providers/providerResults.d.ts +29 -1
- package/dist/providers/types.d.ts +0 -2
- package/dist/schema.d.ts +9 -3
- package/dist/schema.js +4 -12
- package/dist/scheme/fields.d.ts +8 -8
- package/dist/scheme/pagination.d.ts +1 -0
- package/dist/serverConfig.d.ts +1 -1
- package/dist/shared/session/index.d.ts +1 -1
- package/dist/shared/session/index.js +1 -1
- package/dist/shared/session/storage.d.ts +0 -1
- package/dist/toolContract/descriptions.d.ts +6 -6
- package/dist/toolContract/input/resources/tools/ghSearch.d.ts +21 -20
- package/dist/toolContract/input/resources/tools/githubHistorySchema.d.ts +14 -6
- package/dist/toolContract/input/resources/tools/githubRepositoriesOperation.d.ts +3 -3
- package/dist/toolContract/input/resources/tools/githubTreeOperation.d.ts +4 -2
- package/dist/toolContract/input/resources/tools/historyCommitInput.d.ts +9 -0
- package/dist/toolContract/input/resources/tools/historyIssueInput.d.ts +4 -4
- package/dist/toolContract/input/resources/tools/historyPullRequestInput.d.ts +13 -5
- package/dist/toolContract/input/resources/tools/localAnalyzeGraph.d.ts +74 -32
- package/dist/toolContract/input/resources/tools/localFilesOperation.d.ts +2 -2
- package/dist/toolContract/input/resources/tools/localSearch.d.ts +44 -44
- package/dist/toolContract/input/resources/tools/localTextOperation.d.ts +1 -1
- package/dist/toolContract/input/resources/tools/localTreeOperation.d.ts +2 -2
- package/dist/toolContract/input/resources/tools/lspGetSemantics.d.ts +11 -2
- package/dist/toolContract/input/resources/tools/npmSearch.d.ts +2 -1
- package/dist/toolContract/metadata.d.ts +1 -1
- package/dist/toolContract/runtime.d.ts +1 -1
- package/dist/toolContract/types.d.ts +0 -1
- package/dist/tools/directToolCatalog/toolCatalogDefinitions.d.ts +2 -4
- package/dist/tools/directToolCatalog/toolInputPreparation.d.ts +2 -5
- package/dist/tools/directToolCatalog.exec.d.ts +10 -7
- package/dist/tools/github_clone_repo/cache.d.ts +0 -2
- package/dist/tools/github_clone_repo/cacheArtifacts.d.ts +3 -1
- package/dist/tools/github_clone_repo/cachePaths.d.ts +3 -2
- package/dist/tools/github_clone_repo/gitCheckout.d.ts +5 -0
- package/dist/tools/github_clone_repo/scheme.d.ts +3 -3
- package/dist/tools/github_clone_repo/types.d.ts +6 -1
- package/dist/tools/github_fetch_content/finalizer/types.d.ts +10 -2
- package/dist/tools/github_fetch_content/scheme.d.ts +3 -4
- package/dist/tools/github_fetch_content/types.d.ts +4 -3
- package/dist/tools/github_search/scheme.d.ts +24 -23
- package/dist/tools/github_search_code/execution.d.ts +1 -1
- package/dist/tools/github_search_code/finalizer/groups.d.ts +1 -1
- package/dist/tools/github_search_code/finalizer/ranking.d.ts +1 -1
- package/dist/tools/github_search_code/scheme.d.ts +3 -3
- package/dist/tools/github_search_pull_requests/contentResponse/commentsShaping.d.ts +4 -1
- package/dist/tools/github_search_pull_requests/contentResponse/contentView.d.ts +3 -0
- package/dist/tools/github_search_pull_requests/contentResponse/fileSurfaces.d.ts +30 -2
- package/dist/tools/github_search_pull_requests/contentResponse/nextCalls.d.ts +1 -7
- package/dist/tools/github_search_pull_requests/contentResponse/pagination.d.ts +14 -2
- package/dist/tools/github_search_pull_requests/historyContinuations.d.ts +1 -1
- package/dist/tools/github_search_pull_requests/historyDiffContinuations.d.ts +2 -0
- package/dist/tools/github_search_pull_requests/historySchemes.d.ts +23 -22
- package/dist/tools/github_search_pull_requests/scheme.d.ts +17 -9
- package/dist/tools/github_search_pull_requests/splitSchemes.d.ts +35 -26
- package/dist/tools/github_search_pull_requests/types.d.ts +5 -0
- package/dist/tools/github_search_repos/execution/pagination.d.ts +0 -17
- package/dist/tools/github_search_repos/execution/queryVariants.d.ts +1 -23
- package/dist/tools/github_search_repos/execution.d.ts +0 -1
- package/dist/tools/github_search_repos/scheme.d.ts +6 -6
- package/dist/tools/github_view_repo_structure/execution.d.ts +1 -1
- package/dist/tools/github_view_repo_structure/scheme.d.ts +6 -5
- package/dist/tools/local_analyze_graph/analysisTypes.d.ts +16 -3
- package/dist/tools/local_analyze_graph/analyzeGraph.d.ts +1 -1
- package/dist/tools/local_analyze_graph/completeness.d.ts +3 -0
- package/dist/tools/local_analyze_graph/deadCodeScan.d.ts +9 -5
- package/dist/tools/local_analyze_graph/rootInference.d.ts +2 -0
- package/dist/tools/local_analyze_graph/scheme.d.ts +13 -25
- package/dist/tools/local_fetch_content/fetchContent/pagination.d.ts +7 -0
- package/dist/tools/local_fetch_content/scheme.d.ts +3 -3
- package/dist/tools/local_find_files/findFiles.d.ts +1 -1
- package/dist/tools/local_find_files/scheme.d.ts +4 -4
- package/dist/tools/local_ripgrep/execution.d.ts +0 -1
- package/dist/tools/local_ripgrep/rankingProfile/rankingProfiles.d.ts +1 -2
- package/dist/tools/local_ripgrep/rankingProfile/rankingResults.d.ts +2 -2
- package/dist/tools/local_ripgrep/rankingProfile/rankingScoring.d.ts +1 -3
- package/dist/tools/local_ripgrep/ripgrepResultBuilder/buildResult.d.ts +0 -4
- package/dist/tools/local_ripgrep/ripgrepResultBuilder/searchNext.d.ts +1 -0
- package/dist/tools/local_ripgrep/scheme.d.ts +13 -5
- package/dist/tools/local_ripgrep/structuralCompleteness.d.ts +9 -0
- package/dist/tools/local_search/execution.d.ts +0 -1
- package/dist/tools/local_search/scheme.d.ts +47 -47
- package/dist/tools/local_view_structure/scheme.d.ts +5 -5
- package/dist/tools/lsp/semantic_content/scheme.d.ts +29 -7
- package/dist/tools/lsp/semantic_content/semanticAnchored.d.ts +2 -9
- package/dist/tools/lsp/semantic_content/semanticEnvelopes/callEnvelopes.d.ts +2 -2
- package/dist/tools/lsp/semantic_content/semanticEnvelopes/envelopeHelpers.d.ts +2 -1
- package/dist/tools/lsp/semantic_content/semanticEnvelopes/locationEnvelopes.d.ts +2 -3
- package/dist/tools/lsp/semantic_content/semanticFileOps/anchor.d.ts +0 -1
- package/dist/tools/lsp/semantic_content/semanticPresentation.d.ts +1 -0
- package/dist/tools/lsp/semantic_content/semanticSnapshot.d.ts +16 -0
- package/dist/tools/lsp/shared/callHierarchyTraversal.d.ts +2 -1
- package/dist/tools/lsp/shared/semanticTypes.d.ts +19 -10
- package/dist/tools/package_search/execution.d.ts +3 -4
- package/dist/tools/package_search/pagination.d.ts +1 -0
- package/dist/tools/package_search/scheme.d.ts +5 -4
- package/dist/tools/providerMappers/codeSearch.d.ts +2 -9
- package/dist/tools/providerMappers/fileContent.d.ts +1 -1
- package/dist/tools/providerMappers/pullRequests.d.ts +24 -4
- package/dist/tools/providerMappers/repoSearch.d.ts +4 -4
- package/dist/tools/providerMappers/repoStructure.d.ts +4 -3
- package/dist/tools/toolAvailability.d.ts +19 -0
- package/dist/tools/toolConfig.d.ts +1 -3
- package/dist/types/toolResults.d.ts +1 -0
- package/dist/utils/contextUtils.d.ts +1 -1
- package/dist/utils/core/types.d.ts +0 -2
- package/dist/utils/exec/npm.d.ts +2 -0
- package/dist/utils/file/byteOffset.d.ts +1 -1
- package/dist/utils/package/common.d.ts +0 -3
- package/dist/utils/package/npm/npmDeprecation.d.ts +1 -2
- package/dist/utils/package/npm/npmDetailsFetchers.d.ts +3 -15
- package/dist/utils/package/npm/npmMappers.d.ts +0 -4
- package/dist/utils/package/npm/npmRegistry.d.ts +9 -1
- package/dist/utils/package/npm/npmSearchStrategies.d.ts +2 -5
- package/dist/utils/package/types.d.ts +3 -0
- package/dist/utils/pagination/types.d.ts +1 -0
- package/dist/utils/response/callToolResult.d.ts +3 -1
- package/package.json +23 -19
- package/dist/errors/pathUtils.d.ts +0 -1
- package/dist/github/directoryFetch.d.ts +0 -3
- package/dist/github/fileContentRaw.d.ts +0 -2
- package/dist/github/issues.d.ts +0 -3
- package/dist/github/prContentFetcher.d.ts +0 -2
- package/dist/github/queryBuilders.d.ts +0 -4
- package/dist/github/repoStructure.d.ts +0 -1
- package/dist/shared/index.d.ts +0 -6
- package/dist/shared/languageSelectors.d.ts +0 -3
- package/dist/toolContract/schemas.d.ts +0 -31
- package/dist/tools/directToolCatalog.d.ts +0 -15
- package/dist/tools/directToolCatalog.meta.d.ts +0 -28
- package/dist/tools/github_search_code/finalizer.d.ts +0 -2
- package/dist/tools/github_search_repos/execution/ranking.d.ts +0 -4
- package/dist/tools/local_ripgrep/rankingProfile.d.ts +0 -35
- package/dist/tools/local_ripgrep/ripgrepResultBuilder.d.ts +0 -2
- package/dist/tools/lsp/semantic_content/index.d.ts +0 -3
- package/dist/tools/lsp/semantic_content/semanticEnvelopes.d.ts +0 -3
- package/dist/tools/lsp/semantic_content/semanticFileOps.d.ts +0 -8
- package/dist/tools/providerMappers.d.ts +0 -11
- package/dist/tools/toolMetadata/baseSchema.d.ts +0 -1
- package/dist/tools/toolMetadata/descriptions.d.ts +0 -1
- package/dist/tools/toolMetadata/proxies.d.ts +0 -4
- package/dist/tools/toolSchemaImports.d.ts +0 -16
- package/dist/utils/exec/spawn.d.ts +0 -2
- package/dist/utils/file/filters.d.ts +0 -2
- package/dist/utils/http/cache.d.ts +0 -5
- package/dist/utils/package/npm.d.ts +0 -2
- package/dist/utils/response/bulk.d.ts +0 -2
package/dist/direct.js
CHANGED
|
@@ -5,49 +5,5 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
import{z as ka}from"zod";var st={GITHUB_SEARCH:"ghSearch",GITHUB_FETCH_CONTENT:"ghGetFileContent",GITHUB_SEARCH_HISTORY:"ghSearchHistory",GITHUB_GET_HISTORY_ITEM:"ghGetHistoryItem",PACKAGE_SEARCH:"npmSearch",GITHUB_CLONE_REPO:"ghCloneRepo",LOCAL_SEARCH:"localSearch",LOCAL_ANALYZE_GRAPH:"localAnalyzeGraph",LOCAL_FETCH_CONTENT:"localGetFileContent",LSP_GET_SEMANTIC_CONTENT:"lspGetSemantics"},si=ka.object({goal:ka.string().optional().describe("What this query should accomplish."),reasoning:ka.string().optional().describe("Why this query advances the goal.")}),En=Object.fromEntries(Object.entries(si.shape).map(([e,t])=>[e,t.description??""]));var JS={ghSearch:["Use only fields listed for the selected operation.","match: code=file|path; repositories=name|description|readme.","code cannot select branch; it searches GitHub's indexed default branch."],localSearch:["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."],localAnalyzeGraph:["dependencies | dependents -> requires file; depth applies.","path -> requires file + target.","deadCode/reachability use entrypoints and includeTests as roots."],localGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString."],lspGetSemantics:["workspaceSymbol needs symbolName and may use workspaceRoot.","documentSymbols/diagnostic need uri.","definition | references | hover | callers | callees | callHierarchy | implementation | typeDefinition | supertypes | subtypes -> requires uri + symbolName + lineHint."],ghGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString.",'type:"directory" materializes; extraction fields read files.'],npmSearch:["Set exactly one of packageName or keywords."]};function ai(e){return[...JS[e]??[]]}var qS={ghSearch:[{name:"code",when:"Search code contents or file paths",requires:["operation"],excludes:["branch"],fields:["keywords","owner","repo","extension","filename","path","language","match","pageSize","page","concise"],example:{operation:"code",keywords:["toolSchemas"],owner:"bgauryy",repo:"octocode"}},{name:"repositories",when:"Discover repositories",requires:["operation"],fields:["keywords","topics","language","owner","stars","forks","goodFirstIssues","updated","created","size","match","sort","pageSize","page","archived","visibility","license","concise"],example:{operation:"repositories",keywords:["octocode"]}},{name:"tree",when:"Browse a known repository tree",requires:["operation","owner","repo"],fields:["owner","repo","branch","path","maxDepth","page","pageSize","include"],example:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}],localSearch:[{name:"text",when:"Search lexical text or regular expressions",requires:["operation","path","searchText"],example:{operation:"text",path:".",searchText:"toolSchemas"}},{name:"structural",when:"Match AST structure",requires:["operation","path","pattern"],example:{operation:"structural",path:".",pattern:"console.log($A)",langType:"typescript"}},{name:"files",when:"Discover paths by name or metadata",requires:["operation","path"],example:{operation:"files",path:".",names:["*.ts"]}},{name:"tree",when:"Browse a directory tree",requires:["operation","path"],example:{operation:"tree",path:".",maxDepth:5}}],localAnalyzeGraph:[{name:"dependencies",when:"Find files imported by a file",requires:["path","operation","file"],example:{path:".",operation:"dependencies",file:"src/index.ts"}},{name:"dependents",when:"Find files importing a file",requires:["path","operation","file"],example:{path:".",operation:"dependents",file:"src/index.ts"}},{name:"path",when:"Find a shortest dependency path",requires:["path","operation","file","target"],example:{path:".",operation:"path",file:"src/a.ts",target:"src/b.ts"}},{name:"cycles",when:"Find dependency cycles",requires:["path","operation"],example:{path:".",operation:"cycles"}},{name:"deadCode",when:"Find unreachable file candidates",requires:["path","operation"],example:{path:".",operation:"deadCode"}},{name:"reachability",when:"Find files unreachable from selected roots",requires:["path","operation","entrypoints"],example:{path:".",operation:"reachability",entrypoints:["src/index.ts"]}}],lspGetSemantics:[{name:"anchored",when:"Query a named symbol near a source line",requires:["uri","type","symbolName","lineHint"],example:{uri:"src/index.ts",type:"definition",symbolName:"main",lineHint:1}},{name:"document",when:"Query a whole document",requires:["uri","type"],example:{uri:"src/index.ts",type:"documentSymbols"}},{name:"workspace",when:"Search symbols across the workspace",requires:["workspaceRoot","type","symbolName"],example:{workspaceRoot:".",type:"workspaceSymbol",symbolName:"Schema"}}]};function Ia(e){return qS[e]??[]}import{z as ci}from"zod";var Yn=100,Qr=1e3,rd=1e8,od=5e4,Be=1e9,Oa=1e5,Ur=20,li=100,jr=1e4,An=50,xt=100,wt=30,va=200,Fa=100;var Ma=1e5,Na=500,ui=1e5,Da=1e3,Ha=20,Ga=100,Ba=20;function pe(e){return{...e,description:e.instructions}}function H(e,t){return ci.number().int().min(e).max(t)}var we=ci.array(ci.string()).optional();function Pe(){return H(1,Qr).default(1)}function De(){return H(1,Qr).optional()}function pi(){return H(0,Yn).optional()}function Zn(){return H(1,Be).optional()}function ze(){return H(0,rd).optional()}function pt(){return H(1,od).optional()}var q=si.shape,eR=new Set(Object.keys(q)),tR={owner:"Repository owner (user or org).",repo:"Repository name, without the owner.",branch:"Branch, tag, or commit SHA; omit for the default branch.",path:"Target path. GitHub tools: repo-relative, exact case, no leading slash. Local tools: absolute path.",page:"Result page, 1-based. Advance only while pagination.hasMore.",itemsPerPage:"Items per result page.",limit:"Total result cap applied before pagination.",pageSize:"Results returned in one page.",contextLines:"Extra source lines around each match/anchor.",charLength:"Content-window length; continue with the returned offset when partial.",charOffset:"Content-window start; copy the returned offset. A partial window cannot prove absence."};function U(e,t,n=""){let r={};for(let o of Object.keys(t)){let i=t[o],s=n?`${n}.${o}`:o,c=n===""&&eR.has(o)?En[s]:e[s]??(i.description?void 0:tR[o]);r[o]=c?i.describe(c):i}return ci.object(r).strict()}function di(e,t){let n=e.fullContent===!0,r=e.matchString!==void 0,o=e.startLine!==void 0||e.endLine!==void 0;n&&r&&t.addIssue({code:"custom",message:"Choose fullContent or matchString.",path:["matchString"]}),n&&o&&t.addIssue({code:"custom",message:"Choose fullContent or startLine/endLine.",path:["startLine"]}),r&&o&&t.addIssue({code:"custom",message:"Choose matchString or startLine/endLine.",path:["startLine"]}),e.startLine===void 0!=(e.endLine===void 0)&&t.addIssue({code:"custom",message:"Set startLine and endLine together.",path:[e.startLine===void 0?"startLine":"endLine"]}),e.startLine!==void 0&&e.endLine!==void 0&&e.endLine<e.startLine&&t.addIssue({code:"custom",message:"Set endLine greater than or equal to startLine.",path:["endLine"]})}import{z as mi}from"zod";import{z as nn}from"zod";var nR={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",path:"Repo path prefix, not a full file path.",match:'For ghSearch operation:"code": "file" returns snippets and character matchIndices; "path" returns paths only. Operation:"repositories" uses text-field names.',extension:'File extension filter, e.g. "ts" (no dot).',filename:"Exact filename filter.",language:'GitHub language filter, e.g. "typescript".',concise:'Flat "owner/repo:path" rows.',limit:"Results per page (paginate with page)."},rn=U(nR,{...q,keywords:we,owner:nn.string().optional(),repo:nn.string().optional(),extension:nn.string().optional(),filename:nn.string().optional(),path:nn.string().optional(),language:nn.string().optional(),match:nn.enum(["file","path"]).default("file"),limit:H(1,xt).default(wt),page:Pe(),concise:nn.boolean().optional()});import{z as Qe}from"zod";var rR={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",topicsToSearch:"ANDed topic filters; metadata can be sparse.",match:'For ghSearch operation:"repositories": text fields to search are name, description, and readme; readme is broader and slower. Operation:"code" uses "file" or "path".',sort:"stars, forks, updated, help-wanted-issues, best-match.",language:'Primary language filter, e.g. "rust".',stars:'Star range: ">100", "10..50".',forks:'Fork range: ">50", "10..100".',goodFirstIssues:'Good-first-issue count range, e.g. ">5".',updated:'Last push date: ">2024-01-01" or "a..b".',created:'Creation date: ">2023-01-01" or "a..b".',size:'Repo size in KB: ">1000", "50..500".',license:'SPDX id, e.g. "mit".',archived:"true = archived only; default excludes archived.",visibility:'"public" or "private" (private needs token scope).',concise:'Flat "owner/repo" rows for triage.',limit:"Results per page (paginate with page)."},jt=U(rR,{...q,keywords:we,topicsToSearch:we,language:Qe.string().optional(),owner:Qe.string().optional(),stars:Qe.string().optional(),forks:Qe.string().optional(),goodFirstIssues:Qe.string().optional(),updated:Qe.string().optional(),created:Qe.string().optional(),size:Qe.string().optional(),match:Qe.array(Qe.enum(["name","description","readme"])).optional(),sort:Qe.enum(["stars","forks","help-wanted-issues","updated","best-match"]).default("best-match"),limit:H(1,xt).default(wt),page:Pe(),archived:Qe.boolean().optional(),visibility:Qe.enum(["public","private"]).optional(),license:Qe.string().optional(),concise:Qe.boolean().optional()});import{z as Jn}from"zod";var oR={path:'Repo-relative directory; ""/"." for root.',branch:"Ref; fallback warning means default branch was used.",maxDepth:"Tree recursion depth.",page:"Advance only on hasMore.",include:"Optional sizes, languages, contributors, branches, or tags; each adds an API call."},Ln=U(oR,{...q,owner:Jn.string(),repo:Jn.string(),branch:Jn.string().optional(),path:Jn.string().optional(),maxDepth:H(0,Ba).optional(),page:Pe(),itemsPerPage:H(1,va).default(Fa),include:Jn.array(Jn.enum(["sizes","languages","contributors","branches","tags"])).optional()});var gv=pe({name:"ghSearch",type:"Github",shortDescription:"Search GitHub code or repositories, or browse a repository tree.",instructions:`Choose operation:"code" for code contents or file paths, "repositories" to discover repositories, or "tree" to browse a known repository.
|
|
9
|
-
Each operation has a strict input branch; fields from other operations are rejected. Use ghGetFileContent only after a path is known. Empty GitHub search results do not prove absence.`,schema:{operation:'Required: "code", "repositories", or "tree".'}}),iR=rn.omit({limit:!0}).extend({match:rn.shape.match.describe('For operation:"code": "file" returns snippets; "path" returns paths only.'),pageSize:rn.shape.limit.describe("Results returned per page."),operation:mi.literal("code").describe("Search code contents or file paths.")}).strict(),sR=jt.omit({topicsToSearch:!0,limit:!0}).extend({topics:jt.shape.topicsToSearch.describe("Repository topics; all must match."),pageSize:jt.shape.limit.describe("Results returned per page."),match:jt.shape.match.describe('For operation:"repositories": fields to search: name, description, or readme.'),operation:mi.literal("repositories").describe("Discover repositories by keywords and repository filters.")}).strict(),aR=Ln.omit({itemsPerPage:!0}).extend({operation:mi.literal("tree").describe("Browse the tree of a known repository."),pageSize:Ln.shape.itemsPerPage.describe("Tree entries returned per page.")}).strict(),za=mi.discriminatedUnion("operation",[iR,sR,aR]);import{z as Pt}from"zod";var cR=pe({name:"ghGetFileContent",type:"Github",shortDescription:"Read a file or a specific region from a GitHub repository.",instructions:`Read a known GitHub path after search or structure discovery; a complete search snippet needs no reread. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
|
|
10
|
-
Choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; continue with the returned charOffset. matchedLines are LSP anchors; match ranges and offsets are not. type:"directory" returns localPath when local access is enabled; otherwise use ghSearch operation:"tree".`,schema:{startLine:"Requires endLine; exclusive with fullContent/matchString.",endLine:"Requires startLine; must be >= startLine.",fullContent:"Whole small file; exclusive with range/match.",matchString:"Anchor returning padded matchRanges and exact matchedLines.",matchStringIsRegex:"Makes matchString a regex.",matchStringCaseSensitive:"Case-sensitive matchString.",type:'"file" reads; "directory" materializes localPath when clone/local access is enabled\u2014otherwise use ghSearch operation:"tree".',forceRefresh:"Bypass the 24h fetch cache and re-read from GitHub.",charOffset:"Copy pagination.nextCharOffset.",minify:'"symbols" outline, "standard" compact, "none" exact.'}}),fi=U(cR.schema,{...q,owner:Pt.string(),repo:Pt.string(),branch:Pt.string().optional(),path:Pt.string(),startLine:Zn(),endLine:Zn(),fullContent:Pt.boolean().optional(),matchString:Pt.string().optional(),matchStringIsRegex:Pt.boolean().optional(),matchStringCaseSensitive:Pt.boolean().optional(),forceRefresh:Pt.boolean().optional(),type:Pt.enum(["file","directory"]).default("file"),contextLines:H(0,Yn).default(5),charOffset:ze(),charLength:pt(),minify:Pt.enum(["none","standard","symbols"]).default("standard")}).superRefine(di);import{z as F}from"zod";var lR=pe({name:"githubHistory",type:"Github",shortDescription:"Search and read GitHub pull requests and commit history.",instructions:`Use for PR/commit archaeology \u2014 not current code (ghSearch operation:"code"/ghGetFileContent). type:"prs" lists/reads PRs; type:"commits" walks history.
|
|
11
|
-
Param relations: list mode uses filters+sort/page; detail mode needs owner+repo+prNumber and content selectors. patches.mode:"selected" requires files or ranges. Body/patch/comment windows continue via returned charOffset/commentBodyOffset; file/comment/commit lists use their page fields. For code identity, clone and use local/LSP.`,schema:{type:'"prs" for pull requests; "commits" for commit history.',keywords:"PR search terms; ignored in commits mode.",match:'PR text fields searched by keywords; ghSearch operation:"code" instead uses match to select file content or paths.',prNumber:"Switches to PR detail mode; needs owner+repo.",issueNumber:"Switches to issue detail mode; needs owner+repo.",concise:"PR list triage; ignored with prNumber.",path:"Commit-mode file/dir prefix; trailing / scopes subtree.",includeDiff:"Commit-mode diffs; costly.",order:"asc+created helps archaeology.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',interactions:'Combined comment+reaction count range (">20").',project:'Project board: "owner/number".',"team-mentions":'Team mention: "org/team-slug".',filePage:"Changed-files page from contentPagination.",commentPage:"Comments page from contentPagination.",commitPage:"PR commits page from contentPagination.",reviewMode:'"full" fetches all PR detail surfaces.',content:"Detail selector for prNumber.","content.body":"Full PR description; windowed by charOffset.","content.changedFiles":"File list with status and +/- counts.","content.patches.mode":'"none", "selected" (cheapest; needs files or ranges), or "all".',"content.patches.ranges":"Line ranges for selected patch hunks.","content.comments.reviewInline":"Inline review comments; in_reply_to_id marks threads.","content.comments.includeBots":"Include bot/CI comments.","content.reviews":"Review verdicts per reviewer.","content.commits":"PR-bound commits selector.",matchString:"Substring filter for body/patch/comment windows.",charOffset:"Body/patch continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" compact patches; "none" exact diff; "symbols" not available.'}}),qn=lR.schema,hi=U(qn,{...q,type:F.enum(["prs","commits"]).default("prs"),since:F.string().optional(),until:F.string().optional(),path:F.string().optional(),branch:F.string().optional(),includeDiff:F.boolean().optional().default(!1),includeAssets:F.boolean().optional(),keywords:F.array(F.string()).optional(),prNumber:H(1,Be).optional(),issueNumber:H(1,Be).optional(),owner:F.string().optional(),repo:F.string().optional(),concise:F.boolean().optional(),state:F.enum(["open","closed","merged"]).optional(),assignee:F.string().optional(),author:F.string().optional(),committer:F.string().optional(),commenter:F.string().optional(),mentions:F.string().optional(),"review-requested":F.string().optional(),"reviewed-by":F.string().optional(),label:F.union([F.string(),F.array(F.string())]).optional(),checks:F.enum(["success","failure","pending"]).optional(),review:F.enum(["approved","changes_requested","required","none"]).optional(),head:F.string().optional(),base:F.string().optional(),created:F.string().optional(),updated:F.string().optional(),closed:F.string().optional(),"merged-at":F.string().optional(),comments:F.string().optional(),reactions:F.string().optional(),draft:F.boolean().optional(),match:F.array(F.enum(["title","body","comments"])).optional(),sort:F.enum(["created","updated","best-match","comments","reactions"]).optional(),order:F.enum(["asc","desc"]).optional(),limit:H(1,xt).default(wt),page:Pe(),archived:F.boolean().optional(),filePage:De(),commentPage:De(),commitPage:De(),reviewMode:F.literal("full").optional(),content:U(qn,{metadata:F.boolean().optional(),body:F.boolean().optional(),changedFiles:F.boolean().optional(),patches:U(qn,{mode:F.enum(["none","selected","all"]).default("none"),files:we,ranges:F.array(U(qn,{file:F.string(),additions:F.array(H(1,Be)).optional(),deletions:F.array(H(1,Be)).optional()},"content.patches.ranges")).optional()},"content.patches").optional(),comments:U(qn,{discussion:F.boolean().optional(),reviewInline:F.boolean().optional(),includeBots:F.boolean().default(!1),file:F.string().optional()},"content.comments").optional(),reviews:F.boolean().optional(),commits:U(qn,{list:F.boolean().optional(),includeFiles:F.boolean().optional()},"content.commits").optional()},"content").optional(),matchString:F.string().optional(),commentBodyOffset:ze(),charOffset:ze(),charLength:pt(),minify:F.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let n=e.content?.patches;if(!n)return;let r=(n.files?.length??0)>0,o=(n.ranges?.length??0)>0,i=r||o;n.mode==="selected"&&!i&&t.addIssue({code:"custom",message:'content.patches.mode="selected" requires non-empty files or ranges.',path:["content","patches","files"]}),n.mode!=="selected"&&i&&t.addIssue({code:"custom",message:'content.patches.files and content.patches.ranges require mode="selected".',path:["content","patches","mode"]})});import{z}from"zod";var uR=pe({name:"ghSearchHistory",type:"Github",shortDescription:"Search GitHub pull requests, or read one PR's files, diffs, and reviews.",instructions:`Use for PR history, diffs, and review context; use code tools for current bytes, commits for history, and issues for issue threads. Conversation is context: prove landed behavior from selected patches or the merge SHA.
|
|
12
|
-
List mode uses search filters; detail mode needs owner, repo, prNumber, and explicit content selectors. Selected patches need files or ranges. Continue windows and lists with returned offsets/pages. Use local/LSP for symbol identity.`,schema:{keywords:"PR search terms.",match:'PR text fields searched by keywords: title, body, comments. ghSearch operation:"code" instead uses match to select file content or paths.',prNumber:"PR detail mode; requires owner+repo.",concise:"PR list triage; list mode only.",state:"open, closed, or merged.",assignee:"Assigned GitHub login.",author:"PR author login.",commenter:"Commenter login.",mentions:"Mentioned login.","review-requested":"Requested reviewer login.","reviewed-by":"Reviewer login.",checks:"success, failure, or pending.",review:"approved, changes_requested, required, or none.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',created:'Created date/range, e.g. ">2024-01-01" or "a..b".',updated:"Updated-date filter (same format as created).",closed:"Closed-date filter (same format as created).","merged-at":"Merged-date filter (same format as created).",head:"Head branch name filter.",base:"Base branch name filter.",label:"Label name(s); multiple are ANDed.",draft:"true = only drafts; false = exclude drafts.",archived:"Include PRs from archived repos.",sort:"created, updated, comments, reactions, best-match.",order:"asc/desc; asc+created helps archaeology.",filePage:"Changed-files page from contentPagination.",commentPage:"Comments page from contentPagination.",commitPage:"PR commits page from contentPagination.",content:"Detail selector for prNumber.","content.body":"Include the PR description body.","content.changedFiles":"Include changed files and +/- counts.","content.patches":"Patch selector for changed files.","content.patches.mode":'"selected" or "all"; selected is cheapest.',"content.patches.files":'Restrict selected patches to these files (mode:"selected").',"content.patches.ranges":"Line ranges for selected patch hunks.","content.patches.ranges.file":"File the line range applies to.","content.patches.ranges.additions":"Added-side line numbers to include.","content.patches.ranges.deletions":"Deleted-side line numbers to include.","content.comments":"Conversation and inline-review selectors.","content.comments.discussion":"Include the PR conversation timeline.","content.comments.reviewInline":"Include inline review threads.","content.comments.includeBots":"Include bot/CI comments.","content.comments.file":"Filter comments to one file path.","content.reviews":"Include review verdicts per reviewer.","content.commits":"PR-bound commits selector.","content.commits.includeFiles":"Attach per-commit file changes.",matchString:"Substring filter for body/patch/comment windows.",charOffset:"Body/patch continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" compact patches; "none" exact diff; "symbols" not available.',pageSize:"PRs or detail-list items returned per page."}}),er=uR.schema,_n=U(er,{...q,keywords:z.array(z.string()).optional(),prNumber:H(1,Be).optional(),owner:z.string().optional(),repo:z.string().optional(),concise:z.boolean().optional(),state:z.enum(["open","closed","merged"]).optional(),assignee:z.string().optional(),author:z.string().optional(),commenter:z.string().optional(),mentions:z.string().optional(),"review-requested":z.string().optional(),"reviewed-by":z.string().optional(),label:z.array(z.string()).optional(),checks:z.enum(["success","failure","pending"]).optional(),review:z.enum(["approved","changes_requested","required","none"]).optional(),head:z.string().optional(),base:z.string().optional(),created:z.string().optional(),updated:z.string().optional(),closed:z.string().optional(),"merged-at":z.string().optional(),comments:z.string().optional(),reactions:z.string().optional(),draft:z.boolean().optional(),match:z.array(z.enum(["title","body","comments"])).optional(),sort:z.enum(["created","updated","best-match","comments","reactions"]).optional(),order:z.enum(["asc","desc"]).optional(),pageSize:H(1,xt).default(wt),page:De(),archived:z.boolean().optional(),filePage:De(),commentPage:De(),commitPage:De(),content:U(er,{body:z.literal(!0).optional(),changedFiles:z.literal(!0).optional(),patches:U(er,{mode:z.enum(["selected","all"]),files:we,ranges:z.array(U(er,{file:z.string(),additions:z.array(H(1,Be)).optional(),deletions:z.array(H(1,Be)).optional()},"content.patches.ranges")).optional()},"content.patches").optional(),comments:U(er,{discussion:z.literal(!0).optional(),reviewInline:z.literal(!0).optional(),includeBots:z.literal(!0).optional(),file:z.string().optional()},"content.comments").optional(),reviews:z.literal(!0).optional(),commits:U(er,{includeFiles:z.literal(!0).optional()},"content.commits").optional()},"content").optional(),matchString:z.string().optional(),commentBodyOffset:ze(),charOffset:ze(),charLength:pt(),minify:z.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let n=["content","filePage","commentPage","commitPage","matchString","commentBodyOffset","charOffset","charLength"],r=["keywords","concise","state","assignee","author","commenter","mentions","review-requested","reviewed-by","label","checks","review","head","base","created","updated","closed","merged-at","comments","reactions","draft","match","sort","order","page","archived"];if(e.prNumber===void 0)for(let c of n)e[c]!==void 0&&t.addIssue({code:"custom",message:`${c} requires prNumber detail mode.`,path:[c]});else{e.owner?.trim()||t.addIssue({code:"custom",message:"owner is required with prNumber.",path:["owner"]}),e.repo?.trim()||t.addIssue({code:"custom",message:"repo is required with prNumber.",path:["repo"]});for(let c of r)e[c]!==void 0&&t.addIssue({code:"custom",message:`${c} is only available in list mode.`,path:[c]})}e.content&&Object.keys(e.content).length===0&&t.addIssue({code:"custom",message:"content needs at least one selector.",path:["content"]});let o=e.content?.patches;if(!o)return;let i=(o.files?.length??0)>0,s=(o.ranges?.length??0)>0,a=i||s;o.mode==="selected"&&!a&&t.addIssue({code:"custom",message:'content.patches.mode="selected" requires non-empty files or ranges.',path:["content","patches","files"]}),o.mode!=="selected"&&a&&t.addIssue({code:"custom",message:'content.patches.files and content.patches.ranges require mode="selected".',path:["content","patches","mode"]})});import{z as ae}from"zod";var pR=pe({name:"ghSearchHistory",type:"Github",shortDescription:"Search GitHub issues, or read one issue's body and comments.",instructions:`Use for bug reports and feature threads; use PR or code tools for those surfaces. List mode uses search filters. Detail mode needs owner, repo, issueNumber, and content selectors; continue bodies/comments with returned offsets and pages.
|
|
13
|
-
GitHub issue search also finds PRs, which are filtered out. totalCount is present only for a complete page; an empty page with hasMore still has a nextPage.`,schema:{keywords:"Issue search terms.",match:"Keyword fields: title, body, comments.",issueNumber:"Issue detail mode; requires owner+repo.",concise:"Issue list triage; list mode only.",state:"open or closed.",assignee:"Assigned GitHub login.",author:"Issue author login.",commenter:"Commenter login.",mentions:"Mentioned login.",archived:"Include issues from archived repos.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',created:'Created date/range, e.g. ">2024-01-01" or "a..b".',updated:"Updated-date filter (same format as created).",closed:"Closed-date filter (same format as created).",label:"Label name(s); multiple are ANDed.",sort:"created, updated, comments, reactions, best-match.",order:"asc/desc; asc+created helps archaeology.",commentPage:"Comments page from contentPagination.",content:"Detail selector for issueNumber.","content.body":"Include the issue description body.","content.comments":"Comment-thread selector.","content.comments.discussion":"Include the comment thread.","content.comments.includeBots":"Include bot/CI comments.",matchString:"Substring filter for body/comment windows.",charOffset:"Body continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" (default) compacts body/comment text; "none" keeps it exact.',pageSize:"Issues or detail comments returned per page."}}),Qa=pR.schema,kn=U(Qa,{...q,owner:ae.string(),repo:ae.string(),keywords:ae.array(ae.string()).optional(),issueNumber:H(1,Be).optional(),concise:ae.boolean().optional(),state:ae.enum(["open","closed"]).optional(),assignee:ae.string().optional(),author:ae.string().optional(),commenter:ae.string().optional(),mentions:ae.string().optional(),label:ae.array(ae.string()).optional(),created:ae.string().optional(),updated:ae.string().optional(),closed:ae.string().optional(),comments:ae.string().optional(),reactions:ae.string().optional(),match:ae.array(ae.enum(["title","body","comments"])).optional(),sort:ae.enum(["created","updated","best-match","comments","reactions"]).optional(),order:ae.enum(["asc","desc"]).optional(),pageSize:H(1,xt).default(wt),page:De(),archived:ae.boolean().optional(),commentPage:De(),content:U(Qa,{body:ae.literal(!0).optional(),comments:U(Qa,{discussion:ae.literal(!0).optional(),includeBots:ae.literal(!0).optional()},"content.comments").optional()},"content").optional(),matchString:ae.string().optional(),commentBodyOffset:ze(),charOffset:ze(),charLength:pt(),minify:ae.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let n=["content","commentPage","matchString","commentBodyOffset","charOffset","charLength"],r=["keywords","concise","state","assignee","author","commenter","mentions","label","created","updated","closed","comments","reactions","match","sort","order","page","archived"];if(e.issueNumber===void 0)for(let o of n)e[o]!==void 0&&t.addIssue({code:"custom",message:`${o} requires issueNumber detail mode.`,path:[o]});else{e.owner?.trim()||t.addIssue({code:"custom",message:"owner is required with issueNumber.",path:["owner"]}),e.repo?.trim()||t.addIssue({code:"custom",message:"repo is required with issueNumber.",path:["repo"]});for(let o of r)e[o]!==void 0&&t.addIssue({code:"custom",message:`${o} is only available in list mode.`,path:[o]})}e.content&&Object.keys(e.content).length===0&&t.addIssue({code:"custom",message:"content needs at least one selector.",path:["content"]})});import{z as Tt}from"zod";var dR=pe({name:"ghSearchHistory",type:"Github",shortDescription:"Walk a GitHub repository's commit history for a path or range.",instructions:`Trace when or why code changed; use code tools for current bytes and PR search for review context. History mode filters by path/date/ref/author; compare mode needs base+head. This tool does not search commit messages.
|
|
14
|
-
For one commit's changes, compare base:"SHA^" to head:"SHA" with includeDiff. Scope diffs to one commit or a tight window. Use a clone and LSP for symbol identity.`,schema:{pageSize:"Commits returned per page (walk with page).",owner:"Repository owner.",repo:"Repository name.",path:"File/dir prefix; trailing / scopes the subtree.",since:'Lower date bound: ISO date or relative window such as "30d".',until:"Upper date bound; same formats as since.",branch:"Ref to walk; defaults to the default branch.",includeDiff:"Attach diffs; prefer one commit or a tight window.",author:"Author login or email.",committer:"Committer login or email.",base:"Compare-mode base ref; set with head.",head:"Compare-mode head ref; set with base.",filePage:"Changed-file page from pagination.nextFilePage.",charOffset:"Patch offset from patchPagination.nextCharOffset.",charLength:"Patch-window length."}}),gi=U(dR.schema,{...q,owner:Tt.string(),repo:Tt.string(),path:Tt.string().optional(),since:Tt.string().optional(),until:Tt.string().optional(),branch:Tt.string().optional(),author:Tt.string().optional(),committer:Tt.string().optional(),base:Tt.string().optional(),head:Tt.string().optional(),pageSize:H(1,100).optional().default(30),includeDiff:Tt.boolean().optional().default(!1),page:Pe(),filePage:De(),charOffset:ze(),charLength:pt()}).superRefine((e,t)=>{(e.base&&!e.head||e.head&&!e.base)&&t.addIssue({code:"custom",path:[e.base?"head":"base"],message:"Set base and head together for compare mode."})});import{z as Ua}from"zod";var mR=pe({name:"npmSearch",type:"NPM",shortDescription:"Look up npm packages and find their source repositories.",instructions:"Resolve npm packages to source repositories. Set exactly one of packageName for exact lookup or keywords for discovery. Follow the repository into GitHub tools.",schema:{keywords:"Discovery terms joined with spaces. Mutually exclusive with packageName.",packageName:"Exact package name; include scope for scoped packages.",page:"Keyword-result page only."}}),yi=U(mR.schema,{...q,packageName:Ua.string().optional(),keywords:Ua.array(Ua.string()).optional(),page:Pe()}).superRefine((e,t)=>{let n=e.keywords?.join(" ").trim();!e.packageName?.trim()&&!n&&t.addIssue({code:"custom",path:["packageName"],message:"Set packageName or keywords."}),e.packageName?.trim()&&n&&t.addIssue({code:"custom",path:["keywords"],message:"Set packageName or keywords, not both."})});import{z as $r}from"zod";var fR=pe({name:"ghCloneRepo",type:"Github",shortDescription:"Clone a GitHub repo or subtree locally for repeated reads, search, or LSP.",instructions:"Best for repeated reads, local AST/regex, or LSP; use ghGetFileContent for one read. Discover a bounded sparsePath first. branch selects the ref and forceRefresh bypasses the cached clone. Pass results[].data.location.localPath to local tools.",schema:{sparsePath:"Bound checkout to a repo-relative file/dir.",forceRefresh:"Bypass cached clone."}}),ja=U(fR.schema,{...q,owner:$r.string(),repo:$r.string(),branch:$r.string().optional(),sparsePath:$r.string().optional(),forceRefresh:$r.boolean().optional()});import{z as dt}from"zod";import{z as Ae}from"zod";var $a={searchText:'Single lexical pattern. regex:"fixed" is literal and "perl" enables advanced syntax.',mode:'Search mode: "discovery" paths; "paginated" snippets; "detailed" context; "structural" AST.',pattern:"Structural code pattern: $X matches one node; $$$ARGS matches a list. Include modifiers or use a kind rule.",rule:"Structural YAML ast-grep rule for relational matches.",regex:'"smart" (default), "fixed" (literal), or "perl" (advanced).',caseMode:'"smart" (default), "sensitive", or "insensitive".',wholeWord:"Match whole words only (text/regex modes).",invertMatch:"Return non-matching lines (text/regex modes).",multiline:'"off" (default), "on", or "dotall" (. spans newlines).',include:"Glob(s) of files to include.",exclude:"Glob(s) of files to exclude.",excludeDir:"Directory names to prune from the walk.",noIgnore:"Also search .gitignored files.",hidden:"Include dot-files.",matchContentLength:"Matched-line characters kept per hit; longer lines are truncated.",maxFiles:"Text: page ceiling. Structural: scan cap; stats report truncation.",maxDepth:"Maximum levels below the search root; 0 means root files.",output:'"content" lines; "files"/"filesWithout" paths; count modes totals; "matchOnly" substrings.',unique:'With output:"matchOnly", deduplicate values or count frequency.',sort:'"relevance" (default), "matchCount", "path", "modified", "accessed", or "created".',sortReverse:"Reverse the sort order.",rankingProfile:'Language tuning for sort:"relevance"; "auto" detects.',langType:'Language/file type, e.g. "ts"; structural mode maps it to include globs.',captureText:"Structural: include verbatim $$$ list captures; ranges remain available when omitted.",maxMatchesPerFile:"Pairs with matchPage.",matchWindow:'Requires output:"matchOnly".',matchPage:"Per-file match page."},at=U($a,{...q,searchText:Ae.string().optional(),path:Ae.string(),mode:Ae.enum(["paginated","discovery","detailed","structural"]).default("paginated"),pattern:Ae.string().optional(),rule:Ae.string().optional(),regex:Ae.enum(["smart","fixed","perl"]).default("smart"),caseMode:Ae.enum(["smart","sensitive","insensitive"]).default("smart"),wholeWord:Ae.boolean().optional(),invertMatch:Ae.boolean().optional(),include:we,exclude:we,excludeDir:we,noIgnore:Ae.boolean().optional(),hidden:Ae.boolean().optional(),contextLines:pi(),matchContentLength:H(1,Ma).default(Na),maxMatchesPerFile:H(1,ui).optional(),maxFiles:H(1,ui).optional(),maxDepth:H(0,Ur).optional(),multiline:Ae.enum(["off","on","dotall"]).default("off"),sort:Ae.enum(["relevance","matchCount","path","modified","accessed","created"]).default("relevance"),sortReverse:Ae.boolean().optional(),rankingProfile:Ae.enum(["auto","typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"]).default("auto"),langType:Ae.string().optional(),captureText:Ae.boolean().optional(),output:Ae.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).default("content"),unique:Ae.enum(["off","list","count"]).default("off"),matchWindow:H(0,200).optional(),matchPage:De(),itemsPerPage:H(1,Da).optional(),page:Pe()}).superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:"Set pattern or rule for structural mode.",path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"Choose pattern or rule, not both.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:"Remove wholeWord in structural mode.",path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:"Remove invertMatch in structural mode.",path:["invertMatch"]});for(let r of["regex","caseMode","multiline"]){let o=r==="multiline"?"off":"smart";e[r]!==o&&t.addIssue({code:"custom",message:`Remove ${r} in structural mode.`,path:[r]})}e.output!=="content"&&t.addIssue({code:"custom",message:"Remove output in structural mode.",path:["output"]}),e.unique!=="off"&&t.addIssue({code:"custom",message:"Remove unique in structural mode.",path:["unique"]})}else(e.pattern||e.rule)&&t.addIssue({code:"custom",message:"Use structural mode with pattern or rule.",path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:"Set searchText for text modes.",path:["searchText"]});e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'Use output:"matchOnly" with matchWindow.',path:["matchWindow"]}),e.unique!=="off"&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'Use output:"matchOnly" with unique.',path:["unique"]})});import{z as Xe}from"zod";var Va={maxDepth:"Maximum levels below path; 0 is direct entries.",minDepth:"Requires <= maxDepth when both set.",names:"Basename globs; ORed.",pathPattern:"Full-path glob.",regex:"Basename Rust regex.",empty:"Match only empty files/dirs.",time:"Time filters using d/h/w/m durations.","time.modifiedWithin":"Modified within this duration, e.g. 2d or 6h.","time.modifiedBefore":"Modified before this duration ago, e.g. 30d.","time.accessedWithin":"Accessed within this duration, e.g. 1w.",size:"Size range, e.g. 100k or 1m.","size.greater":"Minimum file size, e.g. 100k or 1m.","size.less":"Maximum file size, e.g. 500b or 2m.",extensions:'Extensions without dots, e.g. ["ts","tsx"].',excludeDir:"Directory names; generated/vendor dirs are pruned by default. Pass [] to prune nothing.",entryType:'"f" files, "d" dirs.',permissions:"Exact permission filter.",access:'"executable", "readable", or "writable" filter.',detail:'"basic" (default), "modified" (+mtime), or "full" (all metadata).',sortBy:'"modified" (default), "name", "path", or "size".',limit:"Post-sort result cap; pagination stays within it."},Wa=Va,vt=U(Wa,{...q,path:Xe.string(),maxDepth:H(0,li).optional(),minDepth:H(0,li).optional(),names:we,pathPattern:Xe.string().optional(),regex:Xe.string().optional(),empty:Xe.boolean().optional(),time:U(Wa,{modifiedWithin:Xe.string().optional(),modifiedBefore:Xe.string().optional(),accessedWithin:Xe.string().optional()},"time").optional(),size:U(Wa,{greater:Xe.string().optional(),less:Xe.string().optional()},"size").optional(),permissions:Xe.string().optional(),access:Xe.enum(["executable","readable","writable"]).optional(),extensions:we,excludeDir:we,limit:H(1,jr).optional(),detail:Xe.enum(["basic","modified","full"]).default("basic"),sortBy:Xe.enum(["modified","name","path","size"]).default("modified"),entryType:Xe.enum(["f","d"]).optional(),page:Pe(),itemsPerPage:H(1,An).optional()}).superRefine((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"]})});import{z as on}from"zod";var Ka={pattern:"Name glob or substring; use the files operation for regex.",entryType:'"f" files only, "d" dirs only; omit for both.',detail:'"basic" (default), "modified" (+mtime), or "full" (size/perms).',hidden:"Include dot-files/dirs.",recursive:"true enables the default recursive depth; omit with maxDepth for immediate children.",maxDepth:"Recursion depth. Omitted: immediate children, or 5 if recursive:true; maxDepth alone enables recursion, so recursive:true is not required. 0 uses those defaults.",extensions:"Allowlist without dots.",excludeDir:"Directories to prune; [] includes generated/vendor directories.",sortBy:'"name" (default), "size", "time", or "extension".',reverse:"Reverse the sort order.",limit:"Discovery cap before pagination."},Ft=U(Ka,{...q,path:on.string(),detail:on.enum(["basic","modified","full"]).default("basic"),hidden:on.boolean().optional(),sortBy:on.enum(["name","size","time","extension"]).default("name"),reverse:on.boolean().optional(),pattern:on.string().optional(),entryType:on.enum(["f","d"]).optional(),recursive:on.boolean().optional(),extensions:we,excludeDir:we,maxDepth:H(0,Ur).optional(),limit:H(1,jr).optional(),page:Pe(),itemsPerPage:H(1,An).optional()});var Wr={...$a};delete Wr.mode;delete Wr.output;delete Wr.itemsPerPage;delete Wr.sortReverse;var sd={...Ka};delete sd.recursive;var qv=pe({name:"localSearch",type:"Local",shortDescription:"Search local text, syntax, paths, or directory trees through one operation.",instructions:'Choose operation:"text" for lexical anchors, "structural" for AST matches, "files" for path or metadata discovery, and "tree" for directory orientation. Each operation has a strict branch, so do not mix fields across operations. Files/tree prune common generated and vendor directories by default; pass excludeDir:[] to prune nothing. Read exact hits with localGetFileContent and prove symbol identity with lspGetSemantics.',schema:{...Va,...sd,...Wr,operation:'Required branch: "text", "structural", "files", or "tree".',resultView:'Text/structural result shape. Text also supports "paginated", "discovery", and "detailed".',pattern:"Structural AST pattern.",namePattern:"Tree entry name glob or substring.",pathRegex:"Files operation: basename Rust regex.",limit:"Files/tree discovery cap before pagination.",pageSize:"Results returned per page.",sort:"Operation-specific sort order.",reverse:"Reverse the selected sort order."}}),ad=dt.object(at.shape),hR=dt.object(vt.shape),gR=dt.enum(["paginated","discovery","detailed","content","files","filesWithout","countLines","countMatches","matchOnly"]),yR=dt.enum(["content","files","countLines","countMatches","matchOnly"]),bR=ad.omit({pattern:!0,rule:!0,captureText:!0,mode:!0,output:!0,itemsPerPage:!0,sortReverse:!0}).extend({operation:dt.literal("text").describe('Use "text" for lexical search.'),searchText:dt.string().describe("Single lexical pattern."),resultView:gR.optional().default("paginated").describe("Text result shape; paginated is the default."),pageSize:at.shape.itemsPerPage.describe("Matches returned per page."),reverse:at.shape.sortReverse.describe("Reverse the selected sort order."),unique:at.shape.unique.describe('With resultView:"matchOnly", deduplicate values or count frequency.'),matchWindow:at.shape.matchWindow.describe('Requires resultView:"matchOnly".')}).strict(),cd=ad.omit({searchText:!0,pattern:!0,rule:!0,mode:!0,regex:!0,caseMode:!0,wholeWord:!0,invertMatch:!0,multiline:!0,unique:!0,matchWindow:!0,output:!0,itemsPerPage:!0,sortReverse:!0}).extend({operation:dt.literal("structural").describe('Use "structural" for AST matching.'),resultView:yR.optional().default("content").describe("Structural result shape; content is the default."),pageSize:at.shape.itemsPerPage.describe("Matches returned per page."),reverse:at.shape.sortReverse.describe("Reverse the selected sort order.")}).strict(),SR=cd.extend({pattern:dt.string().describe("Structural AST pattern.")}).strict(),RR=cd.extend({rule:dt.string().describe("Structural YAML ast-grep rule.")}).strict(),CR=hR.omit({regex:!0,limit:!0,sortBy:!0,itemsPerPage:!0}).extend({operation:dt.literal("files").describe('Use "files" for path and metadata discovery.'),pathRegex:vt.shape.regex.describe("Basename Rust regex."),limit:vt.shape.limit.describe("Post-sort discovery cap."),sort:vt.shape.sortBy.describe("File sort order."),pageSize:vt.shape.itemsPerPage.describe("Files returned per page.")}).strict(),xR=Ft.omit({pattern:!0,recursive:!0,limit:!0,sortBy:!0,itemsPerPage:!0}).extend({operation:dt.literal("tree").describe('Use "tree" for directory orientation.'),namePattern:Ft.shape.pattern.describe("Entry name glob or substring."),limit:Ft.shape.limit.describe("Discovery cap before pagination."),sort:Ft.shape.sortBy.describe("Tree sort order."),pageSize:Ft.shape.itemsPerPage.describe("Entries returned per page.")}).strict();function id(e,t){if("error"in e)for(let n of e.error.issues)n.code==="custom"&&t.addIssue({code:"custom",message:n.message,path:n.path})}var Xa=dt.union([bR,SR,RR,CR,xR]).superRefine((e,t)=>{if(e.operation==="text"){let n=e.resultView,r={...e,itemsPerPage:e.pageSize,sortReverse:e.reverse};delete r.operation,delete r.resultView,delete r.pageSize,delete r.reverse;let o=["paginated","discovery","detailed"].includes(n)?{...r,mode:n}:{...r,mode:"paginated",output:n};id(at.safeParse(o),t);return}if(e.operation!=="structural"&&e.operation==="files"){let n={...e,regex:e.pathRegex,limit:e.limit,sortBy:e.sort,itemsPerPage:e.pageSize};delete n.operation,delete n.pathRegex,delete n.pageSize,delete n.sort,id(vt.safeParse(n),t)}});import{z as Le}from"zod";var wR="localAnalyzeGraph",rF=pe({name:wR,type:"Local",shortDescription:"Analyze a repository file graph through one bounded operation.",instructions:"Map file topology, not symbol identity. dependencies/dependents need file; path needs file+target; deadCode/reachability accept roots; cycles needs no selector. Import edges and dead-code results are candidates\u2014verify changes and deletions with exact reads plus LSP.",schema:{path:"Absolute repository or package root to scan.",operation:"One bounded operation: deadCode, cycles, dependencies, dependents, path, or reachability.",file:"Repository-relative source file for dependencies, dependents, or path.",target:"Repository-relative destination file for path.",depth:"Traversal depth for dependencies or dependents.",entrypoints:"Repository-relative roots for deadCode or reachability.",includeTests:"Treat test files as reachability roots.",excludeDir:"Directory names to prune from graph construction.",maxFiles:"Maximum source files scanned; truncation is reported.",limit:"Result cap applied before pagination.",page:"Result page, 1-based; advance only while pagination.hasMore.",pageSize:"Results returned per page."}}),Vr=(e,t)=>Le.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Le.number().int().min(e).max(t)),tr=(e,t)=>Le.literal(e).describe(t),nr={...q,path:Le.string().describe("Absolute repository or package root to scan."),excludeDir:Le.array(Le.string()).optional().describe("Directory names to prune from graph construction."),maxFiles:Vr(1,5e4).optional().describe("Maximum source files scanned; truncation is reported."),limit:Vr(1,5e3).optional().describe("Result cap applied before pagination."),page:Vr(1,Qr).optional().default(1).describe("Result page, 1-based."),pageSize:Vr(1,An).optional().describe("Results returned per page.")},ld={entrypoints:Le.array(Le.string()).optional().describe("Repo-relative reachability roots; omit to detect package.json main/exports/bin."),includeTests:Le.boolean().optional().default(!0).describe("Treat tests as reachability roots (default true).")},ud={file:Le.string().describe("Repo-relative source file."),depth:Vr(1,50).optional().default(1).describe("Maximum traversal depth (default 1).")},sn=Le.discriminatedUnion("operation",[Le.object({...nr,...ld,operation:tr("deadCode","Find unreachable or unretained exported symbols and dead SCCs.")}).strict(),Le.object({...nr,operation:tr("cycles","Find strongly connected file components.")}).strict(),Le.object({...nr,...ud,operation:tr("dependencies","Traverse files imported or re-exported by the source file; results include edgeKinds and syntactic confidence.")}).strict(),Le.object({...nr,...ud,operation:tr("dependents","Traverse files that import or re-export the source file; results include edgeKinds and syntactic confidence.")}).strict(),Le.object({...nr,file:Le.string().describe("Repo-relative source file."),target:Le.string().describe("Repo-relative destination file."),operation:tr("path","Find the shortest directed import/re-export path with per-edge provenance.")}).strict(),Le.object({...nr,...ld,operation:tr("reachability","Classify scanned files by reachability from entrypoints.")}).strict()]);import{z as rr}from"zod";var PR=pe({name:"localGetFileContent",type:"Local",shortDescription:"Read a local file or a specific region.",instructions:`Read a known local path after search, find, or structure discovery. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
|
|
15
|
-
Choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; continue with the returned charOffset. matchedLines are LSP anchors; match ranges and character offsets are not. Report fetched bytes only.`,schema:{fullContent:"Whole file; small files only; exclusive with range/match.",matchString:"Anchor returning padded matchRanges and exact matchedLines.",matchStringIsRegex:"Makes matchString a regex.",matchStringCaseSensitive:"Case-sensitive matchString.",startLine:"Requires endLine; exclusive with fullContent/matchString.",endLine:"Requires startLine; must be >= startLine.",charOffset:"Copy pagination.nextCharOffset.",minify:'"symbols" outline, "standard" compact, "none" exact.'}}),bi=U(PR.schema,{...q,path:rr.string(),fullContent:rr.boolean().optional(),matchString:rr.string().optional(),matchStringIsRegex:rr.boolean().optional(),matchStringCaseSensitive:rr.boolean().optional(),startLine:Zn(),endLine:Zn(),contextLines:H(0,Yn).default(5),charOffset:ze(),charLength:pt(),minify:rr.enum(["none","standard","symbols"]).default("standard")}).superRefine(di);import{z as In}from"zod";var TR=pe({name:"lspGetSemantics",type:"Local",shortDescription:"Run LSP semantic queries \u2014 definitions, references, call hierarchy, symbols, type hierarchy, diagnostics.",instructions:`Use a real search/read line anchor for semantic proof. references finds usages; callers incoming calls; callees outgoing calls; callHierarchy both. Fall back to references if call hierarchy is unavailable.
|
|
16
|
-
documentSymbols/diagnostic need uri; workspaceSymbol needs symbolName; other operations need uri+symbolName+lineHint. orderHint resolves same-line names. format:"compact" saves tokens. Empty/unavailable results call for a new anchor or text search.`,schema:{pageSize:"References or symbols returned per page.",page:"Reference/symbol result page.",type:"Identity, usage, hierarchy, hover, symbol, or diagnostic operation.",uri:"Target file path/URI; required for every type except workspaceSymbol.",symbolName:"Bare anchored identifier, or fuzzy workspace symbol query.",lineHint:"Observed line containing symbolName.",orderHint:"Disambiguate repeated symbols on one line.",depth:"Call/type hierarchy depth; 0 is direct only.",includeDeclaration:"references: include the declaration; disable before unused analysis.",groupByFile:"references summary mode.",contextLines:"Lines of surrounding source shown around each result location.",format:'"compact" saves tokens; "structured" has typed locations.',workspaceRoot:"Use when auto-root is wrong."}}),Si=U(TR.schema,{...q,uri:In.string().optional(),type:In.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).default("definition"),symbolName:In.string().min(1).optional(),lineHint:H(1,Be).optional(),orderHint:H(0,Oa).default(0),depth:H(0,Ha).optional(),includeDeclaration:In.boolean().default(!0),groupByFile:In.boolean().optional(),page:Pe(),pageSize:H(1,Ga).optional(),contextLines:pi(),format:In.enum(["structured","compact"]).default("structured"),workspaceRoot:In.string().optional()}).superRefine((e,t)=>{if(e.type==="workspaceSymbol"){e.symbolName||t.addIssue({code:"custom",path:["symbolName"],message:"Set symbolName for workspaceSymbol."});return}e.uri||t.addIssue({code:"custom",path:["uri"],message:"Set uri for file-scoped operations."}),!(e.type==="documentSymbols"||e.type==="diagnostic")&&(e.symbolName||t.addIssue({code:"custom",path:["symbolName"],message:"Set symbolName for anchored operations."}),Number.isInteger(e.lineHint)||t.addIssue({code:"custom",path:["lineHint"],message:"Set lineHint for anchored operations."}))});var Mt=st.LOCAL_ANALYZE_GRAPH,Ue="localSearch",mt=st.GITHUB_SEARCH,de="ghSearchHistory",fe="ghGetHistoryItem",re={GITHUB_SEARCH:st.GITHUB_SEARCH,GITHUB_FETCH_CONTENT:st.GITHUB_FETCH_CONTENT,PACKAGE_SEARCH:st.PACKAGE_SEARCH,GITHUB_CLONE_REPO:st.GITHUB_CLONE_REPO,LOCAL_FETCH_CONTENT:st.LOCAL_FETCH_CONTENT,LOCAL_ANALYZE_GRAPH:st.LOCAL_ANALYZE_GRAPH,LSP_GET_SEMANTIC_CONTENT:st.LSP_GET_SEMANTIC_CONTENT,GITHUB_SEARCH_HISTORY:de,GITHUB_GET_HISTORY_ITEM:fe},be=re.LSP_GET_SEMANTIC_CONTENT,DF=new Set([Ue,re.LOCAL_FETCH_CONTENT,Mt,be]);var pd=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];function $t(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0},...e.lineDeviation!==void 0&&{lineDeviation:e.lineDeviation}}}function Ya(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var je={ghSearch:`Choose operation:"code" for code contents or file paths, "repositories" to discover repositories, or "tree" to browse a known repository.
|
|
17
|
-
Each operation has a strict input branch; fields from other operations are rejected. Use ghGetFileContent only after a path is known. Empty GitHub search results do not prove absence.`,ghGetFileContent:`Read a known GitHub path after search or structure discovery; a complete search snippet needs no reread. A path-only call returns a bounded standard-minified view. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
|
|
18
|
-
Optionally choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; run the returned continuation. matchedLines are LSP anchors; match ranges and offsets are not. type:"directory" returns localPath when local access is enabled; otherwise use ghSearch operation:"tree".`,ghSearchHistory:'Search or list repository history. Choose operation:"pullRequests", "issues", or "commits"; fields from other operations are rejected. Pull-request search may be global, while issue and commit history require owner+repo. Search branches never accept detail identities, content selectors, or diff pagination. Follow a result with ghGetHistoryItem.',ghGetHistoryItem:'Retrieve exact GitHub history. Choose operation:"pullRequest" or "issue" with number, "commit" with ref, or "compare" with base+head. Every branch requires owner+repo and rejects fields from other branches. PR/issue content and commit/compare diffs keep their branch-specific page and character windows; copy returned continuations exactly.',npmSearch:"Resolve npm packages to source repositories. Set exactly one of packageName for exact lookup or keywords for discovery. Follow the repository into GitHub tools.",ghCloneRepo:"Best for repeated reads, local AST/regex, or LSP; use ghGetFileContent for one read. Discover a bounded sparsePath first; complete is relative to that requested scope. branch selects the ref and forceRefresh bypasses the cached clone. Pass results[].data.location.localPath to local tools.",localSearch:'Choose operation:"text" for lexical anchors, "structural" for AST matches, "files" for path or metadata discovery, and "tree" for directory orientation. Each operation has a strict branch, so do not mix fields across operations. Files/tree prune common generated and vendor directories by default; pass excludeDir:[] to prune nothing. Read exact hits with localGetFileContent and prove symbol identity with lspGetSemantics.',localAnalyzeGraph:"Map file topology, not symbol identity. dependencies/dependents need file; path needs file+target; deadCode/reachability accept roots; cycles needs no selector. Import edges and dead-code results are candidates\u2014verify changes and deletions with exact reads plus LSP.",localGetFileContent:`Read a known local path after search, find, or structure discovery. A path-only call returns a bounded standard-minified view. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
|
|
19
|
-
Optionally choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; run the returned continuation. matchedLines are LSP anchors; match ranges and character offsets are not. Report fetched bytes only.`,lspGetSemantics:`Use a real search/read line anchor for semantic proof. references finds usages; callers incoming calls; callees outgoing calls; callHierarchy both. Fall back to references if call hierarchy is unavailable.
|
|
20
|
-
documentSymbols/diagnostic need uri; workspaceSymbol needs symbolName; other operations need uri+symbolName+lineHint. orderHint resolves same-line names. format:"compact" saves tokens. Empty/unavailable results call for a new anchor or text search.`};import{z as or}from"zod";function M(e,t){return or.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,or.number().int().min(e).max(t))}var he=M(1,1e3).optional().default(1),ir=M(0,100).optional(),sr=M(1,1e9).optional(),Ye=or.preprocess(e=>typeof e=="number"&&Number.isFinite(e)?Math.max(e,0):e,or.number().nonnegative().refine(Number.isSafeInteger,"Expected a safe non-negative integer")),AR={responseCharOffset:Ye.optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:M(1,5e4).optional().describe("Full-response char window.")};function X(e,t={}){let{maxQueries:n=5}=t;return or.object({queries:or.array(e).min(1).max(n).describe("Parallel queries; response rows use matching zero-based indexes."),...AR}).strict()}import{z as dd}from"zod";function LR(e,t){return e?.description&&!t.description?t.describe(e.description):t}function md(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=LR(e.shape[r],o);return n}function _R(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function fd(e,t){if(!t?.length)return e;let n=new Set(t);return dd.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function oe(e,t={},n={}){let r=fd(e,n.omit);return _R(r,md(r,t)).strict()}function ce(e,t={},n={}){let r=fd(e,n.omit);return dd.object({...r.shape,...md(r,t)}).strict()}var Ri=oe(ja),Za=X(Ri);import{z as IR}from"zod";import{z as Et}from"zod";var gd=["fullContent","matchString","matchStringIsRegex","matchStringCaseSensitive","startLine","endLine"],kR=[...gd,"contextLines","charOffset","charLength","minify"];function yd(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)))}function Ci(e,t){return e.description?t.describe(e.description):t}function Se(e,t){let n=e[t];if(!n)throw new TypeError(`Expected schema field: ${t}`);return n}function Re(e,t){return Se(e,t).nonoptional()}function hd(e,t){let n=yd(e.shape,[...gd,...t?["type"]:[]]),r=t?{type:t}:{},o=Ci(Se(e.shape,"fullContent"),Et.literal(!1).optional()),i=Ci(Se(e.shape,"fullContent"),Et.literal(!0)),s=Et.object({...n,...r,fullContent:o}).strict(),a=Et.object({...n,...r,fullContent:i}).strict(),c=Et.object({...n,...r,fullContent:o,matchString:Re(e.shape,"matchString"),matchStringIsRegex:Se(e.shape,"matchStringIsRegex"),matchStringCaseSensitive:Se(e.shape,"matchStringCaseSensitive")}).strict(),l=Et.object({...n,...r,fullContent:o,startLine:Re(e.shape,"startLine"),endLine:Re(e.shape,"endLine")}).strict().superRefine((u,p)=>{typeof u.startLine=="number"&&typeof u.endLine=="number"&&u.endLine<u.startLine&&p.addIssue({code:"custom",path:["endLine"],message:"Set endLine greater than or equal to startLine."})});return[s,a,c,l]}function xi(e,t={}){if(!t.githubDirectoryMode)return Et.union(hd(e));let n=Ci(Se(e.shape,"type"),Et.literal("file").optional()),r=Ci(Se(e.shape,"type"),Et.literal("directory")),o=yd(e.shape,[...kR,"type"]),i=Et.object({...o,type:r}).strict();return Et.union([...hd(e,n),i])}var OR=IR.enum(["none","standard","symbols"]).optional(),bd={startLine:sr,endLine:sr,contextLines:ir,charOffset:Ye.optional(),charLength:M(1,5e4).optional(),minify:OR},vR=ce(fi,bd),Xr=oe(fi,bd),Ja=X(xi(vR,{githubDirectoryMode:!0}));function ec(e){return typeof e=="string"&&e.trim().length>0}function qa(e){return Array.isArray(e)&&e.some(ec)}function FR(e){return e.operation==="code"?qa(e.keywords)||["owner","path","extension","filename","language"].some(t=>ec(e[t])):e.operation==="repositories"?qa(e.keywords)||qa(e.topics)||["owner","language","stars","forks","goodFirstIssues","updated","created","size","visibility","license"].some(t=>ec(e[t]))||typeof e.archived=="boolean":!0}var ar=za.superRefine((e,t)=>{FR(e)||t.addIssue({code:"custom",path:["operation"],message:`${e.operation} needs at least one search term or scope filter`})}),tc=X(ar,{maxQueries:5});import{z as MR}from"zod";var Sd={limit:M(1,100).optional(),page:he.default(1),match:MR.enum(["file","path"]).default("file")},NR=oe(rn,Sd),DR=X(ce(rn,Sd));import{z as nc}from"zod";var Rd={type:nc.enum(["prs","commits","issues"]).optional(),prNumber:M(1,1e9).optional(),issueNumber:M(1,1e9).optional(),pageSize:M(1,100).optional().default(30),match:nc.array(nc.enum(["title","body","comments"])).optional(),page:he.default(1),filePage:M(1,1e3).optional(),commentPage:M(1,1e3).optional(),commitPage:M(1,1e3).optional(),charOffset:Ye.optional(),commentBodyOffset:Ye.optional(),charLength:M(1,5e4).optional()},HR=ce(hi,Rd),rc=oe(hi,Rd),GR=X(HR);import{z as Ei}from"zod";import{z as $e}from"zod";function lr(e,t,n){let r=e.safeParse(t);if(!r.success)for(let o of r.error.issues)n.addIssue({code:"custom",message:o.message,path:o.path})}function Cd(e){let t=e;for(;t instanceof $e.ZodOptional||t instanceof $e.ZodDefault;)t=t.unwrap();if(!(t instanceof $e.ZodObject))throw new TypeError("Expected an object schema");return t}function xd(e){let t=e;for(;t instanceof $e.ZodOptional||t instanceof $e.ZodDefault;)t=t.unwrap();if(!(t instanceof $e.ZodArray))throw new TypeError("Expected an array schema");return t}function ur(e,t){return e.description?t.describe(e.description):t}var wd={pageSize:M(1,100).optional().default(30),page:M(1,1e3).optional()},Pd={...wd,filePage:M(1,1e3).optional(),commentPage:M(1,1e3).optional(),commitPage:M(1,1e3).optional(),charOffset:Ye.optional(),commentBodyOffset:Ye.optional(),charLength:M(1,1e5).optional()},L0=oe(_n,Pd).superRefine((e,t)=>lr(_n,e,t)),cr=ce(_n,Pd),Td=Se(cr.shape,"content"),Ed=Cd(Td),Ad=Se(Ed.shape,"patches"),an=Cd(Ad),Ld=ur(Se(an.shape,"mode"),$e.literal("selected")),zR=ur(Se(an.shape,"mode"),$e.literal("all")),QR=ur(Se(an.shape,"files"),xd(Se(an.shape,"files")).min(1)),UR=ur(Se(an.shape,"ranges"),xd(Se(an.shape,"ranges")).min(1)),jR=$e.object({mode:Ld,files:QR,ranges:Se(an.shape,"ranges")}).strict(),$R=$e.object({mode:Ld,files:Se(an.shape,"files"),ranges:UR}).strict(),WR=$e.object({mode:zR}).strict(),VR=Ed.extend({patches:ur(Ad,$e.union([jR,$R,WR]).optional())}),ic=cr.omit({prNumber:!0,filePage:!0,commentPage:!0,commitPage:!0,content:!0,matchString:!0,commentBodyOffset:!0,charOffset:!0,charLength:!0}),KR=ic.superRefine((e,t)=>lr(_n,e,t)),Pi=cr.omit({keywords:!0,concise:!0,state:!0,assignee:!0,author:!0,commenter:!0,mentions:!0,"review-requested":!0,"reviewed-by":!0,label:!0,checks:!0,review:!0,head:!0,base:!0,created:!0,updated:!0,closed:!0,"merged-at":!0,comments:!0,reactions:!0,draft:!0,match:!0,sort:!0,order:!0,page:!0,archived:!0}).extend({owner:Re(cr.shape,"owner"),repo:Re(cr.shape,"repo"),prNumber:Re(cr.shape,"prNumber"),content:ur(Td,VR.optional())}),XR=Pi.superRefine((e,t)=>lr(_n,e,t)),_0=X($e.union([KR,XR])),_d={...wd,commentPage:M(1,1e3).optional(),charOffset:Ye.optional(),commentBodyOffset:Ye.optional(),charLength:M(1,1e5).optional()},k0=oe(kn,_d).superRefine((e,t)=>lr(kn,e,t)),oc=ce(kn,_d),Yr=oc.omit({issueNumber:!0,commentPage:!0,content:!0,matchString:!0,commentBodyOffset:!0,charOffset:!0,charLength:!0}),YR=Yr.superRefine((e,t)=>lr(kn,e,t)),Ti=oc.omit({keywords:!0,concise:!0,state:!0,assignee:!0,author:!0,commenter:!0,mentions:!0,label:!0,created:!0,updated:!0,closed:!0,comments:!0,reactions:!0,match:!0,sort:!0,order:!0,page:!0,archived:!0}).extend({issueNumber:Re(oc.shape,"issueNumber")}),ZR=Ti.superRefine((e,t)=>lr(kn,e,t)),I0=X($e.union([YR,ZR])),kd={page:he.default(1),pageSize:M(1,100).optional().default(30),filePage:he.optional(),charOffset:Ye.optional(),charLength:M(1,1e5).optional()};function JR(e,t){(e.base&&!e.head||e.head&&!e.base)&&t.addIssue({code:"custom",path:[e.base?"head":"base"],message:"compare mode requires base and head together"})}var O0=oe(gi,kd).superRefine(JR),wi=ce(gi,kd),sc=wi.omit({base:!0,head:!0}),qR=sc,pr=wi.omit({branch:!0,since:!0,until:!0,author:!0,committer:!0,page:!0}).extend({base:Re(wi.shape,"base"),head:Re(wi.shape,"head")}),eC=pr,v0=X($e.union([qR,eC]));var On=e=>Ei.literal(e).describe("Required operation selector."),dr=e=>Re(e,"owner"),mr=e=>Re(e,"repo"),tC=ic.extend({operation:On("pullRequests")}).strict(),nC=Yr.extend({operation:On("issues"),owner:dr(Yr.shape),repo:mr(Yr.shape)}).strict(),ac=sc.omit({includeDiff:!0,filePage:!0,charOffset:!0,charLength:!0}),rC=ac.extend({operation:On("commits"),owner:dr(ac.shape),repo:mr(ac.shape)}).strict(),fr=Ei.discriminatedUnion("operation",[tC,nC,rC]).describe("Search or list GitHub pull requests, issues, or commits using one strict operation branch."),pc=X(fr),cc=Pi.omit({prNumber:!0}),oC=cc.extend({operation:On("pullRequest"),owner:dr(cc.shape),repo:mr(cc.shape),number:Pi.shape.prNumber}).strict(),lc=Ti.omit({issueNumber:!0}),iC=lc.extend({operation:On("issue"),owner:dr(lc.shape),repo:mr(lc.shape),number:Ti.shape.issueNumber}).strict(),uc=pr.omit({base:!0,head:!0}),sC=uc.extend({operation:On("commit"),owner:dr(uc.shape),repo:mr(uc.shape),ref:Ei.string().min(1).describe("Commit SHA or ref to retrieve exactly.")}).strict(),aC=pr.extend({operation:On("compare"),owner:dr(pr.shape),repo:mr(pr.shape)}).strict(),Wt=Ei.discriminatedUnion("operation",[oC,iC,sC,aC]).describe("Retrieve one GitHub pull request, issue, commit, or ref comparison using one strict operation branch."),dc=X(Wt);import{z as Id}from"zod";var Od={limit:M(1,100).optional(),page:he.default(1),match:Id.array(Id.enum(["name","description","readme"])).optional()},cC=oe(jt,Od),lC=X(ce(jt,Od));var vd={maxDepth:M(0,20).optional(),page:he.default(1),itemsPerPage:M(1,200).optional()},pC=oe(Ln,vd),dC=X(ce(Ln,vd));import{z as Fn}from"zod";var Fd={page:he,pageSize:M(1,100).optional().describe("Packages returned per keyword-discovery page."),keywords:Fn.array(Fn.string()).optional()};function mc(e,t){let n=Array.isArray(e.keywords)?e.keywords.join(" ").trim():e.keywords?.trim();!e.packageName?.trim()&&!n&&t.addIssue({code:"custom",path:["packageName"],message:"provide packageName or keywords"}),e.packageName?.trim()&&n&&t.addIssue({code:"custom",path:["keywords"],message:"provide packageName or keywords, not both"}),e.packageName?.trim()&&e.pageSize!==void 0&&t.addIssue({code:"custom",path:["pageSize"],message:"pageSize is only available for keyword discovery"})}var fc=oe(yi,Fd).superRefine(mc),Ai=ce(yi,Fd,{strict:!0}),Md=Ai.omit({packageName:!0,keywords:!0,pageSize:!0}).shape,mC=Fn.object({...Md,packageName:Re(Ai.shape,"packageName")}).strict().superRefine((e,t)=>mc(e,t)),fC=Fn.object({...Md,keywords:Fn.array(Fn.string()).min(1).describe(Se(Ai.shape,"keywords").description??""),pageSize:Se(Ai.shape,"pageSize")}).strict().superRefine((e,t)=>mc(e,t)),hc=X(Fn.union([mC,fC]),{maxQueries:5});import{z as hC}from"zod";var gC=hC.enum(["none","standard","symbols"]).optional(),Nd={startLine:sr,endLine:sr,contextLines:ir.default(5),charOffset:Ye.optional(),charLength:M(1,5e4).optional(),minify:gC},yC=ce(bi,Nd),Zr=oe(bi,Nd),gc=X(xi(yC),{maxQueries:5});import{z as yc}from"zod";var Dd={maxDepth:M(0,100).optional(),minDepth:M(0,100).optional(),limit:M(1,1e4).optional(),page:he.default(1),itemsPerPage:M(1,50).optional(),excludeDir:yc.array(yc.string()).optional()},Hd=yc.object(Object.fromEntries(Object.entries(vt.shape).filter(([e])=>e!=="regexType")));function bC(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 SC=ce(Hd,Dd),RC=oe(Hd,Dd).superRefine(bC),CC=X(SC,{maxQueries:5});var Sc=X(sn,{maxQueries:5});import{z as cn}from"zod";var xC=["paginated","discovery","detailed","structural"],wC=["semanticRanking"],Gd={mode:cn.enum(xC).optional().default("paginated"),searchText:cn.string().optional(),output:cn.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content"),pattern:cn.string().optional(),maxDepth:M(0,20).optional(),rule:cn.string().optional(),captureText:cn.boolean().optional(),contextLines:ir,matchContentLength:M(1,1e5).optional().default(500),maxMatchesPerFile:M(1,1e5).optional(),maxFiles:M(1,1e5).optional(),matchPage:he.optional(),itemsPerPage:M(1,1e3).optional(),page:he.default(1),unique:cn.enum(["off","list","count"]).optional().default("off")},PC={...Gd,semanticRanking:cn.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},TC=ce(at,PC),EC=oe(at,Gd,{strict:!0,omit:wC}),hr=EC.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let n=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(n){let r=n[0].slice(2);t.addIssue({code:"custom",message:`\`${n[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),AC=X(TC,{maxQueries:5});import{z as Bd}from"zod";var zd={excludeDir:Bd.array(Bd.string()).optional(),maxDepth:M(0,20).optional(),limit:M(1,1e4).optional(),page:he.default(1),itemsPerPage:M(1,50).optional()},LC=ce(Ft,zd),_C=oe(Ft,zd),kC=X(LC,{maxQueries:5});import{z as Ud}from"zod";function Rc(e,t){let{pageSize:n,reverse:r,...o}=e,i={...o,...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{sortReverse:r}:{}};return t==="paginated"||t==="discovery"||t==="detailed"?{...i,mode:t}:{...i,mode:"paginated",output:t}}var[IC,OC,vC,FC,MC]=Xa.options,Qd=Ud.enum(["content","files","countMatches"]).optional().default("content").describe("Structural result shape; content is the default."),gr=Ud.union([IC,OC.extend({resultView:Qd}),vC.extend({resultView:Qd}),FC,MC]),Cc=X(gr,{maxQueries:5});import{z as ln}from"zod";var NC=M(1,1e9),DC=M(0,1e5).optional(),HC=["structured","compact"],jd={type:ln.enum(pd).default("definition"),symbolName:ln.string().min(1).max(1024).optional(),lineHint:NC.optional(),orderHint:DC,depth:M(0,20).optional(),includeDeclaration:ln.boolean().optional().default(!0),page:he,pageSize:M(1,100).optional(),contextLines:M(0,100).optional(),format:ln.enum(HC).optional().default("structured")},un=ce(Si,jd),GC=["definition","references","callers","callees","callHierarchy","hover","typeDefinition","implementation","supertypes","subtypes"],BC=["documentSymbols","diagnostic"],zC=un.extend({type:ln.enum(GC).optional(),uri:Re(un.shape,"uri"),symbolName:Re(un.shape,"symbolName"),lineHint:Re(un.shape,"lineHint")}),QC=un.extend({type:ln.enum(BC),uri:Re(un.shape,"uri")}),UC=un.extend({type:ln.literal("workspaceSymbol"),symbolName:Re(un.shape,"symbolName")}),Jr=oe(Si,jd),xc=X(ln.union([zC,QC,UC]),{maxQueries:5});var qr=[{name:mt,title:"GitHub Search",description:je.ghSearch,schema:ar,inputSchema:tc},{name:re.GITHUB_FETCH_CONTENT,title:"GitHub File Content Fetch",description:je.ghGetFileContent,schema:Xr,inputSchema:Ja},{name:de,title:"GitHub History Search",description:je.ghSearchHistory,schema:fr,inputSchema:pc},{name:fe,title:"GitHub History Item",description:je.ghGetHistoryItem,schema:Wt,inputSchema:dc},{name:re.PACKAGE_SEARCH,title:"Package Search",description:je.npmSearch,schema:fc,inputSchema:hc},{name:re.GITHUB_CLONE_REPO,title:"Clone / Fetch GitHub Repository Locally",description:je.ghCloneRepo,schema:Ri,inputSchema:Za},{name:Ue,title:"Local Search",description:je.localSearch,schema:gr,inputSchema:Cc},{name:Mt,title:"Local Analyze Graph",description:je.localAnalyzeGraph,schema:sn,inputSchema:Sc},{name:re.LOCAL_FETCH_CONTENT,title:"Local Fetch Content",description:je.localGetFileContent,schema:Zr,inputSchema:gc},{name:be,title:"Get Semantic Content",description:je.lspGetSemantics,schema:Jr,inputSchema:xc}];var wc=["GitHub","Local Code","Package","Other"],$d=new Map([mt,de,fe,re.GITHUB_FETCH_CONTENT,re.GITHUB_CLONE_REPO,Ue,Mt,re.LOCAL_FETCH_CONTENT,be,re.PACKAGE_SEARCH].map((e,t)=>[e,t])),ft=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},jC=["goal","reasoning"],eo=new Set([...jC]);function $C(e){return{name:e.name,title:e.title,description:e.description,schema:e.schema,inputSchema:e.inputSchema}}var Tc=qr.map(e=>$C(e)),Wd=[...Tc];function We(e){return Tc.find(t=>t.name===e)}function Pc(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===re.PACKAGE_SEARCH?"Package":"Other"}function WC(e){return[...e].sort((t,n)=>{let r=wc.indexOf(Pc(t)),o=wc.indexOf(Pc(n));if(r!==o)return r-o;let i=$d.get(t)??Number.MAX_SAFE_INTEGER,s=$d.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}import{z as Vd}from"zod";var VC=["goal","reasoning"];function KC(e){let t=We(e);if(!t)return"{}";try{return JSON.stringify(Vd.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Vd.toJSONSchema(t.schema,{io:"input"}),null,2)}}function XC(e){return JSON.stringify(e??{},null,2)}function YC(e){return We(e)?[...VC]:[]}function ZC(e,t){return We(e)?.description??e}import{z as Xd}from"zod";function to(e){let t=We(e);if(!t)return[];let n=Xd.toJSONSchema(t.schema,{io:"input"});if(!Nt(n))return[];let r=Lc(n),o=ex(r),i=tx(r,o);return Ec(o,i)}function Yd(e,t){let n=We(e);if(!n)return new Set;let r=Xd.toJSONSchema(n.schema,{io:"input"});if(!Nt(r))return new Set;let o=Lc(r),i=o.filter(a=>JC(a,t)),s=i.length>0?i:o;return new Set(s.flatMap(a=>ht(a.properties)?Object.keys(a.properties):[]))}function JC(e,t){if(!ht(e.properties))return!0;for(let[n,r]of Object.entries(t)){let o=e.properties[n];if(Nt(o)&&("const"in o&&r!==o.const||Array.isArray(o.enum)&&!o.enum.some(i=>i===r)))return!1}return!0}function qC(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 Li(e){if("const"in e)return`enum(${String(e.const)})`;if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Nt(e.items)?e.items:void 0;return`array<${n?Li(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Nt).map(Li).filter(r=>r!=="value");if(n.length>0)return[...new Set(n)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Lc(e){return ht(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(Nt).flatMap(n=>Lc(n))}function ex(e){let t=new Map;for(let n of e)if(ht(n.properties))for(let[r,o]of Object.entries(n.properties)){if(!Nt(o))continue;let i=t.get(r)??[];i.push(o),t.set(r,i)}return Object.fromEntries([...t].map(([n,r])=>{let o=r.filter(s=>"const"in s).map(s=>s.const);return o.length===r.length?[n,{enum:[...new Set(o)],description:n==="operation"?"Required operation selector.":r[0]?.description}]:new Set(r.map(Li)).size>1?[n,{anyOf:r}]:[n,r[0]??{}]}))}function tx(e,t){if(e.length===0)return new Set;let n=e.map(o=>new Set(Array.isArray(o.required)?o.required:[])),r=[...n[0]??new Set].filter(o=>n.every(i=>i.has(o)));return new Set(r.filter(o=>!eo.has(o)&&!Ac(t[o])))}function Ec(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&eo.has(o))continue;let s=Nt(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Li(s),constraints:qC(s),description:typeof s.description=="string"?s.description:void 0}),ht(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!Ac(s.properties?.[u]):!1):[]);r.push(...Ec(s.properties,l,a))}let c=s.type==="array"&&Nt(s.items)?s.items:void 0;if(c&&ht(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!Ac(c.properties?.[u]):!1):[]);r.push(...Ec(c.properties,l,a))}}return r}function Zd(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[Kd(e,n)]}return Kd(e,t)}function Kd(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return e}}function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nt(e){return ht(e)}function Ac(e){return Nt(e)&&"default"in e}function Jd(e){return e!==mt?[]:[{label:"code search",query:{operation:"code",keywords:["localSearch"],owner:"bgauryy",repo:"octocode",pageSize:5}},{label:"repository search",query:{operation:"repositories",keywords:["code research"],language:"TypeScript",pageSize:5}},{label:"repository tree",query:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}]}function qd(e){let t=Jd(e);return t.length>0?t:e===de?[{label:"PR search (list)",query:{operation:"pullRequests",owner:"bgauryy",repo:"octocode",keywords:["localSearch"],concise:!0,pageSize:5}},{label:"issue search (list)",query:{operation:"issues",owner:"bgauryy",repo:"octocode",keywords:["schema"],state:"open",pageSize:5}},{label:"commit history",query:{operation:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"6m",pageSize:10}}]:e===re.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===Ue?[{label:"text anchors",query:{operation:"text",path:"/ABS/repo/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural matches",query:{operation:"structural",path:"/ABS/repo/src",pattern:"eval($X)",langType:"typescript"}},{label:"file discovery",query:{operation:"files",path:"/ABS/repo",names:["package.json"],entryType:"f"}},{label:"tree orientation",query:{operation:"tree",path:"/ABS/repo/src",maxDepth:2}}]:e===re.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"/ABS/repo/packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"/ABS/repo/packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===Mt?[{label:"dead code from detected entrypoints",query:{operation:"deadCode",path:"/ABS/repo",limit:20}},{label:"cycles",query:{operation:"cycles",path:"/ABS/repo",limit:20}},{label:"dependencies of one file",query:{operation:"dependencies",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"dependents of one file",query:{operation:"dependents",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"shortest dependency path",query:{operation:"path",path:"/ABS/repo",file:"src/index.ts",target:"src/responses.ts"}},{label:"reachability from detected entrypoints",query:{operation:"reachability",path:"/ABS/repo",limit:20}}]:e===re.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===fe?[{label:"pull request detail",query:{operation:"pullRequest",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,patches:{mode:"all"}}}},{label:"issue detail",query:{operation:"issue",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,comments:{discussion:!0}}}},{label:"exact commit",query:{operation:"commit",owner:"bgauryy",repo:"octocode",ref:"main"}},{label:"compare two refs (base...head)",query:{operation:"compare",owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===re.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{keywords:["schema","validation"],page:1}}]:e===be?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function em(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function nx(e){let t=qd(e);if(t.length>0)return t.map(r=>({...r,command:em(e,r.query)}));let n=ox(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:em(e,n)}]}function rx(e){return nx(e)[0]?.query??{}}function ox(e){if(!We(e))return{};let t=to(e),n=t.filter(i=>!i.name.includes(".")),r=ix(n),o={};for(let i of r)o[i.name]=Zd(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===be&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}var tm=4,_c=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),nm=new Set(["page","itemsPerPage","limit","pageSize","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function ix(e){let t=e.filter(i=>i.required),n=new Map;for(let i of t)n.set(i.name,i);let r=e.filter(i=>!i.required&&sx(i)).sort(ax),o=Math.max(tm,t.length);for(let i of r){if(n.size>=o)break;n.set(i.name,i)}return n.size>0?[...n.values()]:e.filter(i=>!nm.has(i.name)).filter(i=>i.type!=="boolean").slice(0,tm)}function sx(e){return nm.has(e.name)||e.type==="boolean"?!1:cx(e)?_c.has(e.name):!0}function ax(e,t){let n=_c.get(e.name)??Number.MAX_SAFE_INTEGER,r=_c.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function cx(e){return e.constraints?.includes("default ")===!0}import{z as im}from"zod";import{z as lx}from"zod";function _i(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rm(e){return _i(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(_i).flatMap(rm)}function ux(e){let t=We(e)?.schema;if(!t)return new Map;let n=lx.toJSONSchema(t),r=new Map;for(let o of rm(n)){if(!_i(o.properties))continue;let i=o.properties.operation;if(!_i(i)||typeof i.const!="string")continue;let s=r.get(i.const)??new Set;for(let a of Object.keys(o.properties))["goal","reasoning","operation"].includes(a)||s.add(a);r.set(i.const,s)}return new Map([...r].map(([o,i])=>[o,[...i]]))}function kc(e){if(e==="ghSearch"){let[t,...n]=ai(e);return[...t?[t]:[],"code and repositories need at least one search term or scope filter.",...n]}return e==="localSearch"?["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."]:e==="ghSearchHistory"?["Choose pullRequests, issues, or commits; fields cannot cross operations.","issues and commits require owner+repo; pullRequests may search globally.","Search/list operations reject exact identities, content, and diff pagination."]:e==="ghGetHistoryItem"?["Every operation requires owner+repo.","pullRequest and issue need number; commit needs ref; compare needs base+head.","Fields and pagination axes cannot cross operations."]:ai(e)}function om(e){let t=ux(e);return(e==="ghSearchHistory"?[{name:"pullRequests",when:"Search or list pull requests",requires:["operation"],example:{operation:"pullRequests",keywords:["schema"]}},{name:"issues",when:"Search or list issues",requires:["operation","owner","repo"],example:{operation:"issues",owner:"o",repo:"r"}},{name:"commits",when:"List commit history",requires:["operation","owner","repo"],example:{operation:"commits",owner:"o",repo:"r"}}]:e==="ghGetHistoryItem"?[{name:"pullRequest",when:"Retrieve one pull request",requires:["operation","owner","repo","number"],example:{operation:"pullRequest",owner:"o",repo:"r",number:1}},{name:"issue",when:"Retrieve one issue",requires:["operation","owner","repo","number"],example:{operation:"issue",owner:"o",repo:"r",number:1}},{name:"commit",when:"Retrieve one commit",requires:["operation","owner","repo","ref"],example:{operation:"commit",owner:"o",repo:"r",ref:"main"}},{name:"compare",when:"Compare two refs",requires:["operation","owner","repo","base","head"],example:{operation:"compare",owner:"o",repo:"r",base:"main",head:"next"}}]:Ia(e)).map(r=>({...r,...e==="localSearch"&&r.name==="structural"?{requires:["operation","path"]}:{},...e==="lspGetSemantics"&&r.name==="workspace"?{requires:["type","symbolName"]}:{},...t.has(r.name)?{fields:t.get(r.name)}:{}}))}function px(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new ft("Tool input must be valid JSON.")}return sm(e,r,n)}function sm(e,t,n={}){let r=fx(e,t,n),o=We(e);if(!o)throw new ft(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new ft("Check the query fields.",[...dx(e),...mx(i.error)]);return i.data}function dx(e){if(e==="npmSearch")return kc(e).slice(0,1);if(e==="localSearch"){let t=om(e).map(n=>n.name);return t.length>0?[`operation must be one of ${t.map((n,r)=>r===t.length-1&&t.length>1?`or ${n}`:n).join(", ")}.`]:[]}if(e==="lspGetSemantics"){let t=kc(e);return t.length>0?[t.join(" ")]:[]}return[]}function mx(e){let t=n=>{let r=n.errors;if(n.code!=="invalid_union"||!Array.isArray(r))return[n];let o=r.filter(s=>Array.isArray(s));return o.length===0?[n]:o.reduce((s,a)=>a.length<s.length?a:s).map(s=>({...s,path:[...n.path,...s.path]}))};return e.issues.flatMap(t).map(n=>`${n.path.length>0?n.path.join("."):"input"}: ${n.message}`)}function fx(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(ht(t)&&Array.isArray(t.queries))r=t.queries;else if(ht(t))r=[t];else throw new ft('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new ft("At least one query is required.");let o=ht(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>hx(e,Rx(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function hx(e,t,n){let r={...t},o=n.sourceLabel??"direct tool execution",i=gx(e,o);return(typeof r.goal!="string"||r.goal.trim().length===0)&&(r.goal=i),(typeof r.reasoning!="string"||r.reasoning.trim().length===0)&&(r.reasoning=`Executed via ${o} tool command`),r}function gx(e,t){return`Execute ${e} via ${t}`}function yx(e,t){let n=e.length+1,r=t.length+1,o=Array.from({length:n*r},()=>0);for(let i=0;i<n;i++)o[i*r]=i;for(let i=0;i<r;i++)o[i]=i;for(let i=1;i<n;i++)for(let s=1;s<r;s++){let a=e[i-1]===t[s-1]?0:1;o[i*r+s]=Math.min(o[(i-1)*r+s]+1,o[i*r+s-1]+1,o[(i-1)*r+s-1]+a)}return o[n*r-1]}function bx(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),l=yx(n,c);if(c.includes(n)||n.includes(c)){l<o&&(r=a,o=l);continue}if(n.length<3)continue;let u=Math.max(2,Math.floor(a.length/3));l<=u&&l<s&&(i=a,s=l)}return r??i}var Sx={npmSearch:{name:"packageName"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri",itemsPerPage:"pageSize",limit:""},localGetFileContent:{filePath:"path"},localSearch:{itemsPerPage:"pageSize",maxResults:["maxFiles","limit","pageSize"],keywords:"searchText",language:"langType",regexType:"regex",sortBy:"sort",sortReverse:"reverse"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:"minify"},ghSearch:{itemsPerPage:"pageSize",limit:"",topicsToSearch:"topics"},localAnalyzeGraph:{itemsPerPage:"pageSize",maxResults:"limit",maxDepth:"depth"}};function Rx(e,t,n,r={}){if(!ht(t))throw new ft("Tool input must be a JSON object or an array of objects.");let o=new Set([...to(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...am(We(e)?.schema),...eo]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}if(s.length>0&&o.size>0&&(r.onUnknownFields?.(s,n),r.rejectUnknownFields===!0)){let a=Yd(e,t),c=s.map(l=>{let u=Sx[e]?.[l],d=(Array.isArray(u)?u:u===void 0?[]:[u]).find(m=>a.has(m))??bx(l,a);return d?`'${l}' \u2192 did you mean '${d}'?`:""}).filter(Boolean);throw new ft(`Unknown field(s): ${s.join(", ")}`,[...c,`Remove unknown field(s) from query ${n+1}: ${s.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return i}function am(e){if(!e)return[];if(e instanceof im.ZodObject)return Object.keys(e.shape);let t=e.options,n=e instanceof im.ZodUnion?e.options:Array.isArray(t)?t:[];return n.length>0?[...new Set(n.flatMap(r=>am(r)))]:[]}function pn(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function yr(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let n=new Date;return t.getTime()-n.getTime()<300*1e3}function ki(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var no=new Map,Cx=300*1e3;function xx(e){let t=pn(e),n=no.get(t);return!n||Date.now()-n.cachedAt>=Cx?!1:n.credentials?!yr(n.credentials):!0}function Ic(e){e?no.delete(pn(e)):no.clear()}function cm(e){let t=pn(e);if(xx(t))return no.get(t).credentials}function lm(e,t){let n=pn(e);no.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as dm,readFileSync as mm,writeFileSync as fm,unlinkSync as oD,statSync as _x,chmodSync as kx}from"node:fs";import{createCipheriv as Ix,createDecipheriv as Ox,randomBytes as hm}from"node:crypto";import{existsSync as wx,mkdirSync as Px}from"node:fs";import{join as gt}from"node:path";import{getOctocodeHome as Tx}from"@octocodeai/config";var Ex=448;function ro(){return Tx(process.env)}function Dt(){return Je}var Je=ro(),Vt={home:Je,config:gt(Je,".octocoderc"),credentials:gt(Je,"credentials.json"),key:gt(Je,".key"),session:gt(Je,"session.json"),stats:gt(Je,"stats.json"),tmp:gt(Je,"tmp"),clone:gt(Je,"tmp","clone"),tree:gt(Je,"tmp","tree"),response:gt(Je,"tmp","response"),repos:gt(Je,"tmp","clone"),cliConfig:gt(Je,"config.json"),lspConfig:gt(Je,"lsp-servers.json")};function um(){wx(Vt.home)||Px(Vt.home,{recursive:!0,mode:Ex})}import{z as Oe}from"zod";var Ax=Oe.object({token:Oe.string(),tokenType:Oe.literal("oauth"),scopes:Oe.array(Oe.string()).optional(),refreshToken:Oe.string().optional(),expiresAt:Oe.string().optional(),refreshTokenExpiresAt:Oe.string().optional()}),Lx=Oe.object({hostname:Oe.string(),username:Oe.string(),token:Ax,gitProtocol:Oe.enum(["ssh","https"]),createdAt:Oe.string(),updatedAt:Oe.string()}),pm=Oe.object({version:Oe.number(),credentials:Oe.record(Oe.string(),Lx)});var gm=Vt.home,oo=Vt.credentials,Nn=Vt.key,ym="aes-256-gcm",vx=16;function Dn(){um()}function bm(){if(Dn(),dm(Nn))return _x(Nn).mode&511&63&&kx(Nn,384),Buffer.from(mm(Nn,"utf8"),"hex");let e=hm(32);return fm(Nn,e.toString("hex"),{mode:384}),e}function Oc(e){let t=bm(),n=hm(vx),r=Ix(ym,t,n),o=r.update(e,"utf8","hex");o+=r.final("hex");let i=r.getAuthTag();return`${n.toString("hex")}:${i.toString("hex")}:${o}`}function vc(e){let t=bm(),[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"hex"),s=Buffer.from(r,"hex"),a=Ox(ym,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function Ii(){if(Dn(),!dm(oo))return{version:1,credentials:{}};try{let e=mm(oo,"utf8"),t=vc(e),n=JSON.parse(t),r=pm.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Sm(e){Dn();let t=Oc(JSON.stringify(e,null,2));fm(oo,t,{mode:384})}import{refreshToken as Fx}from"@octokit/oauth-methods";import{request as Mx}from"@octokit/request";var io="178c6fc778ccc68e1d6a",br="github.com";function Nx(e){return e.replace(/\b(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9]{36,}\b/g,"***MASKED***").replace(/\b[a-zA-Z0-9]{40,}\b/g,"***MASKED***")}function Dx(e){return e==="github.com"||e===br?"https://api.github.com":`https://${e}/api/v3`}async function Rm(e,t=br,n=io){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(ki(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Fx({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:Mx.defaults({baseUrl:Dx(t)})}),i={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,i),{success:!0,username:r.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?Nx(o.message):"Token refresh failed"}}}async function Cm(e,t=br,n=io){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!yr(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Rm(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as Bx}from"@octocodeai/config";import{execFile as Hx}from"child_process";var Gx=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Fc(e){return new Promise(t=>{let n=["auth","token"];e&&n.push("--hostname",e);let r=process.env.PATH??"",o=new Set(r.split(":")),i=Gx.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Hx("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Mc=null;function xm(e){Mc=e}function zx(){if(!Mc)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Mc}async function Oi(e){let t=e?.hostname??br,n=e?.clientId??io,r=e?.getGhCliToken??Fc,o=Bx();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await zx().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
|
|
21
|
-
`)}return null}async function wm(e){let t=pn(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Ii();return r.credentials[t]=n,Sm(r),Ic(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Nc(e="github.com",t){let n=pn(e);if(!t?.bypassCache){let i=cm(n);if(i!==void 0)return i}let o=Ii().credentials[n]||null;return lm(n,o),o}async function Pm(e,t){let n=await Nc(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await wm(n),!0):!1}async function Tm(e,t){return Cm({getCredentials:Nc,updateToken:Pm},e,t)}xm({getTokenWithRefresh:Tm});import vi from"node:os";import $D from"node:path";var $x=vi.platform()==="win32",Wx=vi.platform()==="darwin",Vx=vi.platform()==="linux",Kx=vi.homedir();import{randomUUID as SH}from"node:crypto";import{existsSync as km,readFileSync as Im,writeFileSync as qx,unlinkSync as rH,renameSync as ew}from"node:fs";import{isPersistentStorageEnabled as Om,isStatsEnabled as vm}from"@octocodeai/config";import{z as Y}from"zod";var Xx=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),Yx=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),Fi=Y.record(Y.string(),Y.number()).default({}),Zx=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:Fi,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:Fi}),Mi=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:Fi,charsSavedByTool:Y.record(Y.string(),Xx).default({}),githubCacheHits:Yx.default({hits:{},rateLimits:0}),packageRegistryFailures:Fi,totalUsage:Zx.optional()}),Em=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:Mi.optional()}),Am=Y.object({version:Y.literal(1),stats:Mi});function Lm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Jx(e){let t=e.charsSavedByTool??{},n=e.githubCacheHits??{hits:{},rateLimits:0},r=e.rateLimitsByProvider??{},o=e.packageRegistryFailures??{},i=Object.values(t).reduce((s,a)=>({rawChars:s.rawChars+a.rawChars,responseChars:s.responseChars+a.responseChars,savedChars:s.savedChars+a.savedChars,charSavingsCalls:s.charSavingsCalls+a.calls}),{rawChars:0,responseChars:0,savedChars:0,charSavingsCalls:0});return{toolCalls:e.toolCalls,errors:e.errors,rateLimits:e.rateLimits,rateLimitsByProvider:r,...i,githubCacheHits:Lm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Lm(o),packageRegistryFailuresByRegistry:o}}function dn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Jx(t)}}function Sr(){return dn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var so=Vt.session,ao=Vt.stats;function _m(e,t){let n=`${e}.tmp`;qx(n,JSON.stringify(t,null,2),{mode:384}),ew(n,e)}function tw(e){let t=JSON.parse(e),n=Am.safeParse(t);if(n.success)return dn(n.data.stats);let r=Mi.safeParse(t);return r.success?dn(r.data):null}function nw(){if(!km(ao))return Sr();try{let e=Im(ao,"utf8");return tw(e)??Sr()}catch{return Sr()}}function Dc(e){if(!Om())return;Dn(),vm()&&_m(ao,{version:e.version,stats:dn(e.stats)});let{stats:t,...n}=e;_m(so,n)}function Fm(){if(!Om()||!km(so))return null;try{let e=Im(so,"utf8"),t=JSON.parse(e),n=Em.safeParse(t);return n.success?{...n.data,stats:vm()?nw():Sr()}:null}catch{return null}}var rw=6e4,mn=null,co=!1,Hc=null,Mm=!1,Nm=null,Dm=null,Hm=null,Gc=!1;function ow(){Mm||(Mm=!0,Nm=()=>{Ni()},Dm=()=>{Ni()},Hm=()=>{Ni()},process.on("exit",Nm),process.on("SIGINT",Dm),process.on("SIGTERM",Hm))}function iw(){Hc||(Hc=setInterval(()=>{co&&mn&&(Dc(mn),co=!1)},rw),Hc.unref())}function Gm(){if(mn)return mn;let e=Fm();return e&&(mn=e),e}function Bm(e){mn=e,co=!0,ow(),iw()}function Ni(){if(!Gc&&co&&mn){Gc=!0;try{Dc(mn),co=!1}catch{}finally{Gc=!1}}}function sw(e){return dn(e)}function aw(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let i=n[r]??{rawChars:0,responseChars:0,savedChars:0,calls:0};n[r]={rawChars:i.rawChars+o.rawChars,responseChars:i.responseChars+o.responseChars,savedChars:i.savedChars+o.savedChars,calls:i.calls+o.calls}}return n}function zm(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function cw(e,t){if(!t)return e;let n={...e.hits};for(let[r,o]of Object.entries(t.hits??{}))n[r]=(n[r]??0)+o;return{hits:n,rateLimits:e.rateLimits+(t.rateLimits??0)}}function fn(e){let t=Gm();if(!t)return{success:!1,session:null};let n=sw(t.stats),r=dn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:zm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:aw(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:cw(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:zm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Bm(o),{success:!0,session:o}}function Bc(e=1){return fn({rateLimits:e})}function zc(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return fn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function Qc(e,t=1){return fn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function Uc(e=1){return fn({githubCacheHits:{hits:{},rateLimits:e}})}import{z as Ce}from"zod";var lw=Ce.looseObject({$schema:Ce.string().optional(),version:Ce.number().int().optional(),github:Ce.record(Ce.string(),Ce.unknown()).optional(),local:Ce.record(Ce.string(),Ce.unknown()).optional(),tools:Ce.record(Ce.string(),Ce.unknown()).optional(),network:Ce.record(Ce.string(),Ce.unknown()).optional(),lsp:Ce.record(Ce.string(),Ce.unknown()).optional(),output:Ce.record(Ce.string(),Ce.unknown()).optional()});import{existsSync as uw,readdirSync as pw,lstatSync as dw}from"node:fs";import{join as mw}from"node:path";function Di(e){if(!uw(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=pw(r)}catch{continue}for(let i of o){let s=mw(r,i);try{let a=dw(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}import{getConfigSync as wf}from"@octocodeai/config";var Hn="18.2.0";var jc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},lo={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"}},uo={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})`}},hw={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"}},hn={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}`}},gn={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"}},Ve={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}`}},gw={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}`}},po={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},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"}},yw={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}`}},oG={...jc,...lo,...uo,...hw,...hn,...gn,...Ve,...gw,...po,...yw};import{maskSensitiveData as EP}from"@octocodeai/octocode-engine/mask";import{mkdirSync as gf,readFileSync as hP,renameSync as Sf,rmSync as Rf,statSync as gP,writeFileSync as yP}from"node:fs";import{join as Jc}from"node:path";import{isPersistentStorageEnabled as bP}from"@octocodeai/config";import{existsSync as go,readFileSync as Lw,writeFileSync as _w,mkdirSync as kw,rmSync as ho,readdirSync as Iw,statSync as Ow}from"node:fs";import{join as yn}from"node:path";import{join as Hi}from"node:path";import{createHash as Qm}from"node:crypto";function Gi(e){return Hi(e,"tmp","clone")}function Bi(e){return Hi(e,"tmp","tree")}function bw(e){return e?`__sp_${Qm("sha256").update(e).digest("hex").substring(0,6)}`:""}function Sw(e){if(!/[\\/]/.test(e))return e;let t=Qm("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function $c(e,t,n,r,o){let i=`${Sw(r)}${bw(o)}`;return Hi(Gi(e),t,n,i)}function mo(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new Error("Tree cache identity must be a 40-character commit SHA.");return Hi(Bi(e),t,n,r.toLowerCase())}import{readFileSync as Rw,readdirSync as Cw,renameSync as xw,rmSync as $m,statSync as Wm,writeFileSync as ww}from"node:fs";import{join as Rr}from"node:path";var Pw=900*1e3,Um=300*1e3,Vm=".octocode-lock.json";function Tw(e){return typeof e=="object"&&e!==null}function jm(e){try{return Cw(e)}catch{return[]}}function Wc(e,t=process.pid,n=Date.now()){try{ww(Rr(e,Vm),JSON.stringify({pid:t,createdAt:n}),{encoding:"utf8",mode:384})}catch{}}function Ew(e){try{let t=JSON.parse(Rw(Rr(e,Vm),"utf8"));return!Tw(t)||!Number.isInteger(t.pid)||t.pid<=0||typeof t.createdAt!="number"?null:{pid:t.pid,createdAt:t.createdAt}}catch{return null}}function Aw(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function zi(e,t=Date.now()){let n,r=Ew(e);if(r){if(n=r.createdAt,t-n<=Um||Aw(r.pid))return!1}else{try{n=Wm(e).mtimeMs}catch{return!1}if(t-n<=Um)return!1}let o=`${e}.stale-${process.pid}-${t}`;try{return xw(e,o),$m(o,{recursive:!0,force:!0}),!0}catch{return!1}}function Vc(e,t=Date.now()){let n=Rr(e,"tmp","clone-tmp"),r=0;for(let i of jm(n)){let s=Rr(n,i);try{let a=Wm(s);if(t-a.mtimeMs<=Pw)continue;$m(s,{recursive:!0,force:!0}),r++}catch{}}let o=Rr(e,"tmp","clone-locks");for(let i of jm(o))zi(Rr(o,i),t)&&r++;return r}var vw=1440*60*1e3,Fw=2*1024*1024*1024,Mw=50,Xm=".octocode-clone-meta.json";function Nw(e){return typeof e=="object"&&e!==null}function Dw(e){if(!Nw(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),typeof e.commitSha=="string"&&e.commitSha.length===40&&(t.commitSha=e.commitSha),t}function Kc(e){let t=yn(e,Xm);if(!go(t))return null;try{return Dw(JSON.parse(Lw(t,"utf-8")))}catch{return null}}function Cr(e,t){try{_w(yn(e,Xm),JSON.stringify(t,null,2),"utf-8")}catch{}}function Ym(e){return Date.now()<new Date(e.expiresAt).getTime()}function xr(e){let t=Kc(e);return t?Ym(t)?go(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Hw(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return vw}function Gw(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Fw}function Bw(){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 Mw}function wr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Hw()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function bn(e){let t=yn(e,"..");try{go(t)||kw(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 Qi(e){try{go(e)&&ho(e,{recursive:!0,force:!0})}catch{}}function fo(e){try{return Ow(e).isDirectory()}catch{return!1}}function Gn(e){try{return Iw(e)}catch{return[]}}function*Zm(e){for(let t of Gn(e)){let n=yn(e,t);if(fo(n))for(let r of Gn(n)){let o=yn(n,r);if(fo(o))for(let i of Gn(o)){let s=yn(o,i);fo(s)&&(yield s)}}}}function Km(e){for(let t of[...Gn(e)]){let n=yn(e,t);if(fo(n)){for(let r of[...Gn(n)]){let o=yn(n,r);if(fo(o)&&Gn(o).length===0)try{ho(o,{recursive:!0,force:!0})}catch{}}if(Gn(n).length===0)try{ho(n,{recursive:!0,force:!0})}catch{}}}}function zw(e){let t=0;for(let n of Zm(e))try{let r=Kc(n);(!r||!Ym(r))&&(ho(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Qw(e){let t=[];for(let n of Zm(e)){let r=Kc(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??Di(n)})}return t}function Uw(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{ho(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Jm(e){if(!go(e))return 0;let t=0;try{t+=zw(e)}catch{return t}Km(e);let n=Uw(Qw(e),Gw(),Bw());return t+=n,n>0&&Km(e),t}function Ui(e){return Jm(Gi(e))}function Pr(e){return Jm(Bi(e))}import jw from"crypto";var $w="v2",Ww=new Set([]);function Vw(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(Ww.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Ee(e,t,n){let r=Xc(Vw(t)),o=n?`${n}:${r}`:r,i=jw.createHash("sha256").update(o).digest("hex");return`${$w}-${e}:${i}`}function Xc(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=>Xc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Xc(i,t)}`}).join(",")}}`)}import Kw from"node-cache";var Xw=300*1e3,At=new Kw({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),qe={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},qm={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},ct=new Map;function Yw(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Zw(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Bn(e){let t=Yw(e);if(!(!t||!Zw(t)))try{Qc(t,1)}catch{}}function ji(){let e=Date.now();for(let[t,n]of ct.entries())e-n.startedAt>Xw&&ct.delete(t)}function $i(e){return qm[e]||qm.default}function zn(e,t,n){try{return At.set(e,t,n),qe.sets++,qe.totalKeys=At.keys().length,!0}catch{try{let r=At.keys();for(let o of r)At.get(o);return At.set(e,t,n),qe.sets++,qe.totalKeys=At.keys().length,!0}catch{return!1}}}import{createHash as Jw}from"node:crypto";import{chmod as ef,mkdir as nf,readFile as rf,readdir as qw,rename as tf,rm as eP,stat as Yc,writeFile as of}from"node:fs/promises";import{join as yo}from"node:path";import{isPersistentStorageEnabled as tP}from"@octocodeai/config";var sf=1,af=5*1024*1024,nP=5e3,rP=256*1024*1024,oP=1440*60*1e3,iP=900*1e3,cf=".last-gc",lt={hits:0,misses:0,sets:0,errors:0,evictions:0};function Wi(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Zc(){if(!tP())return!1;let e=process.env.OCTOCODE_DISK_CACHE?.trim().toLowerCase();return!(e==="false"||e==="0")}function lf(e=ro()){return yo(e,"tmp","response")}function sP(e){return(e.match(/^v\d+-([^:]+):/)?.[1]??"default").replace(/[^a-zA-Z0-9._-]/g,"_")}function uf(e,t=ro()){let n=Jw("sha256").update(e).digest("hex");return yo(lf(t),sP(e),n.slice(0,2),`${n}.json`)}function pf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aP(e,t){let n;try{n=JSON.parse(e)}catch{return null}return!pf(n)||n.version!==sf||n.key!==t||typeof n.createdAt!="number"||typeof n.expiresAt!="number"||typeof n.staleUntil!="number"||!("value"in n)||n.etag!==void 0&&typeof n.etag!="string"?null:n}async function Sn(e){try{await eP(e,{force:!0,recursive:!0})}catch{}}async function Vi(e,t={}){if(!Zc())return;let n=uf(e);try{let r=await Yc(n);if(!r.isFile()||r.size>Wi("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",af)){await Sn(n),lt.errors++;return}let o=aP(await rf(n,"utf8"),e);if(!o){await Sn(n),lt.errors++;return}let i=Date.now();if(i>=o.staleUntil){await Sn(n),lt.evictions++,lt.misses++;return}if(i>=o.expiresAt&&!t.allowStale){lt.misses++;return}return lt.hits++,{value:o.value,...o.etag?{etag:o.etag}:{},state:i<o.expiresAt?"fresh":"stale",expiresAt:o.expiresAt}}catch(r){r.code!=="ENOENT"&<.errors++,lt.misses++;return}}async function bo(e,t,n,r={}){if(!Zc())return!1;let o=Date.now(),i=Math.max(1,n*1e3),s=Math.max(i,(r.staleTtlSeconds??n)*1e3),a={version:sf,key:e,createdAt:o,expiresAt:o+i,staleUntil:o+s,value:t,...r.etag?{etag:r.etag}:{}},c;try{c=JSON.stringify(a)}catch{return lt.errors++,!1}if(c===void 0||Buffer.byteLength(c)>Wi("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",af))return!1;let l=uf(e),u=yo(l,".."),p=`${l}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{await nf(u,{recursive:!0,mode:448}),await ef(u,448),await of(p,c,{encoding:"utf8",mode:384}),await ef(p,384);try{await tf(p,l)}catch(d){let m=d.code;if(m!=="EEXIST"&&m!=="EPERM")throw d;await Sn(l),await tf(p,l)}return lt.sets++,!0}catch{return lt.errors++,await Sn(p),!1}}async function cP(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=await qw(r,{withFileTypes:!0})}catch{continue}for(let i of o){let s=yo(r,i.name);i.isDirectory()?n.push(s):i.isFile()&&i.name!==cf&&t.push(s)}}return t}async function lP(e,t,n){if(!Zc())return 0;let r=lf(e),o=yo(r,cf);if(n)try{let p=await Yc(o);if(t-p.mtimeMs<oP)return 0}catch{}let i=0,s=await cP(r),a=Wi("OCTOCODE_DISK_CACHE_MAX_ENTRIES",nP),c=Wi("OCTOCODE_DISK_CACHE_MAX_SIZE",rP),l=[],u=0;for(let p of s)try{let d=await Yc(p);if(p.includes(".tmp-")){t-d.mtimeMs>iP&&(await Sn(p),i++);continue}let m=await rf(p,"utf8"),f;try{f=JSON.parse(m)}catch{f=null}if(!pf(f)||typeof f.staleUntil!="number"||t>=f.staleUntil){await Sn(p),i++;continue}l.push({path:p,size:d.size,modified:d.mtimeMs}),u+=d.size}catch{}for(l.sort((p,d)=>p.modified-d.modified);l.length>a||u>c;){let p=l.shift();if(!p)break;await Sn(p.path),u-=p.size,i++}try{await nf(r,{recursive:!0,mode:448}),await of(o,String(t),{encoding:"utf8",mode:384})}catch{lt.errors++}return lt.evictions+=i,i}function df(e=ro(),t=Date.now()){return lP(e,t,!1)}import{AsyncLocalStorage as uP}from"node:async_hooks";var Ki=new uP;async function mf(e){let t={hit:!1};return{value:await Ki.run({root:t,depth:0,role:"response"},e),cacheHit:t.hit}}function Xi(e,t="response"){let n=Ki.getStore();return n?Ki.run({root:n.root,depth:n.depth+1,role:t},e):e()}function Kt(){let e=Ki.getStore();e&&e.depth<=1&&e.role==="response"&&(e.root.hit=!0)}function pP(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return $i(n?.[1]??"default")}async function Fe(e,t,n={}){return Xi(()=>dP(e,t,n),n.cacheRole)}async function dP(e,t,n){if(n.skipCache)return await t();if(!n.forceRefresh){try{let a=At.get(e);if(a!==void 0)return qe.hits++,Bn(e),Kt(),a}catch{}let s=await Vi(e);if(s?.state==="fresh")return qe.hits++,Bn(e),Kt(),zn(e,s.value,Math.max(1,(s.expiresAt-Date.now())/1e3)),s.value}ji();let r=ct.get(e);if(r)return r.promise;let o=Symbol(e),i=(async()=>{try{let s=await t();if(n.forceRefresh||qe.misses++,(n.shouldCache??(()=>!0))(s)){let c=pP(e,n.ttl);zn(e,s,c),await bo(e,s,c)}return s}finally{ct.get(e)?.requestId===o&&ct.delete(e)}})();return ct.set(e,{promise:i,startedAt:Date.now(),requestId:o}),i}import mP from"node-cache";var ff=86400;function hf(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return $i(n?.[1]??"default")}var Yi=new mP({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function Zi(e,t,n={}){return Xi(()=>fP(e,t,n),n.cacheRole)}async function fP(e,t,n){if(n.skipCache)return(await t({})).value;let r;if(!n.forceRefresh){try{let a=At.get(e);if(a!==void 0)return qe.hits++,Bn(e),Kt(),a}catch{}if(r=await Vi(e,{allowStale:!0}),r?.state==="fresh")return qe.hits++,Bn(e),Kt(),zn(e,r.value,Math.max(1,(r.expiresAt-Date.now())/1e3)),r.etag&&Yi.set(e,{data:r.value,etag:r.etag}),r.value}ji();let o=ct.get(e);if(o)return o.promise;let i=Symbol(e),s=(async()=>{try{let c=(n.forceRefresh?void 0:Yi.get(e))??(r?{data:r.value,etag:r.etag}:void 0),l=await t({ifNoneMatch:!n.forceRefresh&&c?.etag?c.etag:void 0});if(l.notModified&&c){qe.hits++,Bn(e),Kt();let p=hf(e,n.ttl);return zn(e,c.data,p),await bo(e,c.data,p,{...c.etag?{etag:c.etag}:{},staleTtlSeconds:ff}),c.data}if(n.forceRefresh||qe.misses++,(n.shouldCache??(()=>!0))(l.value)){let p=hf(e,n.ttl);zn(e,l.value,p),Yi.set(e,{data:l.value,etag:l.etag}),await bo(e,l.value,p,{...l.etag?{etag:l.etag}:{},staleTtlSeconds:ff})}return l.value}finally{ct.get(e)?.requestId===i&&ct.delete(e)}})();return ct.set(e,{promise:s,startedAt:Date.now(),requestId:i}),s}var yf=1440*60*1e3,sB=60*1e3,SP=900*1e3,RP=".last-cache-maintenance",CP=".cache-maintenance.lock";var Ji=new Map;function Cf(e){return Jc(e,"tmp")}function xf(e){return Jc(Cf(e),RP)}function xP(e){try{let t=Number(hP(xf(e),"utf8"));return Number.isFinite(t)&&t>=0?t:null}catch{return null}}function bf(e,t=Date.now()){let n=xP(e);return n===null?0:Math.min(yf,Math.max(0,n+yf-t))}function wP(e,t){let n=Cf(e),r=Jc(n,CP);try{gf(n,{recursive:!0,mode:448})}catch{return null}let o=()=>{try{return gf(r,{mode:448}),!0}catch{return!1}};if(o())return r;try{if(t-gP(r).mtimeMs<=SP)return null;let i=`${r}.stale-${process.pid}-${t}`;Sf(r,i),Rf(i,{recursive:!0,force:!0})}catch{return null}return o()?r:null}function PP(e,t){let n=xf(e),r=`${n}.tmp-${process.pid}-${t}`;yP(r,String(t),{encoding:"utf8",mode:384}),Sf(r,n)}async function TP(e,t){if(bf(e,t)>0)return!1;let n=wP(e,t);if(!n)return!1;try{if(bf(e,t)>0)return!1;try{return Ui(e),Pr(e),Vc(e,t),await df(e,t),PP(e,t),!0}catch{return!1}}finally{try{Rf(n,{recursive:!0,force:!0})}catch{}}}function qi(e,t=Date.now()){if(!bP())return Promise.resolve(!1);let n=Ji.get(e);if(n)return n;let r=TP(e,t).finally(()=>{Ji.get(e)===r&&Ji.delete(e)});return Ji.set(e,r),r}var Ro=null,So=null,AP=Oi;var LP=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function Pf(){try{let e=await AP({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:LP.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Tf(){if(Ro!==null)return;if(So!==null)return So;let e=(async()=>{let t=wf(),n=await Pf();Ro={version:Hn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone&&t.storage.mode==="persistent",tokenSource:n.source},await qi(Dt())})();So=e;try{await e}catch(t){throw So===e&&(Ro=null,So=null),t}}function es(){if(!Ro){let e=EP(jc.NOT_INITIALIZED.message);throw new Error(e)}return Ro}async function qc(){return(await Pf()).token}function Ef(){let e=es();return e.enableLocal&&e.enableClone}function el(){return"github"}function tl(){let e=wf().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as oT}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as _P}from"node:module";var kP=_P(import.meta.url),Af="@octocodeai/octocode-engine",IP=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??kP(Af),ts,OP=IP,nl=class extends Error{constructor(n){super(`Failed to load native dependency ${Af}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function ee(){if(ts)return ts;try{return ts=OP(),ts}catch(e){throw new nl(e)}}var D={applyContentViewMinification(e,t){return ee().applyContentViewMinification(e,t)},applyMinification(e,t){return ee().applyMinification(e,t)},minifyContent(e,t){return ee().minifyContent(e,t)},minifyContentSync(e,t){return ee().minifyContentSync(e,t)},minifyContentResult(e,t){return ee().minifyContentResult(e,t)},minifyMarkdownCore(e){return ee().minifyMarkdownCore(e)},extractSignatures(e,t){return ee().extractSignatures(e,t)},extractJsSymbols(e,t){return ee().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ee().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ee().extractGraphFacts(e,t)},scanGraphFacts(e){return ee().scanGraphFacts(e)},getSupportedJsTsExtensions(){return ee().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ee().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ee().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ee().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ee().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return ee().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return ee().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return ee().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ee().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ee().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ee().parseRipgrepJson(e,t)},searchRipgrep(e){return ee().searchRipgrep(e)},queryFileSystem(e){return ee().queryFileSystem(e)},extractMatchingLines(e,t,n){return ee().extractMatchingLines(e,t,n)},filterPatch(e,t){return ee().filterPatch(e,t)},computeLineDiff(e,t){return ee().computeLineDiff(e,t)},charToByteOffset(e,t){return ee().charToByteOffset(e,t)},byteToCharOffset(e,t){return ee().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ee().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ee().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ee().SIGNATURES_ONLY_HINT}};import{Octokit as vP}from"octokit";import{throttling as FP}from"@octokit/plugin-throttling";import{createHash as MP}from"crypto";function Rn(e){(e.provider?fn({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Bc(1)).session&&e.provider==="github"&&Uc(1)}function Lf(e){fn({packageRegistryFailures:{[e]:1}})}function vf(e){return MP("sha256").update(e).digest("hex").substring(0,16)}async function ve(e){let t=e?.token??await qc(),n=t?vf(t):"anon",r=es().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var NP=vP.plugin(FP),DP=300*1e3,rl=50,HP=60*1e3;function Ff(e){return Date.now()-e.createdAt>DP}var Xt=new Map,Co=null;function Mf(){for(let[e,t]of Xt.entries())Ff(t)&&Xt.delete(e);if(Xt.size>rl){let e=Xt.size-rl,t=0;for(let[n]of Xt){if(t>=e)break;Xt.delete(n),t++}}}function GP(){Co||(Co=setInterval(Mf,HP),typeof Co=="object"&&"unref"in Co&&Co.unref())}var _f=3,kf=60;function If(e,t,n){Rn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var BP=()=>({onRateLimit:(e,t,n,r)=>(If("primary",e,t),r<_f&&e<kf),onSecondaryRateLimit:(e,t,n,r)=>(If("secondary",e,t),r<_f&&e<kf)});function zP(e){let t=es(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Hn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:BP(),log:r,...e&&{auth:e}};return new NP(o)}async function j(e){GP();let t=e?.token??await qc(),n=t?vf(t):"ANONYMOUS",r=Xt.get(n);if(r&&!Ff(r))return r.client;Xt.size>=rl&&Mf();let o=zP(t??void 0);return Xt.set(n,{client:o,createdAt:Date.now()}),o}var QP=200,UP=300*1e3,Tr=new Map;async function Me(e,t,n){let o=`${await ve(n)}:${e}/${t}`,i=Tr.get(o);if(i&&i.expiresAt>Date.now())return i.branch;i&&Tr.delete(o);let s=await j(n);try{let{data:c}=await s.rest.repos.get({owner:e,repo:t}),l=c.default_branch;return Of(o,l),l}catch{}let a=["main","master"];for(let c of a)try{return await s.rest.repos.getBranch({owner:e,repo:t,branch:c}),Of(o,c),c}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Of(e,t){if(Tr.size>=QP){let n=Tr.keys().next().value;n!==void 0&&Tr.delete(n)}Tr.set(e,{branch:t,expiresAt:Date.now()+UP})}import{RequestError as Df}from"octokit";var V={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},_e={[V.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[V.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[V.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[V.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[V.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[V.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[V.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[V.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[V.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[V.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Nf={401:V.AUTH_REQUIRED,403:V.FORBIDDEN_PERMISSIONS,404:V.NOT_FOUND,422:V.INVALID_REQUEST,502:V.SERVER_UNAVAILABLE,503:V.SERVER_UNAVAILABLE,504:V.SERVER_UNAVAILABLE},ol={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},il={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ns={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var jP=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function Ht(e){if(!(e instanceof Df)||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 jP.some(o=>r.includes(o))})}function J(e){return e instanceof Df?$P(e):e instanceof Error?qP(e):{error:typeof e=="string"?e:_e[V.UNKNOWN].message,type:"unknown"}}function $P(e){let{status:t,message:n,response:r}=e;if(t===403)return VP(n,r);if(t===429)return WP(n,r);let o=Nf[t];return o?JP(o,t):Er(V.UNKNOWN,{error:n||_e[V.UNKNOWN].message,status:t})}function sl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function WP(e,t){let n=t?.headers,r=sl(n,"retry-after"),o=sl(n,"x-ratelimit-reset"),i=sl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ns.RESET_BUFFER_SECONDS,0):void 0);return Rn({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Er(V.RATE_LIMIT_PRIMARY,{error:e||_e[V.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:_e[V.RATE_LIMIT_PRIMARY].suggestion})}function VP(e,t){let n=t?.headers;if(il.SECONDARY.test(e))return KP(n);let r=n?.["x-ratelimit-remaining"],o=ZP(t);return r!==void 0&&String(r)==="0"||o?XP(n):YP(n)}function KP(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ns.SECONDARY_FALLBACK_SECONDS:t;return Rn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Er(V.RATE_LIMIT_SECONDARY,{error:_e[V.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:_e[V.RATE_LIMIT_SECONDARY].suggestion})}function XP(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)+ns.RESET_BUFFER_SECONDS,0):void 0,i=r?_e[V.RATE_LIMIT_PRIMARY].messageWithTime(r,o):_e[V.RATE_LIMIT_PRIMARY].messageWithoutTime;return Rn({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Er(V.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:_e[V.RATE_LIMIT_PRIMARY].suggestion})}function YP(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=_e[V.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=eT(String(t),String(n))),Er(V.FORBIDDEN_PERMISSIONS,{error:_e[V.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function ZP(e){return e?.data?.errors?.some(n=>n.type===il.GRAPHQL_TYPE)??!1}function JP(e,t){let n=_e[e];return Er(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function qP(e){return ol.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:_e[V.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:_e[V.NETWORK_CONNECTION_FAILED].suggestion}:ol.TIMEOUT.some(t=>e.message.includes(t))?{error:_e[V.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:_e[V.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Er(e,t){return{type:"http",...t}}function eT(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?_e[V.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):_e[V.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Hf(e){return`user:${e}`}var tT=/[@/]/,nT=/^[A-Za-z0-9_-]+$/;function al(e){return e.startsWith('"')||nT.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var Yt=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(Hf(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=tT.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var rT=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,cl=class extends Yt{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(al))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(rT):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}},ll=class extends Yt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(al)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars");let n=t;return typeof n.size=="string"&&this.queryParts.push(`size:${n.size}`),typeof n.created=="string"&&this.queryParts.push(`created:${n.created}`),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`),typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function ul(e){return new cl().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function pl(e){return new ll().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var dl=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.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.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 ml(e){return new dl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function fl(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["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==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.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var hl=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function gl(e){return new hl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function yl(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as WB,DISCOVERY_IGNORED_FILE_NAMES as VB,DISCOVERY_IGNORED_FOLDER_NAMES as KB,getDiscoveryExtension as Gf,shouldIgnoreDiscoveryDir as xo,shouldIgnoreDiscoveryFile as Ar}from"@octocodeai/octocode-engine/security";var Bf=Symbol.for("octocode.rawResponseChars");function G(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function zf(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?zf(t):G(t);if(n===void 0)return e;try{Object.defineProperty(e,Bf,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ie(e){if(!(typeof e!="object"||e===null))return zf(e[Bf])}function Lr(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function Qf(e){let t=Lr(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function _r(e){let t=Lr(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function Uf(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var jf=30;async function $f(e,t,n){let r=await ve(t),o=Ee("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await Fe(o,async()=>await iT(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function iT(e,t){try{let n=await j(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(g=>g&&g.trim()).length===0)return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let r=ul(e);if(!r.trim())return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:jf,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 sT(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,p=Math.min(u,1e3),d=Math.ceil(p/o),m=Math.min(i,Math.max(1,d)),f=m<d,h=Math.min(p,d*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:m,totalPages:d,perPage:o,totalMatches:p,reportedTotalMatches:u,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:u>p,hasMore:f,...f?{nextPage:m+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Lr(a.headers),rawResponseChars:G(a.data)}}catch(n){if(Ht(n)){let o=Math.min(typeof e.limit=="number"?e.limit:jf,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 J(n)}}async function sT(e,t){let n=aT(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(m=>!Ar(m.path)),c=0,l=0,u=await Promise.allSettled(a.map(async m=>{s.add(m.path);let f=[],h=await Promise.allSettled((m.text_matches||[]).map(async C=>{let P=C.fragment,T=oT.sanitizeContent(P||"",m.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${m.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${m.path}: ${k}`));try{let k=await D.minifyContent(P||"",m.path);P=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let E=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:P||"",positions:Uf(C.fragment||"",E,P||"")}})),y=h.filter(C=>C.status==="fulfilled").map(C=>C.value),g=h.filter(C=>C.status==="rejected").length;g>0&&(l+=g);let S=m,R=Array.from(new Set(f));return{path:m.path,matches:y,url:m.html_url,repository:{nameWithOwner:m.repository.full_name,url:m.repository.url,pushedAt:m.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...R.length>0&&{minificationType:R.join(",")}}})),p=u.filter(m=>m.status==="fulfilled").map(m=>m.value);c=u.filter(m=>m.status==="rejected").length;let d={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let m=n.full_name.split("/");return m.length===2&&m[0]&&m[1]?{owner:m[0],repo:m[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(d.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&&(d.matchLocations=Array.from(r)),d.minified=!o,d.minificationFailed=o,i.length>0&&(d.minificationTypes=Array.from(new Set(i))),d}function aT(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 Wf=30;function Vf(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 Kf(e,t,n){let r=await ve(t),o=e,i=Ee("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:o.size,created:o.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await Fe(i,async()=>await lT(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function cT(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(m){if(m?.status!==404)return J(m);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(h){return J(h)}}let a=i.map(m=>{let h=m.full_name.split("/"),y=h[0]||"",g=h[1]||"";return{owner:y,repo:g,defaultBranch:m.default_branch,stars:m.stargazers_count||0,description:m.description?m.description:"No description",url:m.html_url,createdAt:m.created_at,updatedAt:m.updated_at,pushedAt:m.pushed_at,visibility:m.visibility,...m.topics&&m.topics.length>0&&{topics:m.topics},...m.forks_count&&m.forks_count>0&&{forksCount:m.forks_count},...m.open_issues_count&&m.open_issues_count>0&&{openIssuesCount:m.open_issues_count},...m.language&&{language:m.language},...Vf(m)}}),c=a.length,l=c===n,u=(r-1)*n+c,p=s??u+(l?1:0),d=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:p,reachableTotalMatches:u,totalMatchesKind:d,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:G(i)}}async function lT(e,t){try{let n=await j(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=e,i=!!(e.stars||e.updated||e.language||e.match||o.forks||o.goodFirstIssues||o.created||o.size||o.license||o.visibility||o.archived!==void 0||e.sort&&!["best-match","updated"].includes(e.sort)),s=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&!i&&s)return await cT({owner:s,sort:e.sort,limit:e.limit,page:e.page},n);let a=pl(e);if(!a.trim())return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let c=Math.min(e.limit||Wf,100),l=e.page||1,u={q:a,per_page:c,page:l},p=["stars","forks","help-wanted-issues","updated"];e.sort&&p.includes(e.sort)&&(u.sort=e.sort);let d=await n.rest.search.repos(u),m=d.data.items.map(C=>{let T=C.full_name.split("/"),E=T[0]||"",k=T[1]||"";return{owner:E,repo:k,defaultBranch:C.default_branch,stars:C.stargazers_count||0,description:C.description?C.description:"No description",url:C.html_url,createdAt:C.created_at,updatedAt:C.updated_at,pushedAt:C.pushed_at,visibility:C.visibility,...C.topics&&C.topics.length>0&&{topics:C.topics},...C.forks_count&&C.forks_count>0&&{forksCount:C.forks_count},...C.open_issues_count&&C.open_issues_count>0&&{openIssuesCount:C.open_issues_count},...C.language&&{language:C.language},...Vf(C)}}),f=d.data.total_count,h=Math.min(f,1e3),y=Math.ceil(h/c),g=Math.min(l,Math.max(1,y)),S=g<y,R=Math.min(h,y*c);return{data:{repositories:m,pagination:{currentPage:g,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:f,reachableTotalMatches:R,totalMatchesKind:"reported",totalMatchesCapped:f>h,hasMore:S,...S?{nextPage:g+1}:{}}},status:200,headers:Lr(d.headers),rawResponseChars:G(d.data)}}catch(n){if(Ht(n)){let r=Math.min(e.limit||Wf,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 J(n)}}function Lt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function ke(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 uT(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 Zt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:uT(e)}}function rs(e){return pT(e)?Zt({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 pT(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||dT(n)}function dT(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function wo(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...e?.totalMatchesKind==="lowerBound"?{totalMatchesKind:"lowerBound"}:{},...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function mT(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...wo(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function fT(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...wo(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Xf(e,t,n=ke){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,goal:e.goal,reasoning:e.reasoning},a=await $f(s,t);return Lt(a)?Zt(a):a.data?{data:mT(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??G(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Yf(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,goal:e.goal,reasoning:e.reasoning},r=await Kf(n,t);return"error"in r?rs(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:fT(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??G(r.data)}}import{RequestError as Rl}from"octokit";var I={...re,LOCAL_SEARCH:"localSearch",GITHUB_SEARCH_CODE:"github.code",GITHUB_VIEW_REPO_STRUCTURE:"github.tree",GITHUB_SEARCH_REPOSITORIES:"github.repositories",LOCAL_RIPGREP:"local.text",LOCAL_VIEW_STRUCTURE:"local.tree",LOCAL_FIND_FILES:"local.files"};function bl(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 paths are case-sensitive. Verify exact casing with ghSearch operation:"tree".'),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Sl(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(m=>m.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(m=>m.name===s?!1:!!m.name.startsWith(p+".")).forEach(m=>l.push(m.path)),l.length===0&&p.length>=3&&c.filter(f=>{let h=f.name.replace(/\.[^/.]+$/,"");return h!==p&&h.length>=3&&(p.startsWith(h)||h.startsWith(p))}).forEach(f=>l.push(f.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}async function gT(e,t,n,r,o,i,s,a){let c=await Me(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=J(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,d=await Sl(e,r,o,i,s||c);return d.length>0&&(u.hints=[...u.hints||[],...bl(i,d)]),{...u,...p&&{scopesSuggestion:p}}}async function yT(e,t,n,r,o,i){let s=J(t),a=await Sl(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...bl(o,a)]),s}async function Zf(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:hn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:hn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:hn.DECODE_FAILED.message,type:"unknown",status:422}}}async function Jf(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"?Zf(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return J(i)}}async function bT(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 Me(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(d=>d.name===a&&d.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let p=await Jf(e,t,n,u.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return J(s)}}async function Po(e,t,n={}){try{let r=await j(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(m){if(m instanceof Rl&&m.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(m instanceof Rl&&m.status===404)if(a){let f=await gT(r,m,c,o,i,s,a,t);if("result"in f)l=f.result,u=f.actualBranch;else return f}else return await yT(r,m,o,i,s,a);else{if(m instanceof Rl&&m.status===413)return await bT(r,o,i,s,a||u,t);throw m}}let p=l.data,d=_r(l.headers);if(Array.isArray(p))return{error:hn.PATH_IS_DIRECTORY.message(I.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let m=typeof p.content=="string"?p.content:"",f=p.size??0,h;if(m.length>0)h=await Zf(m,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)h=await Jf(r,o,i,p.sha,s);else return{error:hn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in h)return h;if(!u&&!a)try{u=await Me(o,i,t)}catch{}return{data:{rawContent:h.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:G(p),...d?{etag:d}:{}}}return{error:hn.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return J(r)}}import{ContentSanitizer as El}from"@octocodeai/octocode-engine/contentSanitizer";function os(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Gt(e){return os(e).length}function is(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
22
|
-
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var ST=/\.(?:md|markdown|mdx)$/i;function RT(e){return ST.test(e.split(/[?#]/,1)[0]??e)}function qf(e,t){return RT(t)?xT(CT(e)):null}function ss(e,t){let n=qf(e,t);if(n===null||n.length===0)return null;let r=[];return th(n,r),r.join(`
|
|
23
|
-
`)}function eh(e,t){let n=qf(e,t);return n===null?null:n.map(nh)}function CT(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function xT(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n[n.length-1].level>=r.level;)n.pop();let o=n[n.length-1];o?o.children.push(r):t.push(r),n.push(r)}return t}function th(e,t){for(let n of e){let r=String(n.line).padStart(4," "),o=" ".repeat(Math.max(0,n.level-1));t.push(`${r}| ${o}${"#".repeat(n.level)} ${n.text}`),th(n.children,t)}}function nh(e){let t=`${"#".repeat(e.level)} ${e.text}`;return{name:t,kind:"markdownHeading",range:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},selectionRange:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},children:e.children.map(nh)}}import{getConfigSync as wT,DEFAULT_OUTPUT_CONFIG as PT}from"@octocodeai/config";function Qn(){try{return wT().output.pagination.defaultCharLength}catch{return PT.pagination.defaultCharLength}}function Cl(e,t){return D.byteToCharOffset(e,t)}function rh(e,t){return D.charToByteOffset(e,t)}function oh(e){return D.charToByteOffset(e,e.length)}function xl(e,t,n,r){return D.sliceContent(e,t,n,r)}function as(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=oh(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,p,d,m,f,h;if(o==="bytes"){let y=Math.min(t,s),g=Math.min(y+n,s);p=Cl(e,y),d=Cl(e,g),d<i&&rh(e,d)<g&&(d+=1);let S=xl(e,p,d-p);c=S.text,p=S.charOffset,d=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,m=u<s;let R=r.actualOffset??y;f=Math.floor(R/a)+1,h=Math.max(f,Math.ceil(s/a))}else{let y=xl(e,t,n);c=y.text,p=y.charOffset,d=y.charOffset+y.charLength,l=y.byteOffset,u=y.byteOffset+y.byteLength,m=d<i;let g=r.actualOffset??p;f=Math.floor(g/a)+1,h=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:m?u:void 0,charOffset:p,charLength:c.length,totalChars:i,nextCharOffset:m?d:void 0,hasMore:m,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:h}}function wl(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 TT=8e3,ET="__octocode_generic__.unknown";function AT(e){return e&&e.trim().length>0?e:ET}async function ih(e,t){return(await D.getSemanticBoundaryOffsets(e,AT(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function LT(e,t){let n=e.indexOf(`
|
|
24
|
-
`,t);return n===-1?void 0:n+1}function cs(e){let t=e.trimEnd().split(`
|
|
25
|
-
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function ls(e,t,n){let r=LT(e,Math.max(0,t));return r===void 0?void 0:(await ih(e,n)).find(i=>i>=r&&i>t)}async function us(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=await ih(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=TT?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function kT(){let e=Qn();return Math.min(e,8e3)}async function Pl(e,t,n){let r=e.content??"",o=n??kT();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await us(r,t,o,i),c=as(r,t,s,{pageSize:o}),l;if(c.hasMore&&a==="char-limit"&&cs(c.paginatedContent)){let u=c.charOffset+c.charLength;l=await ls(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function Tl(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}}function To(e,t){return{sourceChars:e,sourceBytes:t}}async function sh(e,t,n,r,o,i,s,a,c=5,l,u,p,d="standard"){let m=e.length,f=Buffer.byteLength(e,"utf-8"),h=d==="standard"||d==="symbols",y=h?"standard":"none",g;if(d==="symbols"){let v=D.extractSignatures(e,o);if(v===null){let A=ss(e,o);if(A!==null){let Z=El.sanitizeContent(A,o),te=[D.SIGNATURES_ONLY_HINT];return Z.hasSecrets&&te.push(`Secrets detected and redacted: ${Z.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Z.content,contentView:"symbols",branch:r,totalLines:Gt(e),...To(m,f),isPartial:!1,signaturesExtracted:!0,hints:te}}g=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(v!==null){let A=El.sanitizeContent(v,o),Z=D.applyContentViewMinification(A.content,o),te=[D.SIGNATURES_ONLY_HINT];return l&&te.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),A.hasSecrets&&te.push(`Secrets detected and redacted: ${A.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Z,contentView:"symbols",branch:r,totalLines:Gt(e),...To(m,f),isPartial:!1,signaturesExtracted:!0,hints:te}}}let S=new Set,R=e,C=R.split(`
|
|
26
|
-
`),P=Gt(R),T=e,E,k,x=!1,b,w;if(i)T=e;else if(l){let v=p===!0,A;try{A=is(C,l,c,u??!1,v)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:P,...To(m,f),matchNotFound:!0,searchedFor:l,hints:["Fix the regex or set matchStringIsRegex:false for a literal."]}}if(A.matchCount===0){let ne=u?[`No lines matched "${l}" (case-${v?"sensitive":"insensitive"}). Check the pattern or use fullContent:true.`]:[`"${l}" not found in file${v?" (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:P,...To(m,f),matchNotFound:!0,searchedFor:l,hints:ne}}T=A.lines.join(`
|
|
27
|
-
`);let Z=A.matchRanges[0],te=A.matchRanges[A.matchRanges.length-1];s=Z.start,a=te.end,E=Z.start,k=te.end,x=!1,b=A.matchRanges,w=A.matchingLines;let Ie=A.matchingLines.slice(0,5).join(", "),K=A.matchingLines.length>5?` and ${A.matchingLines.length-5} more`:"";S.add(A.matchCount>1?`Found ${A.matchCount} occurrences of "${l}" on lines ${Ie}${K} \u2014 all shown as ${A.matchRanges.length} slice${A.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${A.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let v=s||1,A=a||P;if(v<1||v>P)T=e,S.add(`Requested startLine ${v} is out of range for this ${P}-line file \u2014 returning the full file instead of a range.`);else if(A<v)T=e,S.add(`Requested range startLine=${v}, endLine=${A} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let Z=Math.max(1,v),te=Math.min(P,A),Ie=C.slice(Z-1,te);E=Z,k=te,x=te<P,T=Ie.join(`
|
|
28
|
-
`),A>P&&S.add(`Requested endLine ${A} adjusted to ${P} (file end)`)}}let L=El.sanitizeContent(T,o);if(T=h?D.applyContentViewMinification(L.content,o):L.content,L.hasSecrets&&S.add(`Secrets detected and redacted: ${L.secretsDetected.join(", ")}`),L.warnings.length>0&&L.warnings.forEach(v=>S.add(v)),P>2e3&&d!=="symbols"&&!l&&!s&&!a&&!i){let v=Math.max(1,P-200);S.add(`Large file (${P} lines) \u2014 minify:"symbols" for an export index, or startLine=${v} for the tail.`)}let O=Array.from(S);return{owner:t,repo:n,path:o,content:T,contentView:y,branch:r,totalLines:P,...To(m,f),...x&&{startLine:E,endLine:k,isPartial:x},...b&&{matchRanges:b},...w&&{matchedLines:w},...O.length>0&&{matchLocations:O},...(O.length>0||g)&&{warnings:[...g?[g]:[],...O]}}}async function ah(e,t,n){let r=await ve(t),o=Ee("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await Zi(o,async({ifNoneMatch:h})=>{let y=await Po(e,t,{ifNoneMatch:h}),{etag:g,notModified:S,...R}=y;return{value:R,etag:g,notModified:S}},{shouldCache:h=>"data"in h&&!h.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await sh(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...l}=a,u=e.charOffset??0,p=e.charLength,d=e.fullContent===!0&&u===0&&p===void 0,m=c||d?l:await Pl(l,u,p),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let h=await j(t),y=await Fe(Ee("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>Tl(h,e.owner,e.repo,e.path,e.branch),{shouldCache:g=>g!==null,forceRefresh:e.forceRefresh===!0,cacheRole:"helper"});y&&(m.lastModified=y.lastModified,m.lastModifiedBy=y.lastModifiedBy)}catch{}return{data:m,status:200,rawResponseChars:i.rawResponseChars}}function IT(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,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,matchedLines:e.matchedLines,warnings:OT(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function OT(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 ch(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",goal:e.goal,reasoning:e.reasoning},s=await ah(i,t);if(Lt(s))return Zt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:IT(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??G(s.data),...a?.length?{hints:a}:{}}}import{ContentSanitizer as ph}from"@octocodeai/octocode-engine/contentSanitizer";var FT=2;function lh(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function uh(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:FT}):""}function Al(e){let t=ph.sanitizeContent(e.title??""),n=e.body?ph.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 MT=Qn(),NT=Math.round(Qn()/4),dh=3;function mh(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 kr(e,t={}){let n=t.charOffset??0,r=t.charLength??MT,o=t.charLength??NT,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=mh(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,h)=>{let y=f.commentType==="review_inline"?0:1,g=h.commentType==="review_inline"?0:1;return y-g}),c=a.filter(f=>f.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,dh),p=u.map(f=>{let h=mh(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:h.value??"",...h.pagination?{bodyPagination:h.pagination}:{}}}),d=!t.includeFullCommentDetails&&(a.length>u.length||p.some(f=>"bodyPagination"in f)),m=[...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.`]:[],...d?[`PR comments are paginated/summarized to ${dh} 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,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??void 0,mergedAt:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(f=>({id:0,name:f,color:""}))}:{},headRef:e.head||"",...e.head_sha?{headSha:e.head_sha}:{},baseRef:e.base||"",...e.base_sha?{baseSha:e.base_sha}:{},body:s.value,...s.pagination?{bodyPagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{commentDetailsBreakdown:{inlineReview: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,changedFiles:e.file_changes?.total_count||0,...e.file_changes&&{fileChanges: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&&{commitDetails:e.commits},...p.length>0&&{commentDetails:p,commentDetailsShown:p.length,commentDetailsTotal:a.length,...d?{commentDetailsPaginated:!0}:{}},...(e._sanitization_warnings||m.length>0)&&{sanitizationWarnings:[...e._sanitization_warnings||[],...m]}}}function Eo(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 Ao(e,t){let r=t.content?.patches,o=r?.mode??"none",i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?lh(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?uh(a.patch):a.patch}))}function Ir(e){let t=e.content;return!!(t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function fh(e){return e.content?.comments??null}function ps(e){let t=fh(e);return t?t.discussion!==!1:!1}function ds(e){let t=fh(e);return t?t.reviewInline!==!1:!1}function ms(e){return!!e.content?.commits}function fs(e){return!!e.content?.reviews}function Ll(e){return e.prNumber!==void 0?!0:Ir(e)||ps(e)||ds(e)||ms(e)||fs(e)}function _l(e){return!!e.content?.comments?.includeBots}function hs(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
|
|
29
|
-
|
|
30
|
-
`).trim()}import{ContentSanitizer as Ol}from"@octocodeai/octocode-engine/contentSanitizer";var DT=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function Un(e){let t=e.toLowerCase();return t.endsWith("[bot]")||DT.has(t)}async function gs(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=G(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function kl(e,t,n,r){let o=await j(r),{items:i,rawResponseChars:s}=await gs(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $({total_count:i.length,files:i},s)}async function HT(e,t,n,r){let o=await j(r),{items:i,rawResponseChars:s}=await gs(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $(i,s)}async function GT(e,t,n,r){try{let i=await(await j(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return $(i.data.files||[],i.data)}catch{return null}}var BT=5;async function zT(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)break;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function Il(e,t,n,r,o){let i=await HT(e,t,n,o);if(!i)return null;let s=ie(i)??0,a=[...i].sort((l,u)=>{let p=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-p}),c=await zT(a,BT,async l=>{let u=await GT(e,t,l.sha,o),p=[];return u&&(s+=ie(u)??0,p=Ao(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:p}});return $(c,s)}async function vl(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let m=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=G(m.data),i.push(...m.data),c=m.data.length===100,a++}while(c);let l=o?i:i.filter(m=>!Un(m.user?.login??"")),u=i.length-l.length,p=l.map(m=>{let f=D.minifyMarkdownCore(hs(m.body??""));return{id:String(m.id),user:m.user?.login??"unknown",body:Ol.sanitizeContent(f).content,createdAt:m.created_at??"",updatedAt:m.updated_at??"",commentType:"discussion"}}),d=[];return u>0&&d.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(p,s),note:d.length>0?d.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Fl(e,t,n,r){try{let{items:o,rawResponseChars:i}=await gs(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return $(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Ol.sanitizeContent(D.minifyMarkdownCore(hs(s.body??""))).content,submittedAt:s.submitted_at??void 0,commitId:s.commit_id??void 0})),i)}catch{return $([],0)}}async function Ml(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let m=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=G(m.data),i.push(...m.data),c=m.data.length===100,a++}while(c);let l=o?i:i.filter(m=>!Un(m.user?.login??"")),u=i.length-l.length,p=l.map(m=>{let f=D.minifyMarkdownCore(hs(m.body??""));return{id:String(m.id),user:m.user?.login??"unknown",body:Ol.sanitizeContent(f).content,createdAt:m.created_at??"",updatedAt:m.updated_at??"",commentType:"review_inline",path:m.path,line:m.line??m.original_line??void 0,...m.in_reply_to_id!=null?{inReplyToId:m.in_reply_to_id}:{}}}),d=[];return u>0&&d.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(p,s),note:d.length>0?d.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Nl(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Al(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&Ll(t))try{let{owner:l,repo:u}=Eo(t);if(l&&u){let p=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(p.data&&(s+=G(p.data),o.head=p.data.head?.ref,o.head_sha=p.data.head?.sha,o.base=p.data.base?.ref,o.base_sha=p.data.base?.sha,o.draft=p.data.draft??!1,p.data.merged_at&&(o.merged_at=p.data.merged_at),o.additions=p.data.additions??0,o.deletions=p.data.deletions??0,Ir(t)||(o.file_changes={total_count:p.data.changed_files??0,files:[]}),Ir(t))){let d=await kl(l,u,e.number);d&&(s+=ie(d)??0,d.files=Ao(d.files,t),o.file_changes=d)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=ps(t),c=ds(t);if(a||c){let{owner:l,repo:u}=Eo(t);if(l&&u){let p=_l(t),d=()=>Promise.resolve({comments:$([],0)}),[{comments:m,note:f},{comments:h,note:y}]=await Promise.all([a?vl(n,l,u,e.number,p):d(),c?Ml(n,l,u,e.number,p):d()]);o.comments=[...m,...h],s+=(ie(m)??0)+(ie(h)??0);let g=[f,y].filter(S=>typeof S=="string");g.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...g])}}if(fs(t))try{let{owner:l,repo:u}=Eo(t);if(l&&u){let p=await Fl(n,l,u,e.number);s+=ie(p)??0,o.reviews=p}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(ms(t))try{let{owner:l,repo:u}=Eo(t);if(l&&u){let p=await Il(l,u,e.number,t);p&&(s+=ie(p)??0,o.commits=p)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return $(o,s)}async function Lo(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Al(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,Ir(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ir(t))try{let p=await kl(a,c,e.number,r);p&&(s+=ie(p)??0,p.files=Ao(p.files,t),o.file_changes=p)}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${p instanceof Error?p.message:String(p)}`]}let l=ps(t),u=ds(t);if(l||u){let p=_l(t),d=()=>Promise.resolve({comments:$([],0)}),[{comments:m,note:f},{comments:h,note:y}]=await Promise.all([l?vl(n,a,c,e.number,p):d(),u?Ml(n,a,c,e.number,p):d()]);o.comments=[...m,...h],s+=(ie(m)??0)+(ie(h)??0);let g=[f,y].filter(S=>typeof S=="string");g.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...g])}if(fs(t))try{let p=await Fl(n,a,c,e.number);s+=ie(p)??0,o.reviews=p}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${p instanceof Error?p.message:String(p)}`]}if(ms(t))try{let p=await Il(a,c,e.number,t,r);p&&(s+=ie(p)??0,o.commits=p)}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${p instanceof Error?p.message:String(p)}`]}return $(o,s)}function QT(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function hh(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pullRequests:[],totalCount:0,error:Ve.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pullRequests:[],totalCount:0,error:Ve.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await j(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Lo(a,e,i,t);return{pullRequests:[kr(c,{includeFullBody:!0,includeFullCommentDetails:!0})],totalCount:1,rawResponseChars:G(s.data)+(ie(c)??0)}}catch(i){let s=J(i);return QT(s,Ve.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 Dl(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Hl(e){let t=Math.min(e.limit||30,100);return{pullRequests:[],totalCount:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function gh(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 d=>await Lo(d,t,e))),c=a.reduce((d,m)=>d+(ie(m)??0),0),l=a.map(d=>kr(d,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,p=(i-1)*o+l.length;return{pullRequests:l,totalCount:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:p+(u?1:0),reachableTotalMatches:p,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:G(s.data)+c}}catch(n){if(Ht(n))return Hl(t);let r=J(n);return Dl(r,Ve.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}async function UT(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function jT(e,t,n="anon"){return Ee("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,"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,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,project:e.project,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function yh(e,t,n){let r=await ve(t),o=jT(e,n,r);return await Fe(o,async()=>await $T(e,t,n),{shouldCache:s=>!s.error})}async function $T(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await hh(e,t);let r=await j(t);if(!fl(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await gh(r,e);let i=await UT(r,e),s=ml(i);if(!s)return{pullRequests:[],totalCount:0,error:Ve.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,p=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),d=p.data.items?.filter(T=>!!T.pull_request)||[],m=await Promise.all(d.map(async T=>await Nl(T,i,r))),f=m.reduce((T,E)=>T+(ie(E)??0),0),h=m.map(T=>kr(T,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),y=p.data.total_count,g=Math.min(y,1e3),S=Math.ceil(g/c),R=Math.min(l,Math.max(1,S)),C=R<S,P=Math.min(g,S*c);return{pullRequests:h,totalCount:p.data.total_count,effectiveQuery:u,...p.data.incomplete_results&&{incompleteResults:!0},pagination:{currentPage:R,totalPages:S,perPage:c,totalMatches:g,reportedTotalMatches:y,reachableTotalMatches:P,totalMatchesKind:"reported",totalMatchesCapped:y>g,hasMore:C,...C?{nextPage:R+1}:{}},rawResponseChars:G(p.data)+f}}catch(r){if(Ht(r))return Hl(e);let o=J(r);return Dl(o,Ve.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}function WT(e,t,n=ke){let r=(e.pullRequests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.bodyPagination&&{bodyPagination:a.bodyPagination},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.headRef||"",targetBranch:a.baseRef||"",sourceSha:a.headSha,targetSha:a.baseSha,createdAt:a.createdAt,updatedAt:a.updatedAt,closedAt:a.closedAt,mergedAt:a.mergedAt,commentsCount:a.comments,changedFilesCount:a.changedFiles,additions:a.additions,deletions:a.deletions,comments:a.commentDetails?.map(c=>({id:c.id,author:c.user,body:c.body,...c.bodyPagination&&{bodyPagination:c.bodyPagination},createdAt:c.createdAt,updatedAt:c.updatedAt,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.inReplyToId!=null&&{inReplyToId:c.inReplyToId}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submittedAt,commitId:c.commitId})),commits:a.commitDetails?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.fileChanges?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a.sanitizationWarnings)&&a.sanitizationWarnings.length>0?{sanitizationWarnings:a.sanitizationWarnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.totalCount||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...wo(e.pagination)},...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}function VT(e,t,n){return{owner:t,repo:n,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,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,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,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,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}}async function bh(e,t,n=ke){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},i=r||e.owner,s=VT(e,i,o),a=await yh(s,t);return a.error?Zt({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:WT(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??G(a)}}var Cn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function ys(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function Sh(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:x,...b}=e;return b}let r=t.itemsPerPage??Cn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),p=e.path==="/"?"":e.path,d=x=>{let b=x;p&&x.startsWith(p)&&(b=x.slice(p.length),b.startsWith("/")&&(b=b.slice(1)));let w=b.lastIndexOf("/");return w===-1?".":b.slice(0,w)},m=x=>{let b=x.lastIndexOf("/");return b===-1?x:x.slice(b+1)};for(let x of l){let b=d(x.path);u[b]||(u[b]={files:[],folders:[]});let w=m(x.path);x.type==="file"?u[b].files.push(w):u[b].folders.push(w)}for(let x of Object.keys(u)){let b=u[x];b&&(b.files.sort(),b.folders.sort())}let f=Object.create(null),h=Object.keys(u).sort((x,b)=>x==="."?-1:b==="."?1:x.localeCompare(b));for(let x of h){let b=u[x];b&&(f[x]=b)}let y=l.filter(x=>x.type==="file").length,g=l.filter(x=>x.type==="dir").length,S=n.filter(x=>x.type==="file").length,R=n.filter(x=>x.type==="dir").length,C=o<s,P={currentPage:o,totalPages:s,hasMore:C,...C?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},T=ys(P,{owner:e.owner,repo:e.repo,branch:e.branch,path:p,depth:t.maxDepth??1,pageFiles:y,pageFolders:g,allFiles:S,allFolders:R}),E,k=e._cachedFileSizeMap;if(k){let x=new Set(l.filter(L=>L.type==="file").map(L=>L.path)),b=e.path==="/"?"":e.path,w=Object.create(null);for(let[L,O]of Object.entries(k))for(let[v,A]of Object.entries(O)){let Z=L==="."?b?`${b}/${v}`:v:b?`${b}/${L}/${v}`:`${L}/${v}`;x.has(Z)&&(w[L]||(w[L]=Object.create(null)),w[L][v]=A)}Object.keys(w).length>0&&(E=w)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:R,truncated:C,filtered:!0,originalCount:i},structure:f,...E!==void 0&&{fileSizeMap:E},...k!==void 0&&{_cachedFileSizeMap:k},pagination:P,hints:T,rawResponseChars:e.rawResponseChars}}import{RequestError as XT}from"octokit";var Ch=Symbol.for("octocode.recursiveFetchFailures"),YT=new Set([401,403,429]);function Rh(e){return e instanceof XT&&YT.has(e.status)}function Gl(e,t){try{Object.defineProperty(e,Ch,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function _o(e){if(typeof e!="object"||e===null)return 0;let t=e[Ch];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function ko(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Gl($([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(f){if(Rh(f))throw f;return Gl($([],0),1)}let l=G(c.data),p=(Array.isArray(c.data)?c.data:[c.data]).filter(f=>f.type==="file"||f.type==="dir").map(f=>({name:f.name,path:f.path,type:f.type,size:"size"in f?f.size:void 0,download_url:"download_url"in f?f.download_url:void 0,url:f.url,html_url:f.html_url,git_url:f.git_url,sha:f.sha})),d=[...p],m=0;if(i<s){let f=p.filter(y=>y.type==="dir"),h=3;for(let y=0;y<f.length;y+=h){let g=f.slice(y,y+h),S=await Promise.allSettled(g.map(R=>ko(e,t,n,r,R.path,i+1,s,a)));for(let R of S)if(R.status==="fulfilled"){let C=R.value;l+=ie(C)??0,m+=_o(C),d.push(...C)}else{if(Rh(R.reason))throw R.reason;m+=1}}}return Gl($(d,l),m)}import{RequestError as ZT}from"octokit";function JT(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let l=a.lastIndexOf("/"),u=l===-1?a:a.slice(l+1);i.push({name:u,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function xh(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function wh(e,t){let{data:n}=await e.rest.repos.getBranch({owner:t.owner,repo:t.repo,branch:t.workingBranch}),r=n.commit.commit.tree.sha;if(!r)throw new Error(`Could not resolve tree SHA for ${t.owner}/${t.repo}@${t.workingBranch}`);let o;try{o=await e.rest.git.getTree({owner:t.owner,repo:t.repo,tree_sha:r,recursive:"true",...t.ifNoneMatch?{headers:{"If-None-Match":t.ifNoneMatch}}:{}})}catch(c){if(c instanceof ZT&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=_r(o.headers);return{items:JT(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:G(n)+G(i),...s?{etag:s}:{}}}import{RequestError as Ph}from"octokit";async function Bl(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Me(t,n,i),a=c)}catch(l){let u=J(l);return{error:gn.NOT_FOUND.message(t,n,u.error),status:u.status}}try{let l=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),u=_r(l.headers);return{data:l.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...u?{etag:u}:{}}}catch(l){if(l instanceof Ph&&l.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(l instanceof Ph&&l.status===404)){let p=J(l);return{error:gn.ACCESS_FAILED.message(t,n,p.error),status:p.status,rateLimitRemaining:p.rateLimitRemaining,rateLimitReset:p.rateLimitReset,retryAfter:p.retryAfter}}let u=J(l);return{error:gn.PATH_NOT_FOUND.message(r,t,n,a),status:u.status}}}function Th(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 qT(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 Eh(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}function bs(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:l,includeSizes:u,extraHints:p=[]}=e,d=e.allItems.filter(A=>A.type==="dir"?!xo(A.name):!Ar(A.path));d.sort((A,Z)=>{if(A.type!==Z.type)return A.type==="dir"?-1:1;let te=A.path.split("/").length,Ie=Z.path.split("/").length;return te!==Ie?te-Ie:A.path.localeCompare(Z.path)});let m=e.itemsPerPage??Cn.ENTRIES_PER_PAGE,f=e.page??1,h=d.length,y=Math.max(1,Math.ceil(h/m)),g=(f-1)*m,S=Math.min(g+m,h),R=d.slice(g,S),C=qT(R,i),P=u?Eh(d,i):void 0,T=P!==void 0?Eh(R,i):void 0,E=R.filter(A=>A.type==="file").length,k=R.filter(A=>A.type==="dir").length,x=d.filter(A=>A.type==="file").length,b=d.filter(A=>A.type==="dir").length,w=f<y,L={currentPage:f,totalPages:y,hasMore:w,...w?{nextPage:f+1}:{},entriesPerPage:m,totalEntries:h},O=ys(L,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:E,pageFolders:k,allFiles:x,allFolders:b});a>0&&O.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let A of p)O.unshift(A);let v=[...c?["providerTreeTruncated"]:[],...a>0?["partialTreeFailures"]:[]];return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:x,totalFolders:b,truncated:w,filtered:!0,originalCount:d.length,...c?{incompleteTree:!0}:{}},structure:C,...T!==void 0&&{fileSizeMap:T},...P!==void 0&&{_cachedFileSizeMap:P},pagination:L,...v.length>0?{isPartial:!0,partialReasons:v}:{},...c?{terminalLimit:!0}:{},hints:O,rawResponseChars:l,_cachedItems:d.map(A=>({path:A.path,type:A.type}))}}async function zl(e,t,n){let r=await ve(t),o=Ee("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await Zi(o,async({ifNoneMatch:s})=>{let a=await eE({...e,itemsPerPage:e.itemsPerPage??Cn.ENTRIES_PER_PAGE,page:e.page??1},t,s);return{value:a.result,etag:a.etag,notModified:a.notModified}},{shouldCache:s=>!("error"in s)});return!("error"in i)&&i.structure?Sh(i,e):i}async function eE(e,t,n){try{let r=await j(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,l=a.replace(/^\/+|\/+$/g,"");if(c>1&&xh())return await tE(r,e,l,c,t,n);let u=await Bl(r,o,i,l,s,t,c===1?n:void 0);if("error"in u)return{result:u};if(u.notModified)return{result:{error:"not-modified",status:304},etag:u.etag??n,notModified:!0};let{data:p,workingBranch:d,repoDefaultBranch:m,etag:f}=u,h=G(p),y=Array.isArray(p)?p:[p],g=Th(y),S=0;if(c>1){let R=await ko(r,o,i,d,l,1,c);S=_o(R),h=ie(R)??0,g=R}return{result:bs({owner:o,repo:i,workingBranch:d,repoDefaultBranch:m,cleanPath:l,depth:c,allItems:g,partialTreeFailures:S,incompleteTree:!1,rawResponseChars:h,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&f?{etag:f}:{}}}catch(r){let o=J(r);return{result:{error:gn.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function tE(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,l,u;try{c?l=c:(u=await Me(s,a,o),l=u)}catch(g){let S=J(g);return{result:{error:gn.NOT_FOUND.message(s,a,S.error),status:S.status}}}let p;try{p=await wh(e,{owner:s,repo:a,workingBranch:l,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(g){let S=await Bl(e,s,a,n,l,o);if("error"in S)return{result:S};let R=await ko(e,s,a,S.workingBranch,n,1,r);return{result:bs({owner:s,repo:a,workingBranch:S.workingBranch,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:R,partialTreeFailures:_o(R),incompleteTree:!1,rawResponseChars:ie(R)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${g instanceof Error?g.message:String(g)}); used Contents recursion instead.`]})}}if(p.notModified)return{result:{error:"not-modified",status:304},etag:p.etag??i,notModified:!0};let d=p.items,m=0,f=p.rawResponseChars,h=p.truncated,y=[];if(h){y.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let g=await ko(e,s,a,l,n,1,r);m=_o(g),f+=ie(g)??0,d=[...d,...g].filter((R,C,P)=>P.findIndex(T=>T.path===R.path)===C)}catch{}}return{result:bs({owner:s,repo:a,workingBranch:l,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:d,partialTreeFailures:m,incompleteTree:h,rawResponseChars:f,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:y}),...p.etag&&!h?{etag:p.etag}:{}}}async function nE(e,t,n){try{let o=await(await j(n)).rest.repos.listLanguages({owner:e,repo:t}),i=Object.entries(o.data).sort((s,a)=>a[1]-s[1]);return i.length===0?void 0:{languages:Object.fromEntries(i),dominantLanguage:i[0][0]}}catch{return}}async function rE(e,t,n){try{let i=(await(await j(n)).rest.repos.listContributors({owner:e,repo:t,per_page:30})).data.filter(s=>typeof s.login=="string").map(s=>({login:s.login,contributions:s.contributions??0}));return i.length>0?{contributors:i}:void 0}catch{return}}async function oE(e,t,n){try{let i=(await(await j(n)).rest.repos.listBranches({owner:e,repo:t,per_page:100})).data.map(s=>s.name).filter(s=>typeof s=="string");return i.length>0?{branches:i}:void 0}catch{return}}async function iE(e,t,n){try{let i=(await(await j(n)).rest.repos.listTags({owner:e,repo:t,per_page:50})).data.filter(s=>typeof s.name=="string").map(s=>({name:s.name,sha:s.commit?.sha??""}));return i.length>0?{tags:i}:void 0}catch{return}}function sE(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 Ah(e,t,n=ke){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,goal:e.goal,reasoning:e.reasoning},[s,a,c,l,u]=await Promise.all([zl(i,t),e.includeLanguages?nE(r,o,t):Promise.resolve(void 0),e.includeContributors?rE(r,o,t):Promise.resolve(void 0),e.includeBranches?oE(r,o,t):Promise.resolve(void 0),e.includeTags?iE(r,o,t):Promise.resolve(void 0)]);return"error"in s?rs(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:{...sE(s),...a?{languages:a.languages,dominantLanguage:a.dominantLanguage}:{},...c?{contributors:c.contributors}:{},...l?{branches:l.branches}:{},...u?{tags:u.tags}:{}},status:200,provider:"github",rawResponseChars:s.rawResponseChars??G(s)}}var Lh={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};var Ss=class{type="github";capabilities=Lh.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Xf(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await ch(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Yf(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await bh(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Ah(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=ke(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Me(n,r,this.authInfo)}handleError(t){let n=J(t);return Zt(n)}};import{createHash as cE}from"crypto";var lE=3600*1e3,_h=20,Bt=new Map;function kh(e){return Date.now()-e.createdAt<lE}function uE(e=0){for(let[n,r]of Bt.entries())kh(r)||Bt.delete(n);let t=Math.max(0,_h-e);if(Bt.size>t){let n=[...Bt.entries()].sort((o,i)=>o[1].lastAccessedAt-i[1].lastAccessedAt),r=Bt.size-t;for(let o=0;o<r&&o<n.length;o++){let i=n[o];i&&Bt.delete(i[0])}}}function pE(e){return e?cE("sha256").update(e).digest("hex").slice(0,16):"default"}function dE(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 mE(e,t){let n=dE(t?.baseUrl||"default"),r=pE(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Ql(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=mE(e,t),r=Bt.get(n);if(r&&kh(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Bt.delete(n),Bt.size>=_h&&uE(1);let o=new Ss({...t,type:e}),i=Date.now();return Bt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function Ih(){try{return Ql("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}
|
|
31
|
-
`),[{provider:"github",ok:!1,error:t}]}}import{getConfigSync as FO}from"@octocodeai/config";import{existsSync as fE,readdirSync as hE,lstatSync as gE}from"node:fs";import{join as yE}from"node:path";function Oh(e){if(!fE(e))return 0;let t;try{t=hE(e)}catch{return 0}let n=0;for(let r of t){if(r===".git")continue;let o=yE(e,r);try{let i=gE(o);if(i.isSymbolicLink())continue;i.isDirectory()?n+=Di(o):i.isFile()&&(n+=i.size)}catch{}}return n}async function vh(e,t={}){if(!Array.isArray(e))throw new Error(lo.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(lo.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(lo.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(po.NOT_A_FUNCTION.message(l))));if(r<i.length)return bE(i,r,n,o);let s=i.map((c,l)=>Fh(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 Fh(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(po.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 bE(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(po.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await Fh(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Ul=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,SE=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,RE=5e3;function Mh(e,t,n){if(e<=1)return n?Math.max(Ul,n):Ul;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(SE/o),s=Math.max(RE,Math.min(i,Ul));return n?Math.max(s,n):s}async function Nh(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>async()=>{let{value:u,cacheHit:p}=await mf(()=>t(c,l));return{result:p&&u.status!=="error"?{...u,cache:1}:u,queryIndex:l,originalQuery:c}});return(await vh(s,{timeout:Mh(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{if(c.success&&c.data){let l=c.data.result,u=l&&Object.keys(l).some(d=>d!=="status"&&d!=="error"&&d!=="data");if(l&&l.error===void 0&&(l.data===null||l.data===void 0)&&!u&&l.status!=="error"){i.push({queryIndex:c.data.queryIndex,error:"Query resolved without a payload (possible timeout or resource exhaustion) \u2014 retry this query alone, with tighter caps if it was large"});return}o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}else c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}import{ContentSanitizer as CE}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as xE}from"@octocodeai/config";function wE(){try{return xE().output.format}catch{return"yaml"}}function Jt(e){if(e==null)return e;if(typeof e=="string")return CE.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Jt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))n!=="warnings"&&(t[n]=Jt(r));return t}return e}function PE(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(`
|
|
32
|
-
|
|
33
|
-
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Oo(e,t){let n=Io(e)??{},r=Jt(n),o=wE(),i="results"in r?["results","index","status","cache","meta","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Rs(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Rs(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Rs(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Rs(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Rs(n[o],t));return r}var TE=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"]),EE=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"];function AE(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=>TE.has(r))||EE.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Io(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=>Io(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(s==="warnings"||AE(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Io(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}import Dh from"node:path";import{fileURLToPath as LE}from"node:url";function _E(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 Hh=["path","uri","absolutePath"],Gh=new Set(["next","location"]);function jl(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)jl(i,t,n+1);return}let r=e,o=kE(r);o&&t.push({obj:r,abs:o});for(let[i,s]of Object.entries(r))Gh.has(i)||s&&typeof s=="object"&&jl(s,t,n+1)}function kE(e){let t=e.absolutePath;if(typeof t=="string"&&Dh.isAbsolute(t))return t;let n=e.uri;if(typeof n=="string"&&n.startsWith("file://"))try{return LE(n)}catch{return}let r=e.path;if(typeof r=="string"&&Dh.isAbsolute(r))return r}function Cs(e){let t=[];for(let i of e)jl(i?.data,t,0);if(t.length===0)return;let n=_E(t.map(i=>i.abs));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,abs:s}of t)s.startsWith(r)&&(i.path=s.slice(o),delete i.absolutePath,delete i.uri);return IE(e,r),n}function IE(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(Gh.has(s))continue;let a=i[s];typeof a=="string"?!Hh.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function OE(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 vE(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var FE=new Set([...Hh,"owner","repo","name","id","type","kind","reason","isPartial"]);function xs(e){let t=OE(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(FE.has(i))continue;let s=n[i];vE(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}function $l(e,t){let n=e,r=t,o=e.results;if(Array.isArray(o)){let i=o,s=Cs(i);s&&(n.base=s);let a=xs(i);a&&(n.shared=a),(s||a)&&(r=[...s?["base"]:[],...a?["shared"]:[],...t])}return{text:Oo(n,[...r]),structuredContent:Jt(Io(n)??{})}}function Wl(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(`
|
|
34
|
-
`,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 ME(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Wl(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function NE(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Wl(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 Vl(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=Wl(e,s,i),c=a<o,l=ME(e,s,i),u=NE(e,i),p=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
|
|
35
|
-
`:`# Response page ${l}/${u}.
|
|
36
|
-
`}${p}`,pagination:{scope:"content.text",currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Kl(e,t,n){return t?{...e,responsePagination:{...t,...t.hasMore&&n?{next:n}:{}}}:e}function Xl(e,t,n,r){if(!r?.hasMore||r.nextCharOffset===void 0)return;let o=t.map(i=>{let{goal:s,reasoning:a,...c}=i;return c});return{tool:e,query:{queries:o,responseCharLength:n?.responseCharLength,responseCharOffset:r.nextCharOffset}}}function jn(e,t){if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return e.some(r=>jn(r,t));let n=e;return t(n)||Object.values(n).some(r=>jn(r,t))}function ws(e,t){return e===null||typeof e!="object"?!1:Array.isArray(e)?e.some(n=>ws(n,t)):Object.entries(e).some(([n,r])=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r;if(t(n.toLowerCase())&&typeof o.tool=="string"&&o.query!==null&&typeof o.query=="object")return!0}return ws(r,t)})}function Bh(e){return e.truncated===!0||e.capReached===!0||e.capped===!0||e.capturesTruncated===!0||e.totalMatchesCapped===!0||e.complete===!1||e.incompleteResults===!0||e.incompleteTree===!0||e.possiblyTruncated===!0||e.truncatedByDepth===!0||e.truncatedByBudget===!0||Array.isArray(e.partialTreeFailures)&&e.partialTreeFailures.length>0}function Ps(e){return jn(e,t=>t.isPartial===!0||t.hasMore===!0||Bh(t))}function Yl(e){if(!Ps(e))return[];if(jn(e,a=>a.terminalLimit===!0))return["terminalLimitReached"];let t=jn(e,a=>a.hasMore===!0),n=jn(e,Bh),r=jn(e,a=>a.isPartial===!0),o=ws(e,a=>a.startsWith("next")||a.startsWith("continue")),i=ws(e,a=>a.startsWith("expand")||a.startsWith("retry")||a.startsWith("narrow")||a.startsWith("fallback")||a.startsWith("escalate")||a.startsWith("read")||a.includes("search")||a.includes("completeness"));return t&&!o||n&&!i||r&&!o&&!i?["continuationMissing"]:[]}var DE=3;async function ge(e,t,n,r){let o=n.concurrency??DE,{results:i,errors:s}=await Nh(e,t,o,n.minQueryTimeoutMs);return HE(n,i,s,e,r)}function HE(e,t,n,r,o){let i=["results","base","shared"],s=["index","status","cache","meta","evidence","diagnostics","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(y=>{let g=y.result.status,S=QE(y.result);c[y.queryIndex]={index:y.queryIndex,...g!==void 0?{status:g}:{},...y.result.cache===1?{cache:1}:{},meta:zh(e.toolName,y.originalQuery,S,g),data:S}}),n.forEach(y=>{let g=r[y.queryIndex];g&&(c[y.queryIndex]={index:y.queryIndex,status:"error",meta:zh(e.toolName,g,{error:y.error},"error"),data:{error:y.error}})});let l=c.filter(y=>y!==void 0);if(e.finalize){let y=e.finalize({queries:r,results:l,config:e}),g=GE(y.structuredContent,l),S=$l(g,y.keysPriority??a),R=y.renderText?y.renderText(S.structuredContent):S.text,C=Vl(R,o),P=Kl(S.structuredContent,C.pagination,Xl(e.toolName,r,o,C.pagination));return Qh(e.toolName,t,n,C.text.length),{content:[{type:"text",text:C.text}],structuredContent:P,isError:y.isError??(l.length>0&&l.every(T=>T.status==="error"))}}let p=$l({results:l},a),d=p.text,m=Vl(d,o),f=Kl(p.structuredContent,m.pagination,Xl(e.toolName,r,o,m.pagination));return Qh(e.toolName,t,n,m.text.length),{content:[{type:"text",text:m.text}],structuredContent:f,isError:l.length>0&&l.every(y=>y.status==="error")}}function GE(e,t){if(!Array.isArray(e.results))return e;let n=new Map(t.map(i=>[i.index,i])),r=e.shared!==null&&typeof e.shared=="object"&&!Array.isArray(e.shared)?e.shared:void 0,o=e.results.map((i,s)=>{if(i===null||typeof i!="object"||Array.isArray(i))return i;let a=i,c=(typeof a.index=="number"?n.get(a.index):void 0)??t[s];if(!c)return a;let{cache:l,...u}=a,p=a.data!==null&&typeof a.data=="object"&&!Array.isArray(a.data)?a.data:c.data,d=BE(a.meta??c.meta,r?{...r,...p}:p);return{...u,...c.cache===1?{cache:1}:{},meta:d}});return{...e,results:o}}function zh(e,t,n,r){let o=zE(e,t),i=n.confidence,s=r==="error"||i==="low"?"low":i==="high"||i==="medium"?i:o==="provider"||o==="lexical"||o==="syntactic"?"medium":"high",a=Ps(n),c=[...typeof n.errorCode=="string"?[n.errorCode]:[],...Yl(n)],l=c.length>0||a;return{evidence:{kind:o,confidence:s},...l?{diagnostics:{...c.length>0?{codes:c}:{},...a?{partial:!0}:{}}}:{}}}function BE(e,t){let{diagnostics:n,...r}=e,o=[...(n?.codes??[]).filter(a=>a!=="continuationMissing"&&a!=="terminalLimitReached"),...Yl(t)],i=Ps(t),s=o.length>0||i||(n?.hints?.length??0)>0;return{...r,...s?{diagnostics:{...o.length>0?{codes:o}:{},...n?.hints?.length?{hints:n.hints}:{},...i?{partial:!0}:{}}}:{}}}function zE(e,t){if(e==="localAnalyzeGraph")return"syntactic";if(e==="lspGetSemantics")return"semantic";if(e==="local.text")return t.mode==="structural"?"structural":"lexical";if(e==="localSearch"){let n=t.operation;return n==="structural"?"structural":n==="text"?"lexical":"exact"}return e.startsWith("gh")||e.startsWith("github.")||e==="npmSearch"?"provider":"exact"}function Qh(e,t,n,r){let o=t.reduce((i,s)=>i+(ie(s.result)??G(s.result)),0)+n.reduce((i,s)=>i+G(s),0);try{zc(e,o,r)}catch{}}function QE(e){let t=new Set(["status","cache","goal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}var Q={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"};var Uh={[Q.PATH_VALIDATION_FAILED]:{code:Q.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[Q.FILE_ACCESS_FAILED]:{code:Q.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[Q.FILE_READ_FAILED]:{code:Q.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[Q.FILE_TOO_LARGE]:{code:Q.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[Q.BINARY_FILE_UNSUPPORTED]:{code:Q.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[Q.NO_MATCHES]:{code:Q.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[Q.OUTPUT_TOO_LARGE]:{code:Q.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[Q.COMMAND_NOT_AVAILABLE]:{code:Q.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[Q.COMMAND_EXECUTION_FAILED]:{code:Q.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[Q.COMMAND_TIMEOUT]:{code:Q.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[Q.TOOL_EXECUTION_FAILED]:{code:Q.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[Q.LSP_SERVER_UNAVAILABLE]:{code:Q.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:'No language server available for semantic analysis \u2014 use localSearch operation:"text" or "structural", then localGetFileContent',recoverability:"user-action-required"}};var Ne=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Uh[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}
|
|
37
|
-
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 Zl(e){return e instanceof Ne}function jh(e,t=Q.TOOL_EXECUTION_FAILED,n){if(Zl(e))return e;if(e instanceof Error)return new Ne(t,e.message,n,e);let r=String(e);return new Ne(t,r,n)}function UE(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function N(e,t,n={}){let{extra:r}=n,o={status:"error"};if(UE(e))o.error=e;else if(Zl(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=jh(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:$(o,n.rawResponse)}function ut(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!0?`Validation error: ${o}`:o;return{ok:!1,error:N(i,t,{toolName:n.toolName})}}function me(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:$(s,o.rawResponse)}function Ts(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return N(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function He(e,t,n,r){let o=N(e,t,{toolName:r});return n&&typeof o.error=="string"&&(o.error=`${n}: ${o.error}`),o}async function yt({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return He(o,t,r,e)}}function Jl(e){return e.data!==void 0&&!e.error}import{maskSensitiveData as $h}from"@octocodeai/octocode-engine/mask";var ql=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function jE(){return tl().provider??el()}function $E(e){let t=tl(),n=t.provider??el(),{baseUrl:r,token:o}=t;try{let i=Ql(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=$h(s);throw new ql(n,`Failed to initialize ${n} provider: ${a}`)}}function et(e){let t;return()=>t??=$E(e)}function Es(e,t){return e.capabilities[t]}async function qt(e,t){let n=await t();return Jl(n)?{ok:!0,response:n}:{ok:!1,result:Ts(n,e)}}async function Wh(e,t){let n=t??jE(),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:$h(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Jl(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}import{existsSync as XE,mkdirSync as eu,renameSync as YE,rmSync as ZE}from"fs";import{join as Mo}from"path";import{createHash as JE}from"crypto";var As=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],vo=[...As,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Vh=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function Kh(e={},t=As){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}import{spawn as WE}from"child_process";var VE=10*1024*1024,KE=5e3;function Fo(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=As,maxOutputSize:a=VE}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),p=()=>l.stderrChunks.join(""),d={cwd:o,env:Kh(i,s),stdio:["ignore","pipe","pipe"]},m;try{m=WE(e,t,d)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let f,h=setTimeout(()=>{if(!l.killed){l.killed=!0;try{m.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{m.kill("SIGKILL")}catch{}},KE),c({stdout:u(),stderr:p(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),y=()=>{clearTimeout(h),f!==void 0&&(clearTimeout(f),f=void 0)},g=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{m.kill("SIGKILL")}catch{}y(),c({stdout:u(),stderr:p(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};m.stdout?.on("data",S=>{if(l.killed)return;let R=S.toString();l.totalOutputSize+=Buffer.byteLength(R),!g()&&l.stdoutChunks.push(R)}),m.stderr?.on("data",S=>{if(l.killed)return;let R=S.toString();l.totalOutputSize+=Buffer.byteLength(R),!g()&&l.stderrChunks.push(R)}),m.on("close",S=>{l.killed||(y(),c({stdout:u(),stderr:p(),exitCode:S,success:S===0}))}),m.on("error",S=>{l.killed||(l.killed=!0,y(),c({stdout:u(),stderr:p(),exitCode:null,success:!1,error:S}))})})}var Uj=1*1024*1024;function Xh(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var Yh=120*1e3,qE=30*1e3,eA=300*1e3,tA=100,Zh="clone-locks",nA="clone-tmp",Jh=[...vo,"GIT_TERMINAL_PROMPT"];async function qh(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await pA();let a=e.branch??await Me(r,o,t),c=Dt(),l=$c(c,r,o,a,i);return rA(c,l,async()=>{let u=xr(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Ui(c),bn(l);let p=uA(t,n),d=iA(c,l);Qi(d);try{if(i){if(await lA(r,o,a,d,i,p),!XE(Mo(d,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghSearch operation:"tree", then retry with the correct sparsePath (or omit it for a full clone).`)}else await cA(r,o,a,d,p);let m=wr(r,o,a,"clone",i);return Cr(d,m),sA(d,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(m){throw Qi(d),m}})}async function rA(e,t,n){bn(t);let r=oA(e,t);eu(Mo(e,"tmp",Zh),{recursive:!0,mode:448});let o=Date.now();for(;;)try{eu(r,{mode:448}),Wc(r);break}catch(i){if(i.code!=="EEXIST")throw i;if(zi(r))continue;if(Date.now()-o>eA)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await aA(tA)}try{return await n()}finally{ZE(r,{recursive:!0,force:!0})}}function eg(e){return JE("sha256").update(e).digest("hex").slice(0,16)}function oA(e,t){return Mo(e,"tmp",Zh,eg(t))}function iA(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Mo(e,"tmp",nA);return eu(r,{recursive:!0,mode:448}),Mo(r,`${eg(t)}-${n}`)}function sA(e,t){Qi(t),bn(t),YE(e,t)}function aA(e){return new Promise(t=>setTimeout(t,e))}async function cA(e,t,n,r,o){let i=ng(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",tg(e,t),r),await tu(i,Yh,`full clone of ${e}/${t}`,o)}async function lA(e,t,n,r,o,i){let s=ng(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",tg(e,t),r),await tu(s,Yh,`sparse clone of ${e}/${t}`,i),await tu(["-C",r,"sparse-checkout","set","--skip-checks","--",o],qE,`sparse-checkout set ${o}`,void 0)}function tg(e,t){return`https://github.com/${e}/${t}.git`}function ng(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function uA(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function pA(){try{if(!(await Fo("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Jh,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 dA(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 tu(e,t,n,r){let o=await Fo("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Jh,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=dA(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}import{getConfigSync as mA}from"@octocodeai/config";async function rg(e){let{queries:t,authInfo:n}=e,r=et(n);return ge(t,async(o,i)=>yt({toolName:I.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{if(mA().storage.mode==="memory")return N('Clone requires persistent local storage. Set storage.mode="persistent" or OCTOCODE_STORAGE_MODE=persistent to use ghCloneRepo.',o,{extra:{errorCode:"persistentStorageDisabled"}});let s=r();if(!Es(s,"cloneRepo"))return He(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",I.GITHUB_CLONE_REPO);let a;try{a=await qh(o,n,s.token)}catch(d){let m=d instanceof Error?d.message:String(d);return N(`Clone failed for ${o.owner}/${o.repo}: ${m}`,o)}a.cached&&Kt();let c=Oh(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,source:"clone",cached:a.cached,complete:!0,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={viewStructure:{tool:"localSearch",query:{operation:"tree",path:a.localPath},why:"Browse the cloned directory before choosing a text, structural, or file-discovery operation.",confidence:"exact"}},p={owner:o.owner,repo:o.repo,totalSize:c,location:l,next:u};return me(o,p,!0,I.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:I.GITHUB_CLONE_REPO,keysPriority:["totalSize","location","error"],minQueryTimeoutMs:13e4},e)}import{readdirSync as fA,statSync as og}from"node:fs";import{join as hA}from"node:path";var No=50,Ls=5*1024*1024,nu=300*1024,ig=5,gA=1e4,sg=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"]),ru={maxDirectoryFiles:No,maxTotalSize:Ls,maxFileSize:nu};function ou(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function ag(e){return Object.values(e).every(t=>t===0)}function iu(e,t){if(!t&&e)return["Cannot verify completeness against remote tree; use forceRefresh or ghCloneRepo if completeness matters."];if(!e)return["Directory materialization is partial; inspect skipped counts or use ghCloneRepo before repo-wide reachability/dead-code conclusions."]}async function cg(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 bA(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var yA=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function bA(e,t){try{let o=new URL(e);if(!yA.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(),gA);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 lg(e,t){let n=[],r=0;function o(i){let s;try{s=fA(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=hA(i,a);try{let l=og(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function ug(e){try{return og(e).size}catch{return 0}}import{writeFileSync as CA,mkdirSync as dg,existsSync as su,rmSync as xA}from"node:fs";import{join as mg,dirname as wA,resolve as fg,sep as hg}from"node:path";var SA=60;async function pg(e,t,n,r){let s=(await(await j(r)).rest.repos.getCommit({owner:e,repo:t,ref:n})).data.sha;if(typeof s!="string"||!/^[0-9a-f]{40}$/i.test(s))throw new Error(`GitHub returned an invalid commit SHA for ref "${n}".`);return s.toLowerCase()}async function RA(e,t,n,r){try{return{commitSha:await pg(e,t,n,r),resolvedRef:n}}catch(o){if(!(n==="main"||n==="master"))throw o;let s=await Me(e,t,r);if(s===n)throw o;return{commitSha:await pg(e,t,s,r),resolvedRef:s}}}async function _s(e,t,n,r,o=!1){let i=await ve(r),s=Ee("gh-api-ref-resolution",{owner:e,repo:t,ref:n,auth:i});return Fe(s,()=>RA(e,t,n,r),{ttl:SA,forceRefresh:o,cacheRole:"helper"})}async function au(e,t,n,r,o,i=!1){let s=Dt(),{commitSha:a,resolvedRef:c}=await _s(e,t,r,o,i),l=mo(s,e,t,a),u=fg(mg(l,n));if(!u.startsWith(l+hg)&&u!==l)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let p=xr(l);if(p.hit&&p.meta.commitSha===a&&!i&&su(u)){let w=lg(u,l),L=ou();return{localPath:u,repoRoot:l,files:w.files,fileCount:w.fileCount,totalSize:w.totalSize,complete:!0,verified:!1,commitSha:a,directoryEntryCount:w.fileCount,eligibleFileCount:w.fileCount,savedFileCount:w.fileCount,skipped:L,limits:ru,warnings:iu(!0,!1),cached:!0,expiresAt:p.meta.expiresAt,owner:e,repo:t,branch:c,directoryPath:n}}let d=await j(o),{data:m}=await d.rest.repos.getContent({owner:e,repo:t,path:n,ref:a});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=m,h=ou(),y=[];for(let w of f){if(w.type!=="file"){h.nonFile+=1;continue}if(!w.download_url){h.missingDownloadUrl+=1;continue}if(w.size>nu){h.oversized+=1;continue}let L=Gf(w.name,{lowercase:!0,leadingDot:!0});if(sg.has(L)){h.binary+=1;continue}y.push(w)}h.fileLimit=Math.max(0,y.length-No);let g=y.slice(0,No),S=o?.token,R=await cg(g,ig,S);h.fetchFailed=g.length-R.length;let C=0,P=[];for(let w=0;w<R.length;w+=1){let{entry:L,content:O}=R[w];if(C+O.length>Ls){h.totalSizeLimit=R.length-w;break}C+=O.length,P.push({entry:L,content:O})}Pr(s),bn(l),su(u)&&xA(u,{recursive:!0,force:!0}),dg(u,{recursive:!0,mode:448});let T=[];for(let{entry:w,content:L}of P){let O=fg(mg(l,w.path));if(!O.startsWith(l+hg)){h.pathTraversal+=1;continue}let v=wA(O);su(v)||dg(v,{recursive:!0,mode:448}),CA(O,L,"utf-8"),T.push({path:w.path,size:L.length,type:"file"})}let E=wr(e,t,c,"treeFetch",void 0,void 0,a);Cr(l,E);let k=ag(h),x=k,b=h.nonFile>0;return{localPath:u,repoRoot:l,files:T,fileCount:T.length,totalSize:C,complete:k,verified:x,commitSha:a,...b?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:y.length,savedFileCount:T.length,skipped:h,limits:ru,warnings:iu(k,x),cached:!1,expiresAt:E.expiresAt,owner:e,repo:t,branch:c,directoryPath:n}}import{writeFileSync as PA,mkdirSync as TA,existsSync as gg}from"node:fs";import{join as EA,dirname as AA,resolve as LA,sep as _A}from"node:path";async function cu(e,t,n,r,o,i=!1){let s=Dt(),{commitSha:a,resolvedRef:c}=await _s(e,t,r,o,i),l=mo(s,e,t,a),u=LA(EA(l,n));if(!u.startsWith(l+_A)&&u!==l)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let p=xr(l);if(!i&&p.hit&&p.meta.commitSha===a&&gg(u))return{localPath:u,repoRoot:l,path:n,size:ug(u),cached:!0,expiresAt:p.meta.expiresAt,owner:e,repo:t,branch:c,commitSha:a};let d=await Po({owner:e,repo:t,path:n,type:"file",branch:a,fullContent:!0,contextLines:0,minify:"none",goal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in d)||!d.data){let h="error"in d?d.error:void 0;throw new Error(h||`Failed to fetch ${e}/${t}/${n}`)}Pr(s),bn(l);let m=AA(u);gg(m)||TA(m,{recursive:!0,mode:448}),PA(u,d.data.rawContent,"utf-8");let f=wr(e,t,c,"treeFetch",void 0,void 0,a);return Cr(l,f),{localPath:u,repoRoot:l,path:n,size:d.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:c,commitSha:a}}function ks(e,t){return e&&t?`${e}/${t}`:void 0}function Is(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Os(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 IA(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function yg(e){return{keywords:e.keywords??[],projectId:ks(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,goal:e.goal,reasoning:e.reasoning}}function bg(e,t){let n=t.match==="path",r=new Map;for(let i of e.items){let s=i.repository.name||"",{owner:a,repo:c}=Is(s),l=`${a}/${c}`,u=r.get(l);if(u||(u={id:l,owner:a,repo:c,matches:[]},r.set(l,u)),n||!i.matches?.length){u.matches.push({path:i.path,...n?{}:{pathOnly:!0}});continue}let p=!1;for(let d of i.matches){if(!d.context)continue;let m=IA(d.context),f={path:i.path,value:m};if(d.positions?.length>0){let h=d.positions.filter(([,y])=>y<=m.length);h.length>0&&(f.matchIndices=h.map(([y,g])=>({start:y,end:g,lineOffset:(d.context??"").substring(0,y).split(`
|
|
38
|
-
`).length-1})))}u.matches.push(f),p=!0}p||u.matches.push({path:i.path,pathOnly:!0})}let o={results:Array.from(r.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(o.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Os(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),o}function Sg(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:t.size,created:t.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,license:t.license,forks:t.forks,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,goal:e.goal,reasoning:e.reasoning}}function Rg(e){return e.map(t=>{let{owner:n,repo:r}=Is(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function vs(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Cg(e){let t=(e.keywords??[]).filter(o=>o.trim()).map(vs),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ks(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),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,draft:e.draft,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.pageSize,sort:e.sort,order:e.order,limit:e.pageSize??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,goal:e.goal,reasoning:e.reasoning}}function OA(e,t){let n=[];t.some(o=>o.state==="APPROVED")&&n.push("approval"),t.some(o=>o.state==="CHANGES_REQUESTED")&&n.push("changes-requested");let r=e.filter(o=>!Un(o.author??"")).map(o=>o.body.toLowerCase());return n.length===0&&r.some(o=>/\b(lgtm|looks good|approved|ship it)\b/.test(o))&&n.push("approval"),!n.includes("changes-requested")&&r.some(o=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(o))&&n.push("changes-requested"),r.some(o=>o.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function vA(e,t){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(i=>i.author))),r=e.map(i=>i.updatedAt||i.createdAt).filter(Boolean).sort().at(-1),o=e.filter(i=>i.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:o,discussionComments:e.length-o,commenters:n.slice(0,8),commenterCount:n.length,...n.length>8?{commentersTruncated:!0}:{},...r?{latestCommentAt:r}:{},themes:OA(e,t??[])}}function xg(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=vA(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...Os(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pullRequests:r,...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},...o?{pagination:o}:{totalCount:e.totalCount||r.length}},pagination:o}}function wg(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,goal:e.goal,reasoning:e.reasoning}}function Pg(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.matchedLines?.length&&{matchedLines:e.matchedLines},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function lu(e,t){let n=e.include??[];return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Cn.ENTRIES_PER_PAGE,page:(()=>{let r=e.page;return typeof r=="number"?r:void 0})(),includeSizes:n.includes("sizes"),includeLanguages:n.includes("languages"),includeContributors:n.includes("contributors"),includeBranches:n.includes("branches"),includeTags:n.includes("tags"),goal:e.goal,reasoning:e.reasoning}}function Tg(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([g],[S])=>g==="."?-1:S==="."?1:g.localeCompare(S)).map(([g,S])=>({dir:g,files:S.files,folders:S.folders})),c=e.fileSizeMap,l={};if(c){for(let[g,S]of Object.entries(c))if(n[g]){let R=new Set(n[g].files);for(let[C,P]of Object.entries(S))if(R.has(C)){let T=g==="."?C:`${g}/${C}`;l[T]=P}}}let u=Object.values(n).reduce((g,S)=>(g.totalFiles+=S.files.length,g.totalFolders+=S.folders.length,g),{totalFiles:0,totalFolders:0}),p=e,d=e.summary.incompleteTree===!0,m=e.partialReasons&&e.partialReasons.length>0?e.partialReasons:d?["providerTreeTruncated"]:void 0,f=e.isPartial===!0||d,h=e.terminalLimit===!0||d,y={structure:a,...Object.keys(l).length>0&&{fileSizes:l},...p.languages?{languages:p.languages,dominantLanguage:p.dominantLanguage}:{},...p.contributors?{contributors:p.contributors,totalContributors:p.contributors.length}:{},...p.branches?{branches:p.branches,totalBranches:p.branches.length}:{},...p.tags?{tags:p.tags,totalTags:p.tags.length}:{},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders,...d?{incompleteTree:!0}:{}},...f?{isPartial:!0}:{},...h?{terminalLimit:!0}:{},...m?{partialReasons:m}:{}};return i&&(y.resolvedBranch=i),s&&(y.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)&&(y.pagination=e.pagination),y}function Fs(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function FA(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:Fs(t.status),retryAfterSeconds:Fs(t.retryAfter),rateLimitRemaining:Fs(t.rateLimitRemaining),rateLimitReset:Fs(t.rateLimitReset)}}return{message:"Provider error"}}function Eg(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=FA(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({index:n.index,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function Or(e,t,n){return{structuredContent:e,keysPriority:t,isError:n}}import{z as W}from"zod";var MA=W.object({currentPage:W.number(),totalPages:W.number(),hasMore:W.boolean(),nextPage:W.number().optional(),pageSize:W.number().optional(),totalItems:W.number().optional(),perPage:W.number().optional(),totalFound:W.number().optional(),returned:W.number().optional(),totalMatches:W.number().optional(),reportedTotalMatches:W.number().optional().describe("Provider-reported raw total (e.g. GitHub's match count) \u2014 may exceed what pagination can actually reach."),reachableTotalMatches:W.number().optional().describe("Matches reachable by walking pages (bounded by the provider's result window, e.g. GitHub caps at 1000); totalPages is computed from this, not from reportedTotalMatches."),totalMatchesKind:W.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:W.boolean().optional(),totalResults:W.number().optional(),itemsPerPage:W.number().optional()}),cW=W.object({charOffset:W.number(),charLength:W.number(),totalChars:W.number(),hasMore:W.boolean(),nextCharOffset:W.number().optional(),currentPage:W.number().optional(),totalPages:W.number().optional(),chunkMode:W.enum(["semantic","char-limit"]).optional()}),lW=W.object({tool:W.string(),query:W.record(W.string(),W.unknown()),why:W.string().optional(),confidence:W.enum(["exact","high","medium","low"]).optional()}),uW=MA.extend({filesPerPage:W.number().optional(),entriesPerPage:W.number().optional(),matchesPerPage:W.number().optional(),totalFiles:W.number().optional(),totalEntries:W.number().optional(),totalMatches:W.number().optional(),totalFilesFound:W.number().optional(),nextMatchPage:W.number().optional()}),NA=["goal","reasoning"];function DA(e){let t;for(let n of NA)n in e&&(t??={...e},delete t[n]);return t??e}function Ge(e,t,n="Continue to the next page of results."){return{tool:e,query:DA(t),why:n,confidence:"exact"}}function Ms(e,t,n,r){if(!n||!n.hasMore||n.nextCharOffset===void 0)return;let o=r?.includeCharLength!==!1;return{continueChars:{tool:e,query:{...t,charOffset:n.nextCharOffset,...o&&n.charLength!==void 0?{charLength:n.charLength}:{}}}}}var HA=["package.json",".yarnrc.yml","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","turbo.json","lerna.json","nx.json","babel.config.js","vite.config.ts","vite.config.js","webpack.config.js","rollup.config.js","jest.config.js","vitest.config.ts","commitlint.config.js","deno.json","deno.jsonc",".npmrc",".nvmrc",".node-version",".prettierrc",".prettierignore",".eslintignore",".stylelintrc",".editorconfig",".tool-versions","requirements.txt","pyproject.toml","setup.py","setup.cfg","Pipfile","tox.ini","environment.yml",".python-version","Gemfile",".ruby-version","composer.json","Cargo.toml","go.mod","go.work","mix.exs","rebar.config","pubspec.yaml","build.sbt","deps.edn","project.clj","Package.swift","CMakeLists.txt","Makefile.am","configure.ac","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","global.json","Directory.Build.props","Directory.Build.targets","packages.config","nuget.config","Dockerfile","docker-compose.yml","docker-compose.yaml",".dockerignore","Makefile","Vagrantfile","Chart.yaml","Procfile","Brewfile","serverless.yml","netlify.toml","vercel.json","renovate.json",".gitlab-ci.yml",".travis.yml","Jenkinsfile",".gitignore",".gitattributes",".gitmodules",".env",".env.example"],GA=new Set(HA),BA=["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","deno.lock","Pipfile.lock","poetry.lock","uv.lock","pdm.lock","pixi.lock","Gemfile.lock","composer.lock","Cargo.lock","Cargo.toml.orig","go.sum","Gopkg.lock","glide.lock","Package.resolved","pubspec.lock","flake.lock","MODULE.bazel.lock",".terraform.lock.hcl","mise.lock"],zA=new Set(BA),QA=[/\.lock$/],UA=[/^\.eslintrc(\..+)?$/,/^\.prettierrc(\..+)?$/,/^\.babelrc(\..+)?$/,/^eslint\.config\.(c|m)?js$/,/^\.env(\..+)?$/,/^tsconfig\..+\.json$/,/^\.stylelintrc(\..+)?$/,/^\.renovaterc(\..+)?$/,/\.csproj$/,/\.fsproj$/,/\.vbproj$/,/\.sln$/,/\.gemspec$/,/\.tf(vars)?$/],jA=[".toml",".ini",".cfg",".conf",".properties"],Lg=new Set(jA),$A=new Set(".md .mdx .markdown .rst .adoc .asciidoc .txt .text .rtf .org .textile .rdoc .pod .creole .wiki".split(" ")),Ag=new Set(["readme","license","licence","copying","notice","changelog","changes","history","authors","contributors","contributing","code_of_conduct","codeowners","install","citation"]),_g=new Set(".js .jsx .mjs .cjs .ts .tsx .mts .cts .py .pyi .pyx .rb .rake .php .go .rs .java .kt .kts .scala .groovy .clj .cljs .cljc .c .h .cc .cpp .cxx .hpp .hh .m .mm .cs .fs .vb .swift .dart .sh .bash .zsh .fish .ps1 .bat .cmd .vue .svelte .css .scss .sass .less .html .htm .sql .graphql .gql .proto .ex .exs .erl .lua .hs .pl .pm .r .jl".split(" "));function uu(e){let t=e.replace(/\\/g,"/"),n=t.lastIndexOf("/");return n===-1?t:t.slice(n+1)}function pu(e){let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""}function WA(e){if(!e)return!1;let t=uu(e);if(!t)return!1;if(GA.has(t))return!0;for(let r of UA)if(r.test(t))return!0;let n=pu(t);return!!(n&&Lg.has(n))}function VA(e){if(!e)return!1;let t=uu(e);if(!t)return!1;if(zA.has(t))return!0;for(let n of QA)if(n.test(t))return!0;return!1}function KA(e){let t=pu(e);if(t&&$A.has(t))return!0;if(t&&(_g.has(t)||Lg.has(t)))return!1;let n=(t?e.slice(0,e.length-t.length):e).toLowerCase().replace(/\..*$/,""),r=n.split(/[-_.]/)[0]??n;return Ag.has(n)||Ag.has(r)}function XA(e){let t=pu(e);return t!==""&&_g.has(t)}function Ns(e){if(!e)return;let t=uu(e);if(t){if(VA(t))return"lock";if(WA(t))return"config";if(KA(t))return"doc";if(XA(t))return"code"}}function Ds(e){return typeof e=="object"&&e!==null}function bt(e){return typeof e=="string"&&e.length>0?e:void 0}function tt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function kg(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function _t(e,t){return tt(e[t])??0}function YA(e){if(Ds(e))return{nonFile:_t(e,"nonFile"),missingDownloadUrl:_t(e,"missingDownloadUrl"),oversized:_t(e,"oversized"),binary:_t(e,"binary"),fileLimit:_t(e,"fileLimit"),fetchFailed:_t(e,"fetchFailed"),totalSizeLimit:_t(e,"totalSizeLimit"),pathTraversal:_t(e,"pathTraversal")}}function ZA(e){if(Ds(e))return{maxDirectoryFiles:_t(e,"maxDirectoryFiles"),maxTotalSize:_t(e,"maxTotalSize"),maxFileSize:_t(e,"maxFileSize")}}var JA=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function qA(e){if(!Ds(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 JA){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function eL(e,t){let{goal:n,reasoning:r,charOffset:o,...i}=t;return Ms("ghGetFileContent",{...i,charLength:e?.charLength??t.charLength},e)}function tL(e,t){if(t.matchString!==void 0)return;let n=tt(e.startLine),r=tt(e.endLine),o=tt(e.totalLines);if(e.isPartial!==!0||n===void 0||r===void 0||o===void 0||r>=o)return;let i=Math.max(1,r-n+1),s=r+1,a=Math.min(o,r+i);return{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,startLine:s,endLine:a,...t.minify!==void 0?{minify:t.minify}:{}},why:`Continue the file at lines ${s}-${a}.`,confidence:"exact"}}function nL(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"lspGetSemantics (definitions/references) only works on local files \u2014 clone this path locally, then run localSearch or lspGetSemantics on it",confidence:"exact"}}function Ig(){try{return Ef()}catch{return!1}}function rL(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"Clone this directory to retrieve content omitted by remote directory-fetch limits or failures.",confidence:"exact"}}function Og(e,t){let n=qA(e.pagination),r=Ig(),o=n?.hasMore===!0?void 0:tL(e,t),i={...eL(n,t),...o?{continueLines:o}:{},...r?{cloneForSemantics:nL(t)}:{}},s=bt(e.path)??String(t.path??""),a=s?Ns(s):void 0;return{path:s,content:typeof e.content=="string"?e.content:"",...a?{fileType:a}:{},localPath:bt(e.localPath),repoRoot:bt(e.repoRoot),contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:tt(e.totalLines),sourceChars:tt(e.sourceChars),resolvedBranch:bt(e.resolvedBranch),...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},pagination:n,...Object.keys(i).length>0?{next:i}:{},...e.isPartial===!0||n?.hasMore===!0?{isPartial:!0}:{},startLine:tt(e.startLine),endLine:tt(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},...Array.isArray(e.matchedLines)&&e.matchedLines.length>0?{matchedLines:e.matchedLines}:{},lastModified:bt(e.lastModified),lastModifiedBy:bt(e.lastModifiedBy),warnings:kg(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:bt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function vg(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Ds).map(p=>({path:bt(p.path)??"",size:tt(p.size)??0,type:bt(p.type)??"file"})),o=YA(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,p])=>p>0):[],a=s.length>0?Object.fromEntries(s):void 0,c=e.complete===!1,l=c?s.length>0?s.map(([p])=>p):["providerDirectoryIncomplete"]:[],u=c&&Ig();return{path:String(t.path??""),localPath:bt(e.localPath)??"",repoRoot:bt(e.repoRoot),fileCount:tt(e.fileCount)??r.length,totalSize:tt(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:tt(e.directoryEntryCount),eligibleFileCount:tt(e.eligibleFileCount),savedFileCount:tt(e.savedFileCount),skipped:o,limits:ZA(e.limits),warnings:kg(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:bt(e.resolvedBranch),...c?{isPartial:!0,partialReasons:l,...u?{next:{escalateToClone:rL(t)}}:{terminalLimit:!0}}:{}}}function Fg(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e;return typeof t.message=="string"?t.message:t.error===e?void 0:Fg(t.error)}function oL(e,t){let n=typeof t?.owner=="string"?t.owner:void 0,r=typeof t?.repo=="string"?t.repo:void 0;if(e.status==="error"){let i=e.data.error,s=Fg(i)??"File content query failed",a=/\b404\b|not found/i.test(s);return{...n?{owner:n}:{},...r?{repo:r}:{},...t?.path?{path:String(t.path)}:{},error:a&&n&&r?`${s} \u2014 verify the path (exact case, no leading slash) and branch; use ghSearch with operation:"tree", owner:"${n}", repo:"${r}"`:s}}let o={owner:n??"",repo:r??""};return t?.type==="directory"?o.directories=[vg(e.data,t)]:o.files=[Og(e.data,t??{})],o}function Mg(){return({queries:e,results:t})=>{let n=t.map(o=>({...o,data:oL(o,e[o.index])}));return Or({results:n},["results","index","status","meta","data","owner","repo","files","directories","path","content","fileType","totalLines","startLine","endLine","isPartial","pagination","error"],n.length>0&&n.every(o=>o.status==="error"))}}import{getConfigSync as Ng}from"@octocodeai/config";async function Dg(e){let{queries:t,authInfo:n}=e,r=et(n);return ge(t,async(o,i)=>{try{let s=ut(Xr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=a.minify??(a.fullContent===!0?"none":"standard"),l={...a,minify:c};if(l.type==="directory"){let p=iL(l);if(p)return p}let u=r();return l.type==="directory"?sL(l,n,u):aL(l,n,u)}catch(s){return He(s,o,void 0,I.GITHUB_FETCH_CONTENT)}},{toolName:I.GITHUB_FETCH_CONTENT,finalize:Mg()},e)}function iL(e){let t=Ng();if(!t.local.enabled)return N('Directory fetch requires local materialization. Set ENABLE_LOCAL=true to use type: "directory".',e,{extra:{errorCode:"localToolsDisabled"},rawResponse:0});if(!t.local.enableClone)return N('Directory fetch requires clone/materialization support. Set ENABLE_CLONE=true to use type: "directory".',e,{extra:{errorCode:"cloneDisabled"},rawResponse:0});if(t.storage.mode==="memory")return N('Directory fetch requires persistent local materialization. Set storage.mode="persistent" or OCTOCODE_STORAGE_MODE=persistent to use type: "directory".',e,{extra:{errorCode:"persistentStorageDisabled"},rawResponse:0})}async function sL(e,t,n){if(!Es(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",I.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return N("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Me(e.owner,e.repo,t),o=await au(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={viewStructure:{tool:"localSearch",query:{operation:"tree",path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return me(e,l,!0,I.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??G(o)})}async function aL(e,t,n){let r=await qt(e,()=>n.provider.getFileContent(wg(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"&&Ng().storage.mode==="persistent"?await cL(e,t):void 0,i={...Pg(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,commitSha:o.commitSha,...o.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return me(e,i,s,I.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function cL(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Me(e.owner,e.repo,t);return cu(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function Hg(e,t){return e.some(n=>{let r=t[n.index];return typeof r?.owner=="string"&&typeof r?.repo=="string"})}function Gg(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{},...t?.repoState?{repoState:t.repoState}:{}}}function lL(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function uL(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pL(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${uL(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function dL(e,t){return{...e,matches:t}}function du(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?lL(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:pL(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:dL(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 zg(e){let t=new Map;for(let{index: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,queryIndex:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function Bg(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryIndex??-1}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function Qg(e,t,n){if(t.length===0)return[];if(e.length===1){let i=t[0]?.queryIndex??0,s=n.get(i);return[{index:i,data:{files:Bg(t),...s?{pagination:s}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryIndex??0,a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{index:i,data:{files:Bg(r.get(i)),...s?{pagination:s}:{}}}})}function Ug(e,t,n){let r={};for(let o of e){let i=o.data.files[0];if(!i)continue;let s=t[o.index];if(s?.match==="path")continue;let c=(Array.isArray(s?.keywords)?s.keywords.filter(u=>typeof u=="string"):[])[0]??n[0];if(!c)continue;let l=e.length===1?"getLines":`getLines:${o.index}`;r[l]={tool:"ghGetFileContent",query:{owner:i.owner,repo:i.repo,path:i.path,matchString:c},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"low"}}return Object.keys(r).length>0?r:void 0}function Hs(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=new Set,s=[];t.forEach(x=>{if(x.status==="error")return;let b=Gg(x);b.repoState&&s.push({index:x.index,state:b.repoState,query:e[x.index]}),b.incompleteResults&&i.add(x.index),b.results.reduce((O,v)=>O+v.matches.length,0)===0&&o.push({index:x.index,...b.nonExistentScope?{nonExistentScope:!0}:{},...b.incompleteResults?{incompleteResults:!0}:{}});let L=b.results;n.push({index:x.index,groups:L}),b.pagination&&r.set(x.index,b.pagination)});let a=Array.from(new Set(e.flatMap(x=>{let b=x.keywords;return Array.isArray(b)?b.filter(w=>typeof w=="string"):[]}))),c=du(zg(n),a),l=Eg(t),u=e.some(x=>x.concise===!0),p=new Map(t.map(x=>[x.index,x])),d=Qg(e,c,r).map(x=>{let b=p.get(x.index)?.meta;return{...x,...b?{meta:b}:{}}}),m=Ug(d,e,a);if(m)for(let x of d){let b=d.length===1?"getLines":`getLines:${x.index}`,w=m[b];w&&(x.data.next={getLines:w})}if(u)for(let x of d)x.data.files=x.data.files.map(b=>`${b.owner}/${b.repo}:${b.path}`);let f=o.map(({index:x,nonExistentScope:b,incompleteResults:w})=>{let L=p.get(x)?.meta;return{index:x,status:"empty",...L?{meta:L}:{},data:{files:[],...b?{nonExistentScope:b}:{},...w?{incompleteResults:w}:{}}}}),h=l.map(({index:x,error:b})=>{let w=p.get(x)?.meta;return{index:x,status:"error",...w?{meta:w}:{},data:{error:b}}}),g={results:[...d,...f,...h].sort((x,b)=>x.index-b.index)},S=g.results,R=x=>S.find(b=>b.index===x),C=(x,b,w,L=!1)=>{let O=R(x);if(!O)return;let v=O.meta,A=v?.diagnostics;O.meta={evidence:v?.evidence??{kind:"provider",confidence:"medium"},diagnostics:{...A??{},codes:Array.from(new Set([...A?.codes??[],b])),hints:Array.from(new Set([...A?.hints??[],w])),...L||A?.partial?{partial:!0}:{}}}},P=(x,b,w)=>{let L=R(x);!L||!("files"in L.data)||(L.data.next={...L.data.next??{},[b]:w})};for(let x of i){C(x,"ghIncompleteResults","GitHub reported an incomplete search index result; retry, narrow the scope, or verify locally before concluding absence.",!0);let{goal:b,reasoning:w,...L}=e[x];P(x,"retry",{tool:"github.code",query:L,why:"Retry the same query because GitHub marked the result incomplete",confidence:"exact"})}let T=new Set(s.map(({index:x})=>x));for(let x of o){if(T.has(x.index)||!Hg([x],e))continue;let b=e[x.index];C(x.index,"ghScopedZeroUnproven","No indexed matches is unproven absence; verify the repository structure and search a bounded local copy before concluding."),P(x.index,"viewStructure",{tool:"github.tree",query:{owner:b.owner,repo:b.repo,path:""},why:"Verify that the scoped repository and path exist before concluding absence",confidence:"exact"})}let E=8,k=o.filter(({index:x,nonExistentScope:b,incompleteResults:w})=>{if(b||w)return!1;let L=e[x]?.keywords;return Array.isArray(L)&&L.length>E});if(k.length>0)for(let{index:x}of k){let b=e[x],w=Array.isArray(b.keywords)?b.keywords.filter(L=>typeof L=="string").slice(0,E):[];C(x,"ghQueryPossiblyTooComplex",`The query used more than ${E} keywords; narrow it before treating zero matches as absence.`),P(x,"retryNarrow",{tool:"github.code",query:{keywords:w,...typeof b.owner=="string"?{owner:b.owner}:{},...typeof b.repo=="string"?{repo:b.repo}:{},...typeof b.path=="string"?{path:b.path}:{},...typeof b.filename=="string"?{filename:b.filename}:{},...typeof b.extension=="string"?{extension:b.extension}:{},...typeof b.language=="string"?{language:b.language}:{},...b.match==="file"||b.match==="path"?{match:b.match}:{}},why:"Retry with a bounded keyword set to avoid silent under-matching",confidence:"low"})}for(let{index:x,state:b,query:w}of s)if(b.kind==="renamed"){let[L,O]=b.fullName.split("/");C(x,"ghRepoRenamed",`The repository was renamed to ${b.fullName}; retry against the renamed repository.`);let v=w?.keywords;P(x,"retryRenamed",{tool:"github.code",query:{owner:L,repo:O,...Array.isArray(v)?{keywords:v}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"})}else if(b.kind==="archived"){C(x,"ghRepoArchived","The repository is archived, so its code-search index may lag or be incomplete; verify its structure and search locally.");let L=w;typeof L?.owner=="string"&&typeof L.repo=="string"&&P(x,"viewStructure",{tool:"github.tree",query:{owner:L.owner,repo:L.repo,path:""},why:"Inspect the archived repository outside the code-search index",confidence:"exact"})}else{C(x,"ghRepoNotFound","The repository was not found or is private to this token; verify the spelling or discover the current repository name.");let L=w;typeof L?.repo=="string"&&P(x,"findRepository",{tool:"github.repositories",query:{keywords:[L.repo]},why:"Find the repository by name in case it moved or was renamed",confidence:"low"})}return Or(g,["results","index","status","meta","evidence","diagnostics","data","files","path","owner","repo","queryIndex","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","nonExistentScope","incompleteResults","error"],c.length===0&&l.length>0)}}function mL(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function fL(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function hL(e,t,n){try{let r=await j(n),{data:o}=await r.rest.repos.get({owner:e,repo:t}),i=`${e}/${t}`.toLowerCase();return o.full_name&&o.full_name.toLowerCase()!==i?{kind:"renamed",fullName:o.full_name}:o.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function jg(e,t,n=et(t.authInfo)){try{let r=fL(e);if(r)return N(r.error,e);if(!mL(e))return N("At least one search term or scope filter is required.",e);let o=n(),i=await qt(e,()=>o.provider.searchCode(yg(e)));if(i.ok===!1)return i.result;let s=bg(i.response.data,e);if(s.results.length===0&&e.owner&&e.repo){let a=await hL(String(e.owner),String(e.repo),t.authInfo);a&&(s.repoState=a)}return me(e,s,s.results.length>0,I.GITHUB_SEARCH_CODE,{rawResponse:i.response.rawResponseChars})}catch(r){return He(r,e,void 0,I.GITHUB_SEARCH_CODE)}}async function Gs(e,t,n){try{let r=await e.rest.repos.get({owner:t,repo:n}),[o,i]=r.data.full_name?.split("/")??[];return!o||!i?{owner:t,repo:n,renamed:!1}:{owner:o,repo:i,renamed:o!==t||i!==n}}catch{return{owner:t,repo:n,renamed:!1}}}function Wg(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function Bs(e){return!!(e.keywords&&e.keywords.length>0)}function Vg(e){return!!(Bs(e)||Wg(e)||e.owner||e.language||e.stars||e.updated||e.created||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function $g(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Kg(e){let t=Wg(e),n=Bs(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:$g(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:$g(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function Xg(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 Zg(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 Jg(e,t){return[...e].sort((n,r)=>{let o=gL(n,r,t.sort);if(o!==0)return o;let i=Yg(r,t)-Yg(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:mu(n).localeCompare(mu(r))})}function gL(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 Xg(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function Yg(e,t){let n=yL(t),r=mu(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,p)=>o===p||r===p?u+80:o.includes(p)||r.includes(p)?u+40:s.includes(p)?u+35:i.includes(p)?u+10:u,0)+(c&&a===c?20:0)}function yL(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function mu(e){return`${e.owner}/${e.repo}`}function fu(e){return{currentPage:e.currentPage,...e.totalMatchesKind!=="lowerBound"&&e.totalPages!==void 0?{totalPages:e.totalPages}:{},perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function hu(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function gu(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function qg(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??G(n.response.data??n.response)),0)}function bL(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt?t.createdAt.slice(0,10):void 0,updatedAt:t.updatedAt?t.updatedAt.slice(0,10):void 0,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function SL(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"github.tree",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"low"},searchCode:{tool:"github.code",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"low"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(bL),...o?{next:o}:{}}}}async function ey(e,t,n=et(t.authInfo)){let{authInfo:r}=t;try{if(!Vg(e))return N("At least one repository search term or filter is required.",e);let o=n(),i=Kg(e),{successes:s,failures:a}=await Wh(i.map(E=>({meta:{label:E.label,query:E.query},operation:()=>o.provider.searchRepos(Sg(E.query))}))),c=s.map(E=>({label:E.meta.label,query:E.meta.query,response:E.response})),l=a.map(E=>({label:E.meta.label,query:E.meta.query,response:E.response}));if(c.length===0){let E=l[0];return E?Ts(E.response,e):He(new Error("Repository search produced no provider results"),e,void 0,I.GITHUB_SEARCH_REPOSITORIES)}let u=e.limit,p=Jg(Zg(c.flatMap(E=>Rg(E.response.data.repositories))),e),d=u!=null?p.slice(0,u):p,m=c.length===1?c[0]:void 0,h=c.length>1?gu(c,p.length):m?.response.data.pagination,y=h?fu(h):void 0,g=d.length>0,S=SL({repositories:d,pagination:y},e),R=hu(l),C;if(e.owner&&Bs(e)){let E=(Array.isArray(e.keywords)?e.keywords:[e.keywords]).filter(x=>typeof x=="string"&&x.trim().length>0).slice(0,3),k=E.some(x=>d.some(b=>b.repo?.toLowerCase()===x.toLowerCase()));if(E.length>0&&!k)try{let x=await j(r);for(let b of E){let w=await Gs(x,String(e.owner),b);if(w.renamed){C={warning:`No repositories matched under owner "${e.owner}", but "${e.owner}/${b}" now resolves to "${w.owner}/${w.repo}" \u2014 the repository may have been transferred. Retry scoped to owner:"${w.owner}" (see next.retryUnderCanonicalOwner).`,next:{retryUnderCanonicalOwner:{tool:"github.repositories",query:{...e,owner:w.owner,keywords:[w.repo]},why:"Re-run scoped to the repository's current owner after a detected transfer.",confidence:"exact"}}};break}}}catch{}}let P=[...R??[],...C?[C.warning]:[],...!g&&!C?['No repositories matched. Keywords are ANDed \u2014 try fewer or broader keywords, drop a topic/filter (topics are sparse), or add match:"readme" for full-text search.']:[]],T={...S.data,...P.length>0?{warnings:P}:{},...C?{next:C.next}:{}};return me(e,T,g,I.GITHUB_SEARCH_REPOSITORIES,{rawResponse:qg([...c,...l])})}catch(o){return He(o,e,void 0,I.GITHUB_SEARCH_REPOSITORIES)}}function RL(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0,o=typeof r?.status=="number"?r.status:void 0,i=typeof t.path=="string"?t.path.replace(/\/+$/,""):"",s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):"",a=i.split("/").pop()||t.repo,c=o===404?{retryParent:{tool:"github.tree",query:{owner:t.owner,repo:t.repo,...s?{path:s}:{},...t.branch?{branch:t.branch}:{}},why:"Retry at the parent directory \u2014 the path or branch may be wrong.",confidence:"low"},searchPath:{tool:"github.code",query:{owner:t.owner,repo:t.repo,match:"path",keywords:[a]},why:"Locate the path by name in case it moved or was renamed.",confidence:"low"}}:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...c?{next:c}:{}}}function CL(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&xo(o))continue;let i=r.files.filter(a=>!Ar(a)),s=r.folders.filter(a=>!xo(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function ty(e,t,n=et(t.authInfo)){try{let r=n(),o=`${e.owner}/${e.repo}`,i=e.branch,s=i??await r.provider.resolveDefaultBranch(o),a=await qt(e,()=>r.provider.getRepoStructure(lu(e,s))),c=s,l;if(a.ok===!1&&i){let g=a.result.error;if((typeof g=="object"&&g!==null?g.status:void 0)===404){let R=await r.provider.resolveDefaultBranch(o);if(R!==i){let C=await qt(e,()=>r.provider.getRepoStructure(lu(e,R)));C.ok!==!1&&(a=C,c=R,l=`Branch/ref '${i}' was not found. Showing '${R}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(a.ok===!1)return RL(a.result,e);let u=CL(a.response.data.structure),p=Object.keys(u).length>0,d=Tg(a.response.data,e,u,c);l&&(d.branchFallback={requestedBranch:i,actualBranch:c,warning:l});let f=d.structure?.find(g=>(g.files?.length??0)>0),h=String(e.path??"").replace(/\/+$/,""),y=f?(()=>{let g=f.dir==="."?f.files[0]:`${f.dir}/${f.files[0]}`;return h?`${h}/${g}`:g})():void 0;return d.next={...y?{fetchFile:{tool:"ghGetFileContent",query:{owner:e.owner,repo:e.repo,path:y,...c?{branch:c}:{}},why:"Read the first listed file",confidence:"low"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:e.owner,repo:e.repo,path:String(e.path??""),type:"directory",...c?{branch:c}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},me(e,d,p,I.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:a.response.rawResponseChars})}catch(r){return He(r,e,"Failed to explore repository structure",I.GITHUB_VIEW_REPO_STRUCTURE)}}var yu=1e3,xL={"github.code":"code","github.repositories":"repositories","github.tree":"tree"};function ny(){return({queries:e,results:t})=>{let n=e.flatMap((d,m)=>d.operation==="code"?[{query:d,originalIndex:m}]:[]),r=new Map(n.map((d,m)=>[d.originalIndex,m])),o=n.map(d=>d.originalIndex),i=n.map(({query:d})=>{let{operation:m,...f}=d;return f}),s=t.filter(d=>r.has(d.index)).map(d=>({...d,index:r.get(d.index)})),a=wL(i,s).map(d=>({...d,index:o[d.index]??d.index})),c=new Set(o),l=t.filter(d=>!c.has(d.index)),u=[...a,...l].map(d=>PL(d,e[d.index])).sort((d,m)=>d.index-m.index);return Or({results:u},["results","index","status","meta","data","operation","files","repositories","structure","pagination","next","tool","query","why","confidence","error"],u.length>0&&u.every(d=>d.status==="error"))}}function wL(e,t){return e.length===0?[]:Hs()({queries:e,results:t,config:{toolName:"github.code"}}).structuredContent.results??[]}function PL(e,t){let n=t?.operation;if(!n||!t)return e;let r=bu({operation:n,...e.data}),o=EL(r),i=TL(o,n,t);return{...e,data:AL(i,n,t)}}function ry(e,t){let{goal:n,reasoning:r,...o}=e;return{...o,page:t}}function TL(e,t,n){if(!n)return e;let r=e.pagination;if(!r||typeof r!="object")return e;let o=r;if(o.hasMore!==!0)return e;let{nextPage:i,...s}=o,a=typeof o.perPage=="number"&&o.perPage>0?o.perPage:typeof n.pageSize=="number"&&n.pageSize>0?n.pageSize:void 0;if(o.totalMatchesCapped===!0&&typeof i=="number"&&a!==void 0&&(i-1)*a>=yu){let l=e.next&&typeof e.next=="object"?e.next:void 0,{nextPage:u,...p}=l??{};return{...e,pagination:{...s,continuationUnavailable:{reason:"providerResultCap",maxResults:yu}},...Object.keys(p).length>0?{next:p}:{}}}if(typeof i!="number"||!Number.isInteger(i))return{...e,terminalLimit:!0,pagination:{...s,continuationUnavailable:{reason:"missingProviderCursor"}}};if(i>1e3)return{...e,terminalLimit:!0,pagination:{...s,continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}};let c=e.next&&typeof e.next=="object"?e.next:{};return{...e,next:{...c,nextPage:{tool:"ghSearch",query:ry(n,i),why:`Continue ${t} results on page ${i}.`,confidence:"exact"}}}}function EL(e){let t=e.pagination;if(!t||typeof t!="object"||t.totalMatchesCapped!==!0)return e;let n=Array.isArray(e.partialReasons)?e.partialReasons.filter(r=>typeof r=="string"):[];return{...e,isPartial:!0,terminalLimit:!0,partialReasons:n.includes("providerResultCap")?n:[...n,"providerResultCap"],providerLimit:{reason:"providerResultCap",maxResults:yu}}}function AL(e,t,n){if(e.terminalLimit===!0)return e;let r=e.incompleteResults===!0,o=Array.isArray(e.partialReasons)?e.partialReasons.filter(l=>typeof l=="string"):[],i=o.includes("partialTreeFailures");if(!r&&!i)return e;let s=[...o,...r&&!o.includes("providerIncompleteResults")?["providerIncompleteResults"]:[]],a=e.next&&typeof e.next=="object"?e.next:{},c=typeof n.page=="number"&&Number.isInteger(n.page)?n.page:1;return{...e,isPartial:!0,partialReasons:s,next:{...a,...a.retry?{}:{retry:{tool:"ghSearch",query:ry(n,c),why:`Retry the same ${t} provider page because the provider reported incomplete results.`,confidence:"exact"}}}}}function bu(e){if(Array.isArray(e))return e.map(bu);if(!e||typeof e!="object")return e;let t=Object.fromEntries(Object.entries(e).map(([r,o])=>[r,bu(o)])),n=typeof t.tool=="string"?xL[t.tool]:void 0;if(n&&(t.tool="ghSearch",t.query&&typeof t.query=="object")){let r={...t.query};n==="tree"?(r.pageSize=r.itemsPerPage,delete r.itemsPerPage):n==="repositories"?(r.pageSize=r.limit,delete r.limit,r.topics=r.topicsToSearch,delete r.topicsToSearch):n==="code"&&(r.pageSize=r.limit,delete r.limit),t.query={operation:n,...r}}return t}async function oy(e){let t=et(e.authInfo);return ge(e.queries,n=>yt({toolName:mt,query:n,contextMessage:"ghSearch execution failed",execute:async()=>{let r=ar.safeParse(n);if(!r.success)throw r.error;return LL(r.data,e,t)}}),{toolName:mt,finalize:ny()},e)}async function LL(e,t,n){let{operation:r,...o}=e;switch(r){case"code":{let{pageSize:i,...s}=o,a={...s,limit:i};return jg(a,{...t,queries:[a]},n)}case"repositories":{let{topics:i,pageSize:s,...a}=o,c={...a,topicsToSearch:i,limit:s};return ey(c,{...t,queries:[c]},n)}case"tree":{let{pageSize:i,...s}=o;return ty({...s,itemsPerPage:i},{...t,queries:[{...s,itemsPerPage:i}]},n)}default:throw new Error("Unsupported ghSearch operation")}}function Su(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function $n(e,t){let n=e.map(u=>{let p=u.patch!==void 0?Su(u.patch,t.charOffset,t.charLength):void 0;return{filename:u.filename,status:u.status,additions:u.additions,deletions:u.deletions,...p!==void 0?{patch:p.patch,...p.patchPagination?{patchPagination:p.patchPagination}:{}}:{},...u.previous_filename?{previousFilename:u.previous_filename}:{}}}),r=Math.max(1,t.filePage??1),o=Math.max(1,t.itemsPerPage??20),i=n.length,s=Math.max(1,Math.ceil(i/o)),a=Math.min(r,s),c=(a-1)*o;return{files:n.slice(c,c+o),filesPagination:{currentPage:a,totalPages:s,itemsPerPage:o,totalFiles:i,hasMore:a<s,...a<s&&a<1e3?{nextFilePage:a+1}:{},...a<s&&a>=1e3?{terminalLimit:!0,continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}:{}}}}async function iy(e,t){try{let o=(await(await j(t)).rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:e.ref})).data,i=o.files??[],s=e.path,a=s?i.filter(f=>f.filename===s||f.previous_filename===s||f.filename.startsWith(s.endsWith("/")?s:`${s}/`)):i,c=o.commit.author,l=o.commit.committer,u=o.author?.login,p=o.committer?.login,d=o.commit.message,m={type:"commit",owner:e.owner,repo:e.repo,ref:e.ref,sha:o.sha,message:d,messageHeadline:d.split(`
|
|
39
|
-
`)[0]??d,author:{name:c?.name??"unknown",email:c?.email??"",...u?{login:u}:{},...c?.date?{date:c.date}:{}},...l?{committer:{name:l.name??"unknown",email:l.email??"",...p?{login:p}:{},...l.date?{date:l.date}:{}}}:{},parents:o.parents.map(f=>f.sha),...o.stats?.additions===void 0?{}:{additions:o.stats.additions},...o.stats?.deletions===void 0?{}:{deletions:o.stats.deletions},changedFiles:a.length};return e.includeDiff?{data:{...m,...$n(a,{filePage:e.filePage,itemsPerPage:e.itemsPerPage,charOffset:e.charOffset,charLength:e.charLength})},status:200}:{data:m,status:200}}catch(n){return J(n)}}var _L=/^(\d+)\s*([hdwmy])$/i;function Ru(e){let t=e.trim(),n=_L.exec(t);if(n){let r=Number(n[1]),o=n[2].toLowerCase(),i=new Date;switch(o){case"h":i.setUTCHours(i.getUTCHours()-r);break;case"d":i.setUTCDate(i.getUTCDate()-r);break;case"w":i.setUTCDate(i.getUTCDate()-r*7);break;case"m":i.setUTCMonth(i.getUTCMonth()-r);break;case"y":i.setUTCFullYear(i.getUTCFullYear()-r);break}return{value:i.toISOString()}}return Number.isNaN(Date.parse(t))?{warning:`"${e}" is not a valid date or relative window \u2014 use e.g. "30d", "2w", "6m", "1y", or an ISO date like "2026-01-01". Filter skipped.`}:{value:t}}var kL=5;function zs(e){return e?e.includes('rel="next"'):!1}async function IL(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function sy(e,t,n){let r=await ve(t),o=Ee("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,committer:e.committer,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return Fe(o,()=>OL(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function OL(e,t){try{let n=await j(t),r=[],o=e.since?Ru(e.since):void 0,i=e.until?Ru(e.until):void 0;o?.warning&&r.push(`since ${o.warning}`),i?.warning&&r.push(`until ${i.warning}`);let s={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...o?.value?{since:o.value}:{},...i?.value?{until:i.value}:{},...e.author?{author:e.author}:{},...e.committer?{committer:e.committer}:{}},a=await n.rest.repos.listCommits(s),c=a.headers.link,l=zs(c),u=a.data.map(g=>{let S=g.commit.author,R=g.commit.committer,C=R?.date??S?.date??"",P=g.commit.message,T=P.split(`
|
|
40
|
-
`)[0]??P,E=P.slice(T.length).trim(),k=E.length>500,x=E.length===0?T:`${T}
|
|
41
|
-
${k?`${E.slice(0,500)}\u2026`:E}`,b=R?.name===S?.name&&R?.email===S?.email||g.committer?.login==="web-flow";return{sha:g.sha,date:C,...x===T?{}:{message:x},...k?{messageTruncated:!0}:{},messageHeadline:T,author:{name:S?.name??"unknown",email:S?.email??"",...g.author?.login?{login:g.author.login}:{}},...R&&!b?{committer:{name:R.name??"unknown",email:R.email??"",...g.committer?.login?{login:g.committer.login}:{}}}:{}}});u.length===0&&(o?.value!==void 0||i?.value!==void 0)&&r.push("no commits matched the since/until window \u2014 GitHub filters by committer date (not author date; rebases and squash-merges reset it), and a path-scoped walk does not follow renames. Widen or drop since/until and inspect commit dates directly.");let p={currentPage:e.page,perPage:e.perPage,hasMore:l,...l?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:u,pagination:p,...r.length?{warnings:r}:{}},status:200};let d=!1,m=!1,f=await IL(u,kL,async(g,S)=>{try{let R=a.data[S]?.sha??g.sha,C=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:R});if(e.type==="file"&&e.path){let P=e.path,T=C.data.files?.find(x=>x.filename===P||x.previous_filename===P);if(T){let x=T.patch!==void 0?Su(T.patch,e.charOffset,e.charLength):void 0;return{...g,additions:T.additions,deletions:T.deletions,status:T.status,...x!==void 0?{patch:x.patch,...x.patchPagination?{patchPagination:x.patchPagination}:{}}:{},...T.previous_filename?{previousFilename:T.previous_filename}:{}}}let E=P.endsWith("/")?P:`${P}/`,k=(C.data.files??[]).filter(x=>x.filename.startsWith(E));return k.length>0?(d=!0,{...g,...$n(k,e)}):(m=!0,g)}else{let P=e.path,T=(C.data.files??[]).filter(E=>!P||E.filename.startsWith(P));return{...g,...$n(T,e)}}}catch{}return g}),h=[];d&&h.push(`path '${e.path}' matched no single file in these commits but matches files under it \u2014 treated as a directory filter and returned per-commit changed files (append '/' to select directory mode explicitly).`),m&&h.push(`includeDiff: some commits contain no file matching '${e.path}' (rename or shallow diff?) \u2014 those commits are listed without a diff.`);let y=[...r,...h];return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:f,pagination:p,...y.length?{warnings:y}:{}},status:200}}catch(n){return J(n)}}async function ay(e,t){try{let o=(await(await j(t)).rest.repos.compareCommitsWithBasehead({owner:e.owner,repo:e.repo,basehead:`${e.base}...${e.head}`})).data,i=(o.commits??[]).map(l=>({sha:l.sha,messageHeadline:(l.commit.message??"").split(`
|
|
42
|
-
`)[0]??"",author:l.commit.author?.name??l.author?.login??"unknown",date:l.commit.author?.date??""})),s=o.files??[],a=e.path?s.filter(l=>l.filename===e.path):s,c;if(e.includeDiff){let l=$n(a,{filePage:e.filePage,itemsPerPage:e.itemsPerPage,charOffset:e.charOffset,charLength:e.charLength});c={files:l.files,filesPagination:l.filesPagination}}else c={changedFiles:a.length};return{data:{type:"compare",owner:e.owner,repo:e.repo,base:e.base,head:e.head,status:o.status,aheadBy:o.ahead_by,behindBy:o.behind_by,totalCommits:o.total_commits,commits:i,...c},status:200}}catch(n){return J(n)}}async function Cu(e,t,n,r=de){let o=t;if(!o.owner||!o.repo)return N("owner and repo are required for commits mode.",e);if(o.base&&o.head){let m=await ay({owner:o.owner,repo:o.repo,base:o.base,head:o.head,includeDiff:!!o.includeDiff,path:o.path,filePage:typeof o.filePage=="number"?o.filePage:void 0,itemsPerPage:o.pageSize,charOffset:typeof o.charOffset=="number"?o.charOffset:void 0,charLength:typeof o.charLength=="number"?o.charLength:void 0},n);if(Lt(m))return N(m,e,{toolName:r});let f=m.data,h=m.data.filesPagination,y=m.data.files?.find(R=>typeof R.patchPagination?.nextCharOffset=="number"),g={},S={operation:"compare",owner:o.owner,repo:o.repo,base:o.base,head:o.head,...o.includeDiff?{includeDiff:!0}:{},...o.path?{path:o.path}:{},...o.filePage===void 0?{}:{filePage:o.filePage},...o.pageSize===void 0?{}:{pageSize:o.pageSize},...o.charOffset===void 0?{}:{charOffset:o.charOffset},...o.charLength===void 0?{}:{charLength:o.charLength}};return typeof h?.nextFilePage=="number"&&(g.nextFilePage={tool:"ghGetHistoryItem",query:{...S,filePage:h.nextFilePage},why:"Continue the changed-file list.",confidence:"exact"}),typeof y?.patchPagination?.nextCharOffset=="number"&&(g.continuePatch={tool:"ghGetHistoryItem",query:{...S,charOffset:y.patchPagination.nextCharOffset},why:"Continue the current patch window.",confidence:"exact"}),me(e,Object.keys(g).length>0?{...f,next:g}:f,m.data.totalCommits>0||m.data.status!=="identical",r)}let i=o.path,s=i&&!i.endsWith("/")?"file":"repo";if(s==="file"&&!i)return N("path is required when querying a specific file in commits mode.",e);let a=await sy({type:s,owner:o.owner,repo:o.repo,path:i,branch:o.branch,since:o.since,until:o.until,author:o.author,committer:o.committer,page:Number(o.page)||1,perPage:Number(o.pageSize)||30,filePage:typeof o.filePage=="number"?o.filePage:void 0,itemsPerPage:typeof o.pageSize=="number"?o.pageSize:void 0,includeDiff:!!o.includeDiff,charOffset:typeof o.charOffset=="number"?o.charOffset:void 0,charLength:typeof o.charLength=="number"?o.charLength:void 0},n);if(Lt(a))return N(a,e,{toolName:r});let{commits:c}=a.data,l=c.length>0,u=c.map(m=>m.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),p=!l&&a.data.warnings?.length?{hints:a.data.warnings}:{},d={...a.data,...p,...u?{next:{prDetail:{tool:"ghGetHistoryItem",query:{operation:"pullRequest",owner:o.owner,repo:o.repo,number:Number(u)},why:`Open PR #${u} referenced by the first commit for review context`,confidence:"low"}}}:{}};return me(e,d,l,r,{rawResponse:a.rawResponseChars})}function St(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function xu(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(vs),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function cy(e,t,n){if(!n&&!t)return{text:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{text:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Qs(e){return e.pull_request!=null}function vL(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function Us(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:vL(e.labels),createdAt:e.created_at??"",updatedAt:e.updated_at??"",...e.closed_at?{closedAt:e.closed_at}:{}}}function vr(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function wu(e,t,n="anon"){return Ee("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:xu(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,locked:e.locked,visibility:e.visibility,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}import{ContentSanitizer as ly}from"@octocodeai/octocode-engine/contentSanitizer";async function uy(e,t){let n=St(e.owner),r=St(e.repo),o=e.issueNumber;if(!n||!r||o==null)return vr("owner, repo, and issueNumber are required for issue detail mode.");let i=await j(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(Qs(s.data))return vr(`Issue #${o} is a pull request; use ghGetHistoryItem operation:"pullRequest" with number:${o}.`,[`Retry with ghGetHistoryItem { operation: "pullRequest", owner: "${n}", repo: "${r}", number: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,l=e.content?.comments?.includeBots===!0,u=Us(s.data),p={};if(a){let d=ly.sanitizeContent(s.data.body??"").content,m=cy(d,e.charOffset,e.charLength);u.body=m.text,m.pagination&&(p.body=m.pagination)}if(c){let d=Math.max(1,e.commentPage??1),m=Math.max(1,e.itemsPerPage??30),f=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:m,page:d}),h=l?f.data:f.data.filter(g=>!Un(g.user?.login??""));u.comments=h.map(g=>({id:String(g.id),user:g.user?.login??"unknown",body:ly.sanitizeContent(g.body??"").content,createdAt:g.created_at??"",updatedAt:g.updated_at??"",commentType:"discussion"}));let y=zs(f.headers.link);p.comments={currentPage:d,itemsPerPage:m,totalComments:u.comments.length,hasMore:y,...y&&d<1e3?{nextCommentPage:d+1}:{},...y&&d>=1e3?{terminalLimit:!0,continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}:{}}}return Object.keys(p).length>0&&(u.contentPagination=p),{data:{type:"issues",owner:n,repo:r,issues:[u],totalCount:1},status:200}}async function py(e,t,n){let r=St(t.owner)??"",o=St(t.repo)??"",i=await j(n),s=[],a=e;if(r&&o){let g=await Gs(i,r,o);g.renamed&&(s.push(`Repository ${r}/${o} was renamed to ${g.owner}/${g.repo} \u2014 GitHub search does not follow renames, so the canonical name was searched instead.`),a={...e,owner:g.owner,repo:g.repo})}let c=gl(a),l=Math.min(t.limit??30,100),u=t.page??1,p=t.sort&&t.sort!=="best-match"?t.sort:void 0,d=await i.rest.search.issuesAndPullRequests({q:c,sort:p,order:t.order||"desc",per_page:l,page:u}),m=Qf(d.headers);m&&s.push(m);let f=(d.data.items??[]).filter(g=>!Qs(g)).map(g=>Us(g)),h=d.data.total_count??f.length,y=u*l<h&&f.length===l;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?f.map(g=>`#${g.number} ${g.title}`):f,totalCount:h,effectiveQuery:c,...s.length?{warnings:s}:{},...d.data.incomplete_results?{incompleteResults:!0}:{},pagination:{currentPage:u,perPage:l,hasMore:y,...y?{nextPage:u+1}:{},...h>1e3?{totalMatchesCapped:!0}:{}}},status:200}}async function dy(e,t){let n=St(e.owner),r=St(e.repo);if(!n||!r)return vr("owner and repo are required for issues mode.");let o=await j(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),l=c.data.filter(m=>!Qs(m)).map(m=>Us(m)),u=zs(c.headers.link),p=!u&&s===1,d=[];return l.length===0&&u&&d.push("This page contained only pull requests (the GitHub issues endpoint returns both; PRs are filtered out) \u2014 follow pagination.nextPage, later pages may contain issues."),{data:{type:"issues",owner:n,repo:r,issues:e.concise?l.map(m=>`#${m.number} ${m.title}`):l,...p?{totalCount:l.length}:{},...d.length?{warnings:d}:{},pagination:{currentPage:s,perPage:i,hasMore:u,...u?{nextPage:s+1}:{}}},status:200}}async function Pu(e,t,n){let r=await ve(t),o=wu(e,n,r);return Fe(o,()=>FL(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function FL(e,t){try{if(e.state==="merged"){let r={owner:St(e.owner)??"",repo:St(e.repo)??"",state:"merged"};return vr('state:"merged" is not valid for issues \u2014 use "open" or "closed".',[`Use ghSearchHistory with ${JSON.stringify({operation:"pullRequests",...r})}.`])}if(e.issueNumber!=null)return await uy(e,t);let n={...e,query:xu(e)};return yl(n)?await py(n,e,t):await dy(e,t)}catch(n){return Ht(n)?{data:{type:"issues",owner:St(e.owner)??"",repo:St(e.repo)??"",issues:[],totalCount:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:J(n)}}async function Tu(e,t,n,r=de){let o=t;if(!o.owner||!o.repo)return N("owner and repo are required for issues mode.",e);let i=o.issueNumber??o.prNumber,s=await Pu({owner:o.owner,repo:o.repo,...i!=null?{issueNumber:i}:{},keywordsToSearch:o.keywords,query:o.query,state:o.state,author:o.author,assignee:o.assignee,mentions:o.mentions,commenter:o.commenter,label:o.label,milestone:o.milestone,created:o.created,updated:o.updated,closed:o.closed,comments:o.comments,reactions:o.reactions,locked:o.locked,visibility:o.visibility,match:o.match,archived:o.archived,sort:o.sort,order:o.order,limit:o.pageSize,page:Number(o.page)||1,concise:o.concise,content:o.content,charOffset:o.charOffset,charLength:o.charLength,commentPage:o.commentPage,itemsPerPage:o.pageSize},n);if(Lt(s))return N(s,e,{toolName:r});if(i!=null&&Array.isArray(s.data.issues)){let d=s.data.issues[0];if(d&&typeof d=="object"&&d.contentPagination){let m=d.contentPagination,f={operation:"issue",owner:o.owner,repo:o.repo,number:i,content:o.content,...o.commentPage===void 0?{}:{commentPage:o.commentPage},...o.charLength===void 0?{}:{charLength:o.charLength}},h=m.body;typeof h?.nextCharOffset=="number"&&(h.nextQuery={...f,charOffset:h.nextCharOffset});let y=m.comments;typeof y?.nextCommentPage=="number"&&(y.nextQuery={...f,commentPage:y.nextCommentPage})}}let a=Array.isArray(s.data.issues)?s.data.issues.length>0:!1,c=!a&&s.data.warnings?.length?{hints:s.data.warnings}:{},l=s.data.issues,u=(()=>{if(!Array.isArray(l)||l.length===0)return;let d=l[0];if(typeof d=="number")return d;if(typeof d=="string"){let m=d.match(/^#(\d+)\b/);return m?Number(m[1]):void 0}if(d&&typeof d=="object"&&typeof d.number=="number")return d.number})(),p={};return i==null&&u!=null&&(p.readIssue={tool:"ghGetHistoryItem",query:{operation:"issue",owner:o.owner,repo:o.repo,number:u,content:{body:!0}},why:`Read issue #${u} body/discussion from this list`,confidence:"low"}),p.searchRepositoryCode={tool:"ghSearch",query:{operation:"code",owner:o.owner,repo:o.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"low"},me(e,{...s.data,...c,next:p},a,r,{rawResponse:s.rawResponseChars})}function ML(e){let t=e?.patches;return t?.mode?{mode:t.mode,...t.files?{files:t.files}:{},...t.ranges?{ranges:t.ranges}:{}}:{mode:"none"}}function NL(e){let t=e?.comments;return t?{discussion:t.discussion??!0,reviewInline:t.reviewInline??!0,includeBots:t.includeBots??!1,...t.file?{file:t.file}:{}}:!1}function DL(e){let t=e?.commits;return t?{list:!0,includeFiles:t.includeFiles??!1}:!1}function my(e){let{content:t}=e,n=ML(t),r=NL(t),o=DL(t);return{body:t?.body??!1,changedFiles:(t?.changedFiles??!1)||n.mode!=="none",patches:n,comments:r,reviews:t?.reviews??!1,commits:o}}function xn(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Eu(e,t){return xn(Object.fromEntries(t.map(n=>[n,e[n]])))}function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wn(e){return e===!0?!0:void 0}function HL(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{if(!Do(n)||typeof n.file!="string")return[];let r=Array.isArray(n.additions)?n.additions.filter(i=>typeof i=="number"):void 0,o=Array.isArray(n.deletions)?n.deletions.filter(i=>typeof i=="number"):void 0;return[xn({file:n.file,...r?.length?{additions:r}:{},...o?.length?{deletions:o}:{}})]});return t.length>0?t:void 0}function fy(e){if(!Do(e))return;let t=Do(e.comments)?xn({discussion:Wn(e.comments.discussion),reviewInline:Wn(e.comments.reviewInline),includeBots:Wn(e.comments.includeBots),file:typeof e.comments.file=="string"?e.comments.file:void 0}):void 0,n=Do(e.commits)?xn({includeFiles:Wn(e.commits.includeFiles)}):void 0,r=Do(e.patches)?xn({mode:e.patches.mode==="all"||e.patches.mode==="selected"?e.patches.mode:void 0,files:Array.isArray(e.patches.files)?e.patches.files.filter(i=>typeof i=="string"):void 0,ranges:HL(e.patches.ranges)}):void 0,o=xn({body:Wn(e.body),changedFiles:Wn(e.changedFiles),...r&&Object.keys(r).length>0?{patches:r}:{},...t&&Object.keys(t).length>0?{comments:t}:{},reviews:Wn(e.reviews),...n&&Object.keys(n).length>0?{commits:n}:{}});return Object.keys(o).length>0?o:void 0}function hy(e,t,n={}){let r={...e,...n},o=fy(e.content),i=fy(n.content),s=o||i?{...i??{},...o??{}}:void 0;return xn({operation:"pullRequest",owner:e.owner,repo:e.repo,number:t,...Eu(r,["pageSize","filePage","commentPage","commitPage","charOffset","commentBodyOffset","charLength","matchString","minify"]),...s?{content:s}:{}})}function Au(e,t={}){let n={...e,...t};return xn({operation:"commit",...Eu(n,["owner","repo","ref","includeDiff","path","filePage","pageSize","charOffset","charLength"])})}var GL={pullRequests:["keywords","owner","repo","concise","state","assignee","author","commenter","mentions","review-requested","reviewed-by","label","checks","review","head","base","created","updated","closed","merged-at","comments","reactions","draft","match","sort","order","archived","minify","pageSize"],issues:["owner","repo","keywords","concise","state","author","assignee","commenter","mentions","label","created","updated","closed","comments","reactions","match","sort","order","archived","minify","pageSize"],commits:["owner","repo","path","since","until","branch","author","committer","pageSize"]};function Lu(e,t,n){return{operation:t,...Eu(e,GL[t]),page:n}}function Ho(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Mr(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Go(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&&s<1e3?{nextPage:s+1}:{},...s<i&&s>=1e3?{terminalLimit:!0,continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}:{}}}}function Vn(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 js(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function gy(e,t){return{operation:"pullRequest",owner:e.owner,repo:e.repo,number:t}}function Bo(e,t,n){return hy(e,t,n)}function _u(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Bo(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function $s(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Bo(e,t,{content:n,[r]:o.nextPage,pageSize:e.pageSize})}function Nr(e){return typeof e=="object"&&e!==null}function Ws(e){if(Nr(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Vs(e){if(Nr(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function BL(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 yy(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=BL(r,n.comments),i=Ho(t),s=i?o.filter(l=>Mr(l.body,i)):o,{items:a,pagination:c}=Go(s,t.commentPage??t.page??1,t.pageSize??20);return{comments:a.map(l=>{let u=Vn(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:js(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),contentPagination:{comments:c}}}function by(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Ho(t);return{reviews:(o?r.filter(s=>Mr(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Vn(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 Sy(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Go(r,t.commitPage??t.page??1,t.pageSize??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}:{}})),contentPagination:{commits:i}}}function Ks(e){return String(e.path??e.filename??"")}function zL(e,t){return{path:Ks(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function Ry(e,t,n){let r=Array.isArray(e.fileChanges)?e.fileChanges:[],o=n.patches.files,i=o&&o.length>0?r.filter(d=>o.includes(Ks(d))):r,s=Ho(t),a=s?i.filter(d=>Mr(Ks(d),s)||Mr(d.patch,s)):i,{items:c,pagination:l}=Go(a,t.filePage??t.page??1,t.pageSize??20),u=n.patches.mode!=="none",p=c.map(d=>{let m=zL(d,!1);if(!u||typeof d.patch!="string")return m;let f=Vn(d.patch,t.charOffset??0,t.charLength??12e3);return{...m,patch:f?.content??"",...f?{patchPagination:f.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,contentPagination:{changedFiles:l}}:r.length===0?{}:{filePathsPreview:r.slice(0,20).map(Ks).filter(Boolean),contentPagination:{filePaths:{totalFiles:r.length,filesPerPage:20,hasMore:r.length>20,...r.length>20?{nextFilePage:2}:{}}}}}function wn(e,t){return{...e,content:t}}function Cy(e,t,n,r){let o=gy(e,t);return{target:o,...n.body?{}:{getBody:wn(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:wn(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:wn(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:wn(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:wn(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:wn(o,{reviews:!0})},...n.commits?{}:{getCommits:wn(o,{commits:{}})},fullReview:wn(o,{body:!0,changedFiles:!0,patches:{mode:"all"},comments:{discussion:!0,reviewInline:!0},reviews:!0,commits:{}})}}function QL(e){return e.replace(/\n{3,}/g,`
|
|
43
|
-
|
|
44
|
-
`)}function UL(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function jL(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Nr(n))continue;let r=Vs(n.patchPagination);if(r?.hasMore)return r}}function $L(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Nr(n))continue;let r=Vs(n.bodyPagination);if(r?.hasMore)return r}}function WL(e,t,n,r,o){let i={},s=Vs(t.body),a=Ws(t.changedFiles),c=Ws(t.comments),l=Ws(t.commits),u=jL(e),p=$L(e),d=UL(r);if(s&&(i.body={...s,nextQuery:_u(n,o,{body:!0},s)}),a){let f=$s(n,o,d,"filePage",a);i.changedFiles={...a,...f?{nextQuery:f}:{}}}if(c&&r.comments){let f=$s(n,o,{comments:r.comments},"commentPage",c);i.comments={...c,...f?{nextQuery:f}:{}}}if(p?.hasMore&&p.nextCharOffset!==void 0&&r.comments&&(i.commentBody={...p,nextQuery:Bo(n,o,{content:{comments:r.comments},...n.commentPage!==void 0?{commentPage:n.commentPage}:{},commentBodyOffset:p.nextCharOffset,charLength:n.charLength})}),l&&r.commits){let f=$s(n,o,{commits:r.commits},"commitPage",l);i.commits={...l,...f?{nextQuery:f}:{}}}u&&r.patches.mode!=="none"&&(i.patches={...u,nextQuery:_u(n,o,{patches:r.patches},u,{filePage:n.filePage??n.page})});let m=t.filePaths;return Nr(m)&&(i.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Bo(n,o,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(i).length>0?i:void 0}function xy(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?QL(s):s,c=n.body?Vn(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,d=t.prNumber!==void 0||t.verbose===!0,{contentPagination:m={},...f}=Ry(e,t,n),{contentPagination:h={},...y}=yy(e,t,n),{contentPagination:g={},...S}=Sy(e,t,n),R=Array.isArray(f.changedFiles)?f.changedFiles.find(E=>E.path)?.path:void 0,P={...{number:e.number,title:e.title,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,...d?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...d?{updatedAt:e.updatedAt}:{},...d||!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}:{},...d&&!c?{bodyPreview:js(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:Cy(t,i,n,R)}:{}},...n.body?c?{body:c.content}:{bodyEmpty:!0}:{},...f,...y,...by(e,t,n),...S,...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},T=WL(P,{...c?{body:c.pagination}:{},...m,...h,...g},t,n,i);return T&&(P.contentPagination=T),P}async function ku(e,t,n,r=de){let o=n(),i={...t},s=my(i),a=i.prNumber!==void 0;a||(i.content=void 0);let c=await qt(i,()=>o.provider.searchPullRequests(Cg(i)));if(c.ok===!1)return c.result;let l=a?s.changedFiles||s.patches.mode!=="none":!1,{pullRequests:u,resultData:p}=xg(c.response.data,{includeFileChanges:l});i.prNumber!==void 0&&delete p.pagination;let d=!a&&!!e.content,m={...s,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},f=i.minify==="standard",h=a,y=u.map(S=>xy(S,i,d?m:s,f,h));p.pullRequests=y,!a&&i.concise===!0&&(p.pullRequests=y.map(S=>{let R=S;return`#${R.number} ${R.title}`}));let g=y.length>0;if(!a&&g){let S=y[0].number,R=i.owner,C=i.repo;S!=null&&R&&C&&(p.next={readPr:{tool:"ghGetHistoryItem",query:{operation:"pullRequest",owner:R,repo:C,number:S,content:{body:!0,changedFiles:!0,comments:{discussion:!0}}},why:"Read any PR from this list \u2014 swap number for the # you want.",confidence:"low"}})}return me(i,p,g,r,{rawResponse:c.response.rawResponseChars})}var wy={body:"continueBody",changedFiles:"nextChangedFilesPage",comments:"nextCommentsPage",commentBody:"continueCommentBody",commits:"nextCommitsPage",patches:"continuePatch",filePaths:"nextFilePathsPage"},VL={body:"charOffset",changedFiles:"filePage",comments:"commentPage",commentBody:"commentBodyOffset",commits:"commitPage",patches:"charOffset",filePaths:"filePage"};function en(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zo(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,t])]}function KL(e){return{body:"Continue the pull-request or issue body.",changedFiles:"Continue the pull-request changed-file list.",comments:"Continue the discussion comment list.",commentBody:"Continue the current comment body.",commits:"Continue the pull-request commit list.",patches:"Continue the current patch window.",filePaths:"Continue the pull-request file-path list."}[e]}function XL(e,t){return["filePage","commentPage","commitPage","charOffset","commentBodyOffset"].every(n=>e[n]===void 0||e[n]===t[n])}function Iu(e,t){let n=t==="pullRequest"?"pullRequests":"issues",r=e[n];if(!Array.isArray(r)||r.length===0||!en(r[0]))return e;let o=r[0].contentPagination;if(!en(o))return e;let s={...en(e.next)?e.next:{}},a={},c=!1,l=!1;for(let[p,d]of Object.entries(o)){if(!en(d)){a[p]=d;continue}let{nextQuery:m,...f}=d,h=p;if(f.hasMore===!0&&h in wy){c=!0;let y=en(m)?Wt.safeParse(m):void 0,g=VL[h],S=en(m)&&typeof m[g]=="number";y?.success&&S&&XL(m,y.data)?s[wy[h]]={tool:fe,query:y.data,why:KL(h),confidence:"exact"}:(l=!0,f.continuationUnavailable={reason:S?"schemaLimit":"missingCursor"})}a[p]=f}if(!c)return e;let u=[...r];return u[0]={...r[0],contentPagination:a},{...e,[n]:u,isPartial:!0,partialReasons:zo(e.partialReasons,"contentPagination"),...l?{terminalLimit:!0}:{},...Object.keys(s).length>0?{next:s}:{}}}function Py(e,t){let r=(Array.isArray(e.commits)?e.commits:[]).find(a=>en(a)&&a.messageTruncated===!0);if(!en(r)||typeof r.sha!="string")return e;let o={operation:"commit",owner:t.owner,repo:t.repo,ref:r.sha},i=Wt.safeParse(o);if(!i.success)return e;let s=en(e.next)?e.next:{};return{...e,isPartial:!0,partialReasons:zo(e.partialReasons,"commitMessageTruncated"),next:{...s,readCommit:{tool:fe,query:i.data,why:`Read the complete message for commit ${r.sha}.`,confidence:"exact"}}}}var vu=1e3;function Xs(e,t,n){let r=n==="commits"?Py(e,t):e,o=r.incompleteResults===!0,i=Fu(r.next),s=typeof t.page=="number"&&Number.isInteger(t.page)?t.page:1,a=o?{...r,isPartial:!0,partialReasons:zo(r.partialReasons,"providerIncompleteResults"),next:{...i,retry:{tool:de,query:Lu(t,n,s),why:`Retry the same ${n} provider page because the provider reported incomplete results.`,confidence:"exact"}}}:r,c=a.pagination;if(!c||typeof c!="object")return a;let l=c,u=l.totalMatchesCapped===!0,p=u?YL(a):a;if(l.hasMore!==!0)return p;let d=l.nextPage;if(typeof d!="number"||!Number.isInteger(d))return Ou(p,l,{reason:"missingProviderCursor"});if(d>1e3)return Ou(p,l,{reason:"schemaPageLimit",maxPage:1e3});let m=typeof l.perPage=="number"&&l.perPage>0?l.perPage:typeof t.pageSize=="number"&&t.pageSize>0?t.pageSize:void 0;return u&&m!==void 0&&(d-1)*m>=vu?Ou(p,l,{reason:"providerResultCap",maxResults:vu}):{...p,next:{...Fu(p.next),nextPage:{tool:de,query:Lu(t,n,d),why:`Continue ${n} search/list results on page ${d}.`,confidence:"exact"}}}}function YL(e){return{...e,isPartial:!0,terminalLimit:!0,partialReasons:zo(e.partialReasons,"providerResultCap"),providerLimit:{reason:"providerResultCap",maxResults:vu}}}function Ou(e,t,n){let{nextPage:r,...o}=t,{nextPage:i,...s}=Fu(e.next);return{...e,terminalLimit:!0,pagination:{...o,continuationUnavailable:n},...Object.keys(s).length>0?{next:s}:{}}}function Fu(e){return e&&typeof e=="object"?e:{}}function Ty(e){return ut(rc,e)}function Ey(e){let{operation:t,...n}=e;return n}function ZL(e,t){let n=e.filesPagination,o=(Array.isArray(e.files)?e.files:[]).find(s=>s&&typeof s=="object"&&typeof s.patchPagination?.nextCharOffset=="number"),i={};return typeof n?.nextFilePage=="number"&&(i.nextFilePage={tool:fe,query:Au(t,{filePage:n.nextFilePage}),why:"Continue the changed-file list.",confidence:"exact"}),typeof o?.patchPagination?.nextCharOffset=="number"&&(i.continuePatch={tool:fe,query:Au(t,{charOffset:o.patchPagination.nextCharOffset}),why:"Continue the current patch window.",confidence:"exact"}),Object.keys(i).length>0?{...e,next:i}:e}async function JL(e,t,n){let r=ut(fr,e);if(r.ok===!1)return r.error;let o=r.data,i=o.operation,s={...Ey(o),type:i==="pullRequests"?"prs":i==="issues"?"issues":"commits"},a=Ty(s);return a.ok===!1?a.error:i==="pullRequests"?Xs(await ku(s,a.data,n,de),e,i):i==="issues"?Xs(await Tu(s,a.data,t.authInfo,de),e,i):Xs(await Cu(s,a.data,t.authInfo,de),e,i)}async function qL(e,t,n){let r=ut(Wt,e);if(r.ok===!1)return r.error;let o=r.data;if(o.operation==="commit"){let c=await iy({owner:String(o.owner),repo:String(o.repo),ref:String(o.ref),...typeof o.includeDiff!="boolean"?{}:{includeDiff:o.includeDiff},...typeof o.path!="string"?{}:{path:o.path},...typeof o.filePage!="number"?{}:{filePage:o.filePage},...typeof o.pageSize!="number"?{}:{itemsPerPage:o.pageSize},...typeof o.charOffset!="number"?{}:{charOffset:o.charOffset},...typeof o.charLength!="number"?{}:{charLength:o.charLength}},t.authInfo);return Lt(c)?N(c,e,{toolName:fe}):me(e,ZL(c.data,e),!0,fe)}let s={...Ey(o),...o.operation==="pullRequest"?{type:"prs",prNumber:o.number,number:void 0}:o.operation==="issue"?{type:"issues",issueNumber:o.number,number:void 0}:{type:"commits"}};delete s.number;let a=Ty(s);return a.ok===!1?a.error:o.operation==="pullRequest"?Iu(await ku(s,a.data,n,fe),o.operation):o.operation==="issue"?Iu(await Tu(s,a.data,t.authInfo,fe),o.operation):Cu(s,a.data,t.authInfo,fe)}function Ay(e,t,n){let r=et(e.authInfo);return ge(e.queries,async o=>{try{return await n(o,e,r)}catch(i){return He(i,o,void 0,t)}},{toolName:t},e)}function Ly(e){return Ay(e,de,JL)}function _y(e){return Ay(e,fe,qL)}import{existsSync as ky}from"fs";import{delimiter as e_,dirname as t_,join as Iy}from"path";function Oy(){return process.platform==="win32"?"npm.cmd":"npm"}function n_(){let e=t_(process.execPath);return Iy(e,Oy())}function r_(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function o_(){let e=(process.env.PATH??"").split(e_).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...r_()])]}function i_(){let e=n_();if(ky(e))return{command:process.execPath,argsPrefix:[e]};let t=Oy();for(let n of o_()){let r=Iy(n,t);if(ky(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var s_=["view","search","ping","config","whoami"],a_=[...vo,...Vh];async function Kn(e,t,n={}){if(!s_.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Xh(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=i_(),c=await Fo(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:a_});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var Dr="https://registry.npmjs.org",Ys=null;async function Zs(){if(Ys)return Ys;try{let e=await Kn("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 Ys=t,t}}catch{}return Ys=Dr,Dr}var Qo=new Map,c_=5,Mu=3e4;function Uo(e){try{return new URL(e).host||e}catch{return e}}var Nu=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 vy(e,t=Date.now()){let n=Qo.get(Uo(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Mu)throw new Nu(Uo(e),Mu-r);n.state="half-open"}}function Du(e){let t=Qo.get(Uo(e));t&&(t.failures=0,t.state="closed")}function Fy(e,t=Date.now()){let n=Uo(e),r=Qo.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=c_&&(r.state="open",r.openedAt=t)),Qo.set(n,r)}function My(e,t=Date.now()){let n=Qo.get(Uo(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Mu:!1}import{z as _}from"zod";var Js=_.looseObject({name:_.string(),version:_.string(),repository:_.union([_.string(),_.object({url:_.string().optional(),type:_.string().optional(),directory:_.string().optional()})]).optional(),main:_.string().optional(),module:_.string().optional(),type:_.string().optional(),exports:_.unknown().optional(),types:_.string().optional(),typings:_.string().optional(),description:_.string().optional(),keywords:_.array(_.string()).optional(),license:_.union([_.string(),_.object({type:_.string().optional()})]).optional(),homepage:_.string().optional(),author:_.union([_.string(),_.object({name:_.string().optional(),email:_.string().optional(),url:_.string().optional()})]).optional(),maintainers:_.array(_.object({name:_.string().optional(),email:_.string().optional()})).optional(),engines:_.record(_.string(),_.string()).optional(),dependencies:_.record(_.string(),_.string()).optional(),devDependencies:_.record(_.string(),_.string()).optional(),peerDependencies:_.record(_.string(),_.string()).optional(),time:_.record(_.string(),_.string().optional()).optional()}),l_=_.looseObject({package:_.looseObject({name:_.string().nullish(),version:_.string().nullish(),description:_.string().nullish(),links:_.looseObject({npm:_.string().nullish(),homepage:_.string().nullish(),repository:_.string().nullish()}).nullish()}),score:_.looseObject({final:_.number().nullish(),detail:_.looseObject({quality:_.number().nullish(),popularity:_.number().nullish(),maintenance:_.number().nullish()}).nullish()}).nullish()}),Ny=_.looseObject({objects:_.array(l_),total:_.union([_.number(),_.string()]).optional()}),u_=_.union([_.string(),_.boolean(),_.number(),_.null(),_.record(_.string(),_.unknown())]);var p_=6e4;function Dy(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function d_(e,t,n,r){e&&Rn({limit_type:"primary",retry_after_seconds:Dy(r),api_method:t,api_url:n,provider:e})}function m_(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(uo.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Lf(r),e.status===429&&d_(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function f_(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=Dy(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function zt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=p_,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,p=e;if(a){let y=e.includes("?")?"&":"?";p=`${e}${y}version=${encodeURIComponent(Hn)}`}let d={"User-Agent":`Octocode-MCP/${Hn}`,...i},m=globalThis.fetch;if(!m)throw new Error(uo.FETCH_NOT_AVAILABLE.message);vy(p);let f,h=n+1;for(let y=1;y<=h;y++){if(c?.aborted)throw new Error("Request aborted");try{let g=await m(p,{method:s,headers:d,signal:c});if(!g.ok)throw m_(g,s,p,u,l);if(g.status===204)return Du(p),null;let S=await g.json();return Du(p),S}catch(g){let S=g;if(c?.aborted||g instanceof Error&&g.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw g;if(f=g instanceof Error?g:new Error(String(g)),y===h)break;let R=f_(y,r,o,S);await new Promise(C=>setTimeout(C,R))}}throw Fy(p),new Error(uo.FETCH_FAILED_AFTER_RETRIES.message(h,f?.message||""))}function Pn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var h_="https://api.npmjs.org/downloads/point/last-week";function Ke(e){return e===void 0?0:G(e)}async function ea(e){try{let t=`${h_}/${encodeURIComponent(e)}`,n=await zt(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Ke(n)}}catch{return{rawResponseChars:0}}}function qs(e,t){return{values:e.slice(0,t),total:e.length,truncated:e.length>t}}function g_(e){if(typeof e=="string")return qs([e],12);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}`):[]);return n.length>0?qs(n,12):void 0}function y_(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return qs([n?`${n} \u2192 ${e}`:e],8)}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`);return n.length>0?qs(n,8):void 0}}function b_(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function ta(e,t=!1,n="cli"){let r=g_(e.exports),o=y_(e.bin,e.name),i=null,s;e.repository&&(typeof e.repository=="string"?i=Pn(e.repository):(e.repository.url&&(i=Pn(e.repository.url)),e.repository.directory&&(s=e.repository.directory.replace(/^\.\//,""))));let a;if(e.time){let u=(e.version?e.time[e.version]:void 0)||e.time.modified;u&&(a=u)}let c={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:i,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:b_(e),...s?{repositoryDirectory:s}:{},...r?{exports:r.values,exportsTotal:r.total,...r.truncated?{exportsTruncated:!0}:{}}:{},...o?{bin:o.values,binTotal:o.total,...o.truncated?{binTruncated:!0}:{}}:{},lastPublished:a,source:n};return e.description&&(c.description=e.description),e.license&&(c.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?c.author=e.author:e.author.name&&(c.author=e.author.name)),e.keywords&&e.keywords.length>0&&(c.keywords=e.keywords),e.homepage&&(c.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(c.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(c.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(c.peerDependencies=e.peerDependencies)),c}function S_(e){return typeof e.links?.repository=="string"?Pn(e.links.repository):typeof e.repository=="string"?Pn(e.repository):typeof e.repository?.url=="string"?Pn(e.repository.url):null}function Hy(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:S_(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 Hu(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function Gy(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}var R_=3e3;function Gu(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}async function Bu(e){try{let t=await Zs(),n=Hu(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await zt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ke(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await zt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ke(i)}}catch{return{rawResponseChars:0}}}async function ra(e,t,n){let[r,o]=await Promise.all([ea(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Bu(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 na(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function C_(e,t){try{let n=await Kn("view",[e,"--json"],{timeout:R_});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,...na(c)?{}:{errorDetail:c},rawResponseChars:Ke(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Ke(o),s=Js.safeParse(o);return s.success?{pkg:ta(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,...na(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function x_(e,t){try{let n=await Zs(),r=Hu(e),o=`${n}/${r}/latest`,i;try{i=await zt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Ke(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=Js.safeParse(i);return a.success?{pkg:ta(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,...na(r)?{}:{errorDetail:r},rawResponseChars:0}}}function w_(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function zu(e,t){let n=0,r;for(let o of w_(e)){let i;try{i=await zt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);na(l)||(r=l);continue}if(n+=Ke(i),!i||typeof i!="object")continue;let s=Js.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:ta(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function oa(e,t=!1){let[n,r]=await Promise.allSettled([C_(e,t),x_(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?ra(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function By(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await oa(e,t);if(!r){if(o){let s=Gu(o);if(s&&n){let a=await zu(e,t);if(a.pkg){let c=await ra(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 ghSearch operation:"repositories" with the 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 P_(e,t,n,r=0){let o=Math.max(t+r,t),i=await Kn("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Ke(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Ke(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((f,h)=>{let y=f?.score?.final??0;return(h?.score?.final??0)-y}).slice(r,r+t),p=await Promise.all(u.map(async f=>{if(!f||typeof f!="object")return null;let h=f;if(!h.name)return null;if(n){let y=await oa(h.name,!0);if(y.pkg)return y}return{pkg:Hy(h),rawResponseChars:0}})),d=p.map(f=>f?.pkg).filter(f=>!!f),m=p.reduce((f,h)=>f+(h?.rawResponseChars??0),0);return{packages:d,totalFound:a.length,rawResponseChars:c+m}}async function T_(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Dr}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await zt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`Could not reach the npm search API (${f instanceof Error?f.message:String(f)}). The package may not exist, or the registry search endpoint is unavailable.`,hints:['Verify the exact package name / scope (e.g. "@scope/name")',"For an exact known name, query it directly instead of a keyword search","Ensure the npm registry is accessible from this environment"]}}let a=Ke(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Ny.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(h=>h.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((f,h)=>{let y=f.score?.final??0;return(h.score?.final??0)-y}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),p=await Promise.all(u.map(async f=>{if(n){let h=await oa(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"?Pn(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),d=p.map(f=>f.pkg).filter(f=>!!f),m=p.reduce((f,h)=>f+h.rawResponseChars,0);return{packages:d,totalFound:Gy(c.data.total,d.length),rawResponseChars:a+m}}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 Qu(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 zt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Ke(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ke(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?Pn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Ke(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Uu(e,t,n,r=0){try{let o=await P_(e,t,n,r);if(!("error"in o))return o}catch{}return T_(e,t,n,r)}async function ju(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}):ea(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Bu(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)]}}function Xn(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function zy(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function $u(e,t,n,r=0){let o=Ee("npm-search",{name:e,limit:t,metadata:n,from:r});return Fe(o,async()=>{if(My(Dr)){if(r===0&&t===1&&Xn(e)){let u=await zu(e,n);if(u.pkg){let p=await ra(e,u.pkg,u.rawResponseChars);return{packages:p.pkg?[p.pkg]:[],totalFound:p.pkg?1:0,rawResponseChars:p.rawResponseChars}}}let l=await Qu(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:['Use ghSearch operation:"repositories" to find the source repository.']}}if(r===0&&Xn(e)){let l=await By(e,n,t===1);if("error"in l){if(!Gu(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Uu(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return ju(s);let a=zy(e);if(a!==e){let l=await Uu(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return ju(l)}let c=await Qu(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 ghSearch operation:"repositories" with the package name or domain terms.']}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function Qy(e){let t=Xn(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return $u(e.name,n,!0,r)}function Wu(e){if(e===void 0)return;let t=e.join(" ").trim();return t.length>0?t:void 0}var A_=/\b(?:404|e404)\b|not\s+found|no\s+such\s+package|does\s+not\s+exist/i;function Vu(e){return A_.test(e)}function Ku(e,t,n,r){let o=Math.max(1,e.page??1),i=r?e.pageSize??10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c&&o<1e3?{nextPage:o+1}:{},...c&&o>=1e3?{continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}:{}}}function Uy(e,t){if(!(!Array.isArray(e.keywords)||typeof t.nextPage!="number"))return{nextPage:{tool:"npmSearch",query:{keywords:e.keywords,page:t.nextPage,...typeof e.pageSize=="number"?{pageSize:e.pageSize}:{}},why:`Continue npm keyword discovery on page ${t.nextPage}.`,confidence:"exact"}}}function L_(e){return"error"in e}function ia(e){return"npmUrl"in e}function __(e){return ia(e)&&e.path?e.path:e.name}function k_(e){return ia(e)?e.repoUrl:e.repository}function I_(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}var O_={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function v_(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=s=>s.replace(/\.git$/,""),r=t.match(/^(github|gitlab|bitbucket):(.+)$/i);if(r&&r[1]&&r[2]){let s=O_[r[1].toLowerCase()];return n(`https://${s}/${r[2]}`)}let o=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(o&&o[1]&&o[2])return n(`https://${o[1]}/${o[2]}`);let i=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(i&&i[1]){let s=i[1].replace(/^[^@/]+@/,"");return n(`https://${s}`)}return n(t)}function Xu(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function jy(e,t){let n=Xu(e);if(!n)return;let{owner:r,repo:o}=n;return{viewTree:{tool:"ghSearch",query:{operation:"tree",owner:r,repo:o,...t?{path:t}:{}}},searchRepositoryCode:{tool:"ghSearch",query:{operation:"code",owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function F_(e){let t=__(e),n=v_(k_(e)),r={name:t};ia(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=I_(ia(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=jy(n,o);return i&&(r.next=i),r.version&&Xu(n)&&(r.warnings=[`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`]),r}function M_(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=Xu(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:jy(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:p,...d}=i;return{...d,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}async function $y(e){return ge(e.queries,async t=>{try{let n=t.packageName??Wu(t.keywords),r=Array.isArray(t.keywords);if(!n)return N("Provide a packageName or keywords for package search",t);let o=await Qy({name:n,page:t.page,...r&&typeof t.pageSize=="number"?{itemsPerPage:t.pageSize}:{},goal:t.goal,reasoning:t.reasoning});if(L_(o)){if(Vu(o.error)){let d=Xn(n);return me(t,{packages:[],hints:[d?`No package named "${n}". Check spelling and scope.`:`No packages matched "${n}". Try fewer keywords or an exact name.`]},!1,I.PACKAGE_SEARCH,{rawResponse:o})}return N(o.error,t,{rawResponse:o})}let s=o.packages.map(F_),a=s.length>0,c=Ku(t,o.totalFound,s.length,r),l=M_(s),u=Uy(t,c),p={...l,pagination:c,...c.continuationUnavailable?{terminalLimit:!0}:{},...u?{next:u}:{}};return me(t,p,a,I.PACKAGE_SEARCH,{rawResponse:o.rawResponseChars??o})}catch(n){return N(n,t,{toolName:I.PACKAGE_SEARCH})}},{toolName:I.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{ContentSanitizer as W_}from"@octocodeai/octocode-engine/contentSanitizer";import sa from"path";import{pathValidator as aa}from"@octocodeai/octocode-engine/pathValidator";import{redactPath as jo}from"@octocodeai/octocode-engine/pathUtils";var nt={pathValidationFailed:(e,t,n)=>new Ne(Q.PATH_VALIDATION_FAILED,t||`Path validation failed: ${jo(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=jo(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path with localSearch operation:"files".`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localSearch operation:"tree".`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Ne(Q.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Ne(Q.FILE_READ_FAILED,`Failed to read file: ${jo(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Ne(Q.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)}). Use startLine/endLine, matchString, or charOffset/charLength to read a bounded slice.`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Ne(Q.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${jo(e)}. Use localSearch operation:"text" for embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Ne(Q.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Ne(Q.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 Ne(Q.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Ne(Q.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{getConfigSync as Wy,getOctocodeHome as N_}from"@octocodeai/config";function D_(e=Wy().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&aa.addAllowedRoot(t)}function H_(){let e=N_(process.env);aa.addAllowedRoot(sa.join(e,"tmp","clone")),aa.addAllowedRoot(sa.join(e,"tmp","tree"))}function rt(e,t){if(!e.path?.trim()){let s=nt.pathValidationFailed("","path is required");return{isValid:!1,errorResult:N(s,e,{toolName:t})}}D_(),H_();let n=process.env.WORKSPACE_ROOT?.trim()||Wy().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=sa.isAbsolute(r)?r:sa.resolve(n,r),i=aa.validate(o);if(!i.isValid){let s=nt.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:N(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}import{open as G_,readFile as B_,stat as z_}from"fs/promises";var Qt={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 Vy(e,t){return n=>t}function Yu(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Zu(e,t,n){return{...e,...Yu(t,n)}}function Ky(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function Xy(e,t){try{return{fileStats:await z_(t)}}catch(n){let r=nt.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:N(r,e,{toolName:I.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Yy(e){let t=e.startLine!==void 0&&e.endLine!==void 0;return e.minify??(e.fullContent===!0||t?"none":"standard")}function Zy(e,t,n){return n!=="none"?!1:t>Qt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.charLength}function Jy(e,t,n){let r=nt.fileTooLarge(e.path,n,Qt.LARGE_FILE_THRESHOLD_KB);return N(r,e,{toolName:I.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function qy(e,t){let n=nt.binaryFileUnsupported(e.path);return N(n,e,{toolName:I.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function eb(e){let n=Buffer.alloc(8192),r;try{r=await G_(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,{stream:!0})}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(Vy("binary sample handle close",void 0))}}async function tb(e,t){try{return{content:await B_(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?nt.fileAccessFailed(e.path,r):nt.fileReadFailed(e.path,r);return{errorResult:N(i,e,{toolName:I.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function nb(e,t){return{status:"empty",errorCode:Q.NO_MATCHES,totalLines:t}}function Q_(e,t,n){let r=is(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:nb(e,n)};let o=r.lines.join(`
|
|
45
|
-
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,p;if(r.matchRanges.length>0){let d=r.matchRanges[0],m=r.matchRanges[r.matchRanges.length-1];d&&m&&(l=d.start,u=m.end,p=r.matchRanges)}return{resultContent:o,isPartial:!1,actualStartLine:l,actualEndLine:u,matchRanges:p,matchedLines:r.matchingLines,warnings:[c]}}function U_(e){return e.startLine!==void 0&&e.endLine!==void 0}function j_(e,t,n){let r=String(n).length;return e.slice(t-1,n).map((o,i)=>`${String(t+i).padStart(r," ")}\u2192 ${o}`).join(`
|
|
46
|
-
`)}function $_(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:Q.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:Q.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:j_(t,i,s),isPartial:s<n,actualStartLine:i,actualEndLine:s,warnings:a}}function rb(e,t,n){let r=t.split(`
|
|
47
|
-
`),o=Gt(t);return e.matchString?Q_(e,r,o):U_(e)?$_(e,r,o):{resultContent:t,isPartial:!1}}async function ob(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",p=s;if(s!==void 0){let R=await us(e,l,s,r);u=R.chunkMode,p=R.length}let d=as(e,l,p,s!==void 0?{pageSize:s}:void 0),m;if(d.hasMore&&u==="char-limit"&&cs(d.paginatedContent)){let R=d.charOffset+d.charLength;m=await ls(e,R,r)}let{goal:f,reasoning:h,charOffset:y,...g}=t,S=Ms("localGetFileContent",{...g,path:r,charLength:s??d.charLength},d);return{windowedContent:d.paginatedContent,pagination:d,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:m,next:S,showPagination:s!==void 0||i>0||a}}async function ib(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=await ob(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let p=t.isPartial||u.pagination.hasMore,d=t.actualStartLine!==void 0&&t.actualEndLine!==void 0?t.actualEndLine-t.actualStartLine+1:void 0,m=t.isPartial&&!u.pagination.hasMore&&t.actualEndLine!==void 0&&d!==void 0?Ge("localGetFileContent",{path:c,startLine:t.actualEndLine+1,endLine:Math.min(r,t.actualEndLine+d),...e.minify!==void 0?{minify:e.minify}:{}},"Continue with the next source-line window."):void 0,f={...u.next??{},...m?{continueLines:m}:{}};return{path:c,content:u.windowedContent,contentView:s,returnedChars:u.windowedContent.length,...p&&{isPartial:p},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges},...t.matchedLines!==void 0&&{matchedLines:t.matchedLines}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...wl(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...Object.keys(f).length>0?{next:f}:{},...a.length>0&&{warnings:a}}}async function Ju(e,t,n,r,o,i,s){let a=await ob(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",returnedChars:a.windowedContent.length,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...Yu(r,o),...a.showPagination&&{pagination:{...wl(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function sb(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}function qu(e,t){let n=W_.sanitizeContent(e,t);return{text:n.content,warning:n.hasSecrets?`Secrets detected and redacted: ${n.secretsDetected.join(", ")}`:void 0}}async function ab(e){let t=Qn();try{let n=rt(e,I.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=Ky(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await Xy(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await eb(o))return $(qy(e,o),c);let u=Yy(e);if(Zy(e,l,u))return $(Jy(e,o,l),c);let{content:p,errorResult:d}=await tb(e,o);if(d||p===void 0)return d;let m=p.length,f=Buffer.byteLength(p,"utf-8"),h=p,y=e.matchString!==void 0&&u!=="none",g=y?"none":u,S=y&&e.minify!==void 0?`minify:"${e.minify}" is not applied to matchString extractions \u2014 matched slices are returned verbatim so the content always contains the matched text.`:void 0,R=g==="standard"||g==="symbols",C=R?"standard":"none",P;if(g==="symbols"){let b=D.extractSignatures(h,i);if(b===null){let w=ss(h,i);if(w!==null){let L=qu(w,i);return $(await Ju(e,L.text,Gt(h),m,f,L.warning,t),m)}P=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(b!==null){let w=Gt(h),L=D.applyContentViewMinification(b,i),O=qu(L,i);return $(await Ju(e,O.text,w,m,f,O.warning,t),m)}}let T=Gt(h),E=rb(e,h,t),k=b=>{let w=b.content;if(typeof w!="string")return b;let L=qu(w,i),O=[...P?[P]:[],...S?[S]:[],...L.warning?[L.warning]:[]],v=b.warnings??[];return{...b,content:L.text,...O.length>0&&{warnings:[...v,...O]}}};if(E.earlyResult){let b=E.earlyResult.content,w=R&&typeof b=="string"?{...E.earlyResult,content:D.applyContentViewMinification(b,i)}:E.earlyResult;return $(Zu(k(sb(w,C)),m,f),m)}let x=await ib(e,E,s,T,t,R,C);return $(Zu(k(x),m,f),m)}catch(n){return N(n,e,{toolName:I.LOCAL_FETCH_CONTENT})}}async function cb(e){let{queries:t}=e;return ge(t||[],async n=>yt({toolName:I.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=ut(Zr,n);return r.ok===!1?r.error:await ab(r.data)}}),{toolName:I.LOCAL_FETCH_CONTENT,finalize:V_()},e)}function V_(){return({results:e})=>{let t={results:K_(e)},n=Cs(t.results);n&&(t.base=n);let r=xs(t.results);return r&&(t.shared=r),{structuredContent:Jt(t),renderText:o=>X_(o),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function K_(e){return e.map(t=>{let n=structuredClone(t.data),r=typeof n.path=="string"?n.path:void 0;if(t.status!=="error"&&r){let o=Ns(r);o&&(n.fileType=o)}return{...t,data:n}})}function X_(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.index}${n.status?` (${n.status})`:""}`);let s=Oo({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","returnedChars","fileType","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Oo({shared:e.shared},["shared"]).trimEnd()),t.join(`
|
|
48
|
-
`).trimEnd()+`
|
|
49
|
-
`}import{posix as pb}from"node:path";var Y_=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","async","await"]);function ca(e){return e?!Y_.has(e):!1}import{posix as la}from"node:path";var ep=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],Z_={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function lb(e){return e.split("\\").join("/")}function $o(e,t,n,r=new Map){let o=lb(e);if(!o.startsWith(".")&&!o.startsWith("/"))return r.get(o)??null;let i=la.dirname(lb(t)),s=o.startsWith("/")?o.slice(1):la.normalize(la.join(i,o)),a=[];if(ep.some(l=>s.endsWith(l))){a.push(s);for(let[l,u]of Object.entries(Z_))if(s.endsWith(l)){a.push(s.slice(0,-l.length)+u);break}}else{a.push(s);for(let l of ep)a.push(`${s}${l}`);for(let l of ep)a.push(la.join(s,`index${l}`))}for(let l of a)if(n.has(l))return l;return null}import{readFileSync as J_}from"node:fs";import{join as q_,posix as ua}from"node:path";var ek=new Set(["dist","out","lib","build"]),tk={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts",".ts"],".cjs":[".cts",".ts"],".d.ts":[".ts"]};function tp(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let n of e){let r=tp(n);if(r)return r}return null}if(!e||typeof e!="object")return null;let t=e;for(let n of["import","default","node","require","types"]){let r=tp(t[n]);if(r)return r}return null}function nk(e,t){if(!t.startsWith("./"))return[];let n=t.slice(2).split("/"),r=[n];ek.has(n[0]??"")&&r.push(["src",...n.slice(1)]);let o=new Set;for(let i of r){let s=ua.normalize(ua.join(e,...i));o.add(s);for(let[a,c]of Object.entries(tk))if(s.endsWith(a))for(let l of c)o.add(s.slice(0,-a.length)+l)}return[...o]}function ub(e,t){let n=new Set(["."]);for(let o of t){let i=ua.dirname(o);for(;i!==".";)n.add(i),i=ua.dirname(i)}let r=new Map;for(let o of n){let i;try{i=JSON.parse(J_(q_(e,o,"package.json"),"utf8"))}catch{continue}if(typeof i.name!="string")continue;let s=[];i.exports&&typeof i.exports=="object"&&!Array.isArray(i.exports)&&Object.keys(i.exports).some(a=>a.startsWith("."))?s.push(...Object.entries(i.exports)):i.exports!==void 0&&s.push([".",i.exports]);for(let[a,c]of s){if(a!=="."&&!a.startsWith("./"))continue;let l=tp(c);if(!l)continue;let u=nk(o,l).find(d=>t.has(d));if(!u)continue;let p=a==="."?i.name:`${i.name}/${a.slice(2)}`;r.set(p,u)}}return r}var rk=["node_modules","dist","build","out","coverage",".git","target",".next",".cache"];function pa(e){return[...new Set([...rk,...e??[]])]}async function Hr(e,t,n){let r=await D.scanGraphFacts({path:e,excludeDir:t,maxFiles:n,maxFileBytes:1e6}),o=r.entries,i=r.truncated,s=new Set(r.candidatePaths.map(f=>pb.normalize(f.split("\\").join("/")))),a=ub(e,s),c=new Map,l=new Map,u=new Set,p=new Set,d=new Map,m=r.filesSkipped;for(let f of o){let h=pb.normalize(f.relativePath.split("\\").join("/")),y;try{y=JSON.parse(f.factsJson)}catch{m++;continue}let g=(y.declarations??[]).filter(b=>ca(b.name)).map(b=>({id:b.id,name:b.name,kind:b.kind,line:b.line,exported:b.exported??!1})),S=new Map(f.referenceCounts.map(({name:b,count:w})=>[b,w])),R=(y.exports??[]).filter(b=>b.source&&b.name!=="*").map(b=>({specifier:b.source,localName:b.localName??b.name,importedName:b.name,line:b.line,importKind:"value",resolvedTarget:$o(b.source,h,s,a)})),C=(y.calls??[]).filter(b=>b.kind==="dynamic-import").map(b=>b.callee),P={relativePath:h,declarations:g,imports:(y.imports??[]).map(b=>({specifier:b.specifier,localName:b.localName,importedName:b.importedName,line:b.line,importKind:b.importKind==="type"?"type":"value",resolvedTarget:$o(b.specifier,h,s,a)})),namedReexports:R,calls:(y.calls??[]).filter(b=>b.kind!=="dynamic-import").map(b=>({caller:b.caller,callee:b.callee})),referenceCounts:S};c.set(h,P);let T=new Set,E=new Set,k=new Map,x=(b,w)=>{T.add(b);let L=k.get(b)??new Set;L.add(w),k.set(b,L)};for(let b of P.imports){let w=b.resolvedTarget;w&&x(w,b.importKind==="type"?"type-import":"static-import")}for(let b of P.namedReexports){let w=b.resolvedTarget;w&&x(w,"named-reexport")}for(let b of C){let w=$o(b,h,s,a);w&&(x(w,"dynamic-import"),p.add(w))}for(let b of y.exports??[]){if(!b.source||b.name!=="*")continue;let w=$o(b.source,h,s,a);if(w){x(w,"star-reexport"),u.add(w);let L=d.get(w)??[];L.push(h),d.set(w,L)}}for(let[b,w]of k)w.size===1&&w.has("dynamic-import")&&E.add(b);l.set(h,{relativePath:h,importsFiles:T,dynamicImportsFiles:E,edgeKinds:k})}return{facts:c,fileGraph:l,filesScanned:c.size,filesSkipped:m,truncated:i,starReexportTargets:u,dynamicImportTargets:p,starReexporters:d}}import{readFileSync as ok}from"node:fs";import{posix as np}from"node:path";var ik=/(\.(test|spec)\.[^/]+$)|(^|\/)(__tests__|tests?)\//i;function op(e){return ik.test(e)}var sk=/\.(mjs|cjs|jsx?|tsx?)$/i;function ak(e){let t=[];for(let n of e.split(/\s+/)){let r=n.includes("=")?[n,n.slice(n.indexOf("=")+1)]:[n];for(let o of r){let i=o.replace(/^["']|["']$/g,"");sk.test(i)&&!i.startsWith("-")&&t.push(i)}}return t}function rp(e){return e.split("\\").join("/")}function db(e){return e.replace(/^\.\//,"")}var mb=["dist","build","out"],ck={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function fb(e){for(let[t,n]of Object.entries(ck))if(e.endsWith(t))return e.slice(0,-t.length)+n}function lk(e,t){let n=[],r=fb(e);r&&n.push(r);for(let o of mb){let i=`${o}/`;if(!e.startsWith(i))continue;let a=`src/${e.slice(i.length)}`;n.push(a);let c=fb(a);c&&n.push(c)}return mb.some(o=>e.startsWith(`${o}/`))&&t.has("src/index.ts")&&n.push("src/index.ts"),n.find(o=>t.has(o))}function Wo(e,t){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let n of e)Wo(n,t);return}if(e&&typeof e=="object")for(let n of Object.values(e))Wo(n,t)}function da(e,t,n,r){let o=[],i=new Set,s=!1;if(t&&t.length>0){let a=rp(e).replace(/\/$/,"");for(let c of t){let l=db(rp(c));l.startsWith(a+"/")&&(l=l.slice(a.length+1)),l=np.normalize(l),r.has(l)?i.add(l):o.push(`entrypoint not found in scan: ${c} \u2014 pass it relative to the scanned path (e.g. "src/index.ts"), or as an absolute path under it`)}}else{let a;try{let c=np.join(e,"package.json");a=JSON.parse(ok(c,"utf-8"))}catch{}if(a){let c=[];if(Wo(a.main,c),Wo(a.exports,c),Wo(a.bin,c),a.scripts&&typeof a.scripts=="object")for(let l of Object.values(a.scripts))typeof l=="string"&&c.push(...ak(l));for(let l of c){let u=np.normalize(db(rp(l))),p=r.has(u)?u:lk(u,r);p&&i.add(p)}}i.size===0&&(o.push("no entrypoints resolved from package.json \u2014 pass `entrypoints` explicitly, or every export in a reachable file will read as unreachable"),s=!0)}if(n)for(let a of r)op(a)&&i.add(a);return{entrypoints:[...i],warnings:o,lowConfidence:s}}function Vo(e,t){let n=new Set,r=[];for(let o of t)n.has(o)||(n.add(o),r.push(o));for(;r.length>0;){let o=r.pop(),i=e.get(o);if(i)for(let s of i.importsFiles)n.has(s)||(n.add(s),r.push(s))}return n}function ma(e){let t=0,n=new Map,r=new Map,o=new Set,i=[],s=[],a=[];for(let c of e.keys())if(!n.has(c))for(a.push({node:c,iterator:(e.get(c)?.importsFiles??new Set).values()}),n.set(c,t),r.set(c,t),t++,i.push(c),o.add(c);a.length>0;){let l=a[a.length-1],u=l.iterator.next();if(!u.done){let p=u.value;if(!n.has(p))n.set(p,t),r.set(p,t),t++,i.push(p),o.add(p),a.push({node:p,iterator:(e.get(p)?.importsFiles??new Set).values()});else if(o.has(p)){let d=r.get(l.node),m=n.get(p);r.set(l.node,Math.min(d,m))}continue}if(a.pop(),a.length>0){let p=a[a.length-1],d=r.get(p.node),m=r.get(l.node);r.set(p.node,Math.min(d,m))}if(r.get(l.node)===n.get(l.node)){let p=[],d;do d=i.pop(),o.delete(d),p.push(d);while(d!==l.node);(p.length>1||(e.get(p[0])?.importsFiles.has(p[0])??!1))&&s.push({files:p})}}return s}function Ko(e,t){return`${e}::${t}`}function uk(e,t,n,r,o,i){let s=new Set,a=[{file:e,name:t}];for(;a.length>0;){let c=a.pop(),l=Ko(c.file,c.name);if(!s.has(l)){if(s.add(l),n.has(c.file)||r.has(l))return!0;for(let u of o.get(l)??[])a.push({file:u.file,name:u.localName});for(let u of i.get(c.file)??[])a.push({file:u,name:c.name})}}return!1}function hb(e,t,n,r,o,i){let s=new Set(t.declarations.filter(d=>d.exported).map(d=>d.name)),a=new Set;for(let d of s)uk(e,d,n,r,o,i)&&a.add(d);let c=new Map,l=new Map;for(let d of t.calls){let m=c.get(d.caller)??[];m.push(d.callee),c.set(d.caller,m),s.has(d.caller)&&l.set(d.callee,(l.get(d.callee)??0)+1)}let u=[...a],p=d=>{!s.has(d)||a.has(d)||(a.add(d),u.push(d))};for(let[d,m]of c)if(!s.has(d))for(let f of m)p(f);for(let d of s)(t.referenceCounts.get(d)??0)-(l.get(d)??0)>1&&p(d);for(let d=0;d<u.length;d++){let m=u[d];for(let f of c.get(m)??[])f!==m&&p(f)}return a}async function gb(e,t,n){let r=pa(t.excludeDir),o=t.maxFiles??2e4,{facts:i,fileGraph:s,filesScanned:a,filesSkipped:c,truncated:l,dynamicImportTargets:u,starReexporters:p}=n??await Hr(e,r,o),d=new Set(i.keys()),{entrypoints:m,warnings:f,lowConfidence:h}=da(e,t.entrypoints,t.includeTests??!0,d);l&&f.push(`scan stopped at maxFiles (${o}) \u2014 results are partial, not a full-repo verdict`),c>0&&f.push(`${c} file(s) could not be read or parsed within the native graph bounds \u2014 results are partial, not a full-repo verdict`);let y=m.filter(K=>{let ne=i.get(K);return(s.get(K)?.importsFiles.size??0)===0&&(ne?.declarations.length??0)===0&&(ne?.namedReexports.length??0)===0}),g=y.length>0;g&&f.push(`${y.length} entrypoint file(s) parsed to no imports/exports (likely an extractor parse failure on that file) \u2014 reachability from them is unreliable, so "unreachable-file" results here are low-confidence and may be false positives: ${y.join(", ")}`);let S=Vo(s,m),R=new Set(m),C=new Set([...R,...u]),P=K=>t.includeTests!==!1||!op(K),T=new Map([...s].map(([K,ne])=>[K,{relativePath:ne.relativePath,importsFiles:new Set([...ne.importsFiles].filter(le=>!ne.dynamicImportsFiles.has(le))),dynamicImportsFiles:new Set,edgeKinds:new Map([...ne.edgeKinds].map(([le,xe])=>[le,new Set([...xe].filter(ye=>ye!=="dynamic-import"))]).filter(([,le])=>le.size>0))}])),E=Vo(T,m),k=[...S].filter(K=>!E.has(K)).sort();k.length>0&&f.push(`${k.length} file(s) reachable only through a dynamic import() \u2014 lower confidence than static analysis, verify with lspGetSemantics before treating as proof: ${k.join(", ")}`);let x=new Set,b=new Map;for(let K of S){let ne=i.get(K);if(ne){for(let le of ne.imports){let xe=le.resolvedTarget;xe&&x.add(Ko(xe,le.importedName))}for(let le of ne.namedReexports){let xe=le.resolvedTarget;if(!xe)continue;let ye=Ko(xe,le.importedName),it=b.get(ye)??[];it.push({file:K,localName:le.localName}),b.set(ye,it)}}}let w=new Map;for(let[K,ne]of p){let le=ne.filter(xe=>S.has(xe));le.length>0&&w.set(K,le)}let L=new Set(w.keys()),O=[],v=ma(s),A=new Map,Z=[],te=0;for(let K of v){let ne=K.files.filter(P);if(ne.length===0||!ne.every(ye=>!S.has(ye)))continue;let xe=te++;for(let ye of ne)A.set(ye,xe);Z.push({id:xe,files:ne,reason:"mutually-referencing cluster with no path from any entrypoint \u2014 each file looks locally referenced by the others, but the cluster as a whole is unreachable"})}let Ie=new Map;for(let[K,ne]of i){if(!P(K))continue;let le=R.has(K),xe=S.has(K);for(let ye of ne.declarations){if(!ye.exported)continue;if(!xe){let ii=A.get(K);O.push({file:K,name:ye.name,kind:ye.kind,line:ye.line,reason:ii!==void 0?"dead-cluster":"unreachable-file",...ii!==void 0?{clusterId:ii}:{}});continue}if(le||L.has(K)||u.has(K))continue;let it=Ie.get(K);it||(it=hb(K,ne,C,x,b,w),Ie.set(K,it)),it.has(ye.name)||O.push({file:K,name:ye.name,kind:ye.kind,line:ye.line,reason:"unreferenced-export",viaHeuristic:b.has(Ko(K,ye.name))?"reexport-chain":"lexical-count"})}}return{filesScanned:a,filesSkipped:c,entrypointsResolved:m,deadExports:O,deadClusters:Z,warnings:f,...h||g?{confidence:"low"}:{}}}import{posix as pk}from"node:path";function fa(e){return pk.normalize(e.split("\\").join("/")).replace(/^\.\//,"")}function ha(e,t){return[...e?.edgeKinds.get(t)??["static-import"]].sort()}function ip(e,t){let n=new Set(t),r=new Set;for(let o of t){let i=e.get(o);for(let s of i?.importsFiles??[])if(n.has(s))for(let a of ha(i,s))r.add(a)}return[...r].sort()}function yb(e,t,n){let r=[],o=new Set([t]),i=[{file:t,distance:0}];for(let s=0;s<i.length;s++){let a=i[s];if(a.distance>=n)continue;let c=e.get(a.file),l=[...c?.importsFiles??[]].sort();for(let u of l){if(o.has(u))continue;o.add(u);let p=a.distance+1;i.push({file:u,distance:p}),r.push({file:u,distance:p,via:a.file,edgeKinds:ha(c,u),confidence:"syntactic"})}}return r}function bb(e){let t=new Map;for(let n of e.keys())t.set(n,{relativePath:n,importsFiles:new Set,dynamicImportsFiles:new Set,edgeKinds:new Map});for(let[n,r]of e)for(let o of r.importsFiles){let i=t.get(o);if(!i)continue;i.importsFiles.add(n);let s=new Set(ha(r,o));i.edgeKinds.set(n,s),s.size===1&&s.has("dynamic-import")&&i.dynamicImportsFiles.add(n)}return t}function Sb(e,t,n){let r=new Map,o=new Set([t]),i=[t];for(let c=0;c<i.length;c++){let l=i[c];if(l===n)break;for(let u of[...e.get(l)?.importsFiles??[]].sort())o.has(u)||(o.add(u),r.set(u,l),i.push(u))}if(!o.has(n))return{found:!1,files:[],edges:[]};let s=[n];for(;s[0]!==t;)s.unshift(r.get(s[0]));let a=s.slice(0,-1).map((c,l)=>{let u=s[l+1];return{from:c,to:u,edgeKinds:ha(e.get(c),u),confidence:"syntactic"}});return{found:!0,files:s,edges:a,length:s.length,complete:!0,confidence:"syntactic"}}function Rb(e){return new Map([...e].map(([t,n])=>{let r=[...n.importsFiles].filter(o=>{let i=n.edgeKinds.get(o);return!i||i.size>1||!i.has("type-import")});return[t,{relativePath:t,importsFiles:new Set(r),dynamicImportsFiles:new Set(r.filter(o=>n.dynamicImportsFiles.has(o))),edgeKinds:new Map(r.map(o=>[o,new Set(n.edgeKinds.get(o)??["static-import"])]))}]}))}function sp(e){let t=0,n=new Map,r=new Map,o=[],i=new Set,s=[];for(let m of[...e.keys()].sort()){if(n.has(m))continue;let f=[{node:m,successors:[...e.get(m)?.importsFiles??[]].sort(),offset:0}];for(n.set(m,t),r.set(m,t++),o.push(m),i.add(m);f.length>0;){let h=f[f.length-1],y=h.successors[h.offset++];if(y!==void 0){n.has(y)?i.has(y)&&r.set(h.node,Math.min(r.get(h.node),n.get(y))):(n.set(y,t),r.set(y,t++),o.push(y),i.add(y),f.push({node:y,successors:[...e.get(y)?.importsFiles??[]].sort(),offset:0}));continue}f.pop();let g=f[f.length-1];if(g&&r.set(g.node,Math.min(r.get(g.node),r.get(h.node))),r.get(h.node)!==n.get(h.node))continue;let S=[],R;do R=o.pop(),i.delete(R),S.push(R);while(R!==h.node);s.push(S.sort())}}s.sort((m,f)=>(m[0]??"").localeCompare(f[0]??""));let a=new Map;s.forEach((m,f)=>{for(let h of m)a.set(h,f)});let c=new Map,l=new Map;s.forEach((m,f)=>{c.set(f,new Set),l.set(f,new Set)});for(let[m,f]of e){let h=a.get(m);for(let y of f.importsFiles){let g=a.get(y);g===void 0||g===h||(c.get(h)?.add(g),l.get(g)?.add(h))}}let u=new Map(s.map((m,f)=>[f,l.get(f)?.size??0])),p=[],d=[...u].filter(([,m])=>m===0).map(([m])=>m).sort((m,f)=>m-f);for(;d.length>0;){p.push(d);let m=[];for(let f of d)for(let h of[...c.get(f)??[]].sort((y,g)=>y-g)){let y=u.get(h)-1;u.set(h,y),y===0&&m.push(h)}d=m.sort((f,h)=>f-h)}return{components:s,componentOf:a,edges:c,reverseEdges:l,layers:p}}function ap(e){let t=new Set;for(let[n,r]of e)for(let o of r){let i=new Set([n]),s=[...r].filter(a=>a!==o);for(;s.length>0;){let a=s.pop();if(a===o){t.add(`${n}:${o}`);break}i.has(a)||(i.add(a),s.push(...e.get(a)??[]))}}return t}function Cb(e,t){let n=new Set,r=[],o=[{node:t,successors:[...e.get(t)?.importsFiles??[]].sort(),offset:0}];for(n.add(t);o.length>0;){let d=o[o.length-1],m=d.successors[d.offset++];if(m!==void 0){if(n.has(m))continue;n.add(m),o.push({node:m,successors:[...e.get(m)?.importsFiles??[]].sort(),offset:0});continue}o.pop(),r.push(d.node)}let i=r.reverse(),s=new Map(i.map((d,m)=>[d,m])),a=new Map(i.map(d=>[d,new Set]));for(let d of i)for(let m of e.get(d)?.importsFiles??[])a.get(m)?.add(d);let c=new Map([[t,t]]),l=(d,m)=>{let f=d,h=m;for(;f!==h;){for(;s.get(f)>s.get(h);)f=c.get(f);for(;s.get(h)>s.get(f);)h=c.get(h)}return f},u=!0;for(;u;){u=!1;for(let d of i.slice(1)){let m=[...a.get(d)??[]].filter(h=>c.has(h));if(m.length===0)continue;let f=m[0];for(let h of m.slice(1))f=l(h,f);c.get(d)!==f&&(c.set(d,f),u=!0)}}let p=new Map([[t,null]]);for(let d of i.slice(1))p.set(d,c.get(d)??null);return p}function dk(e,t){let n=new Map,r=new Map;for(let o of[...t].sort()){if(!e.has(o)||n.has(o))continue;n.set(o,"visiting");let i=[{node:o,successors:[...e.get(o)?.importsFiles??[]].filter(s=>t.has(s)).sort(),offset:0}];for(;i.length>0;){let s=i[i.length-1],a=s.successors[s.offset++];if(a===void 0){n.set(s.node,"done"),i.pop();continue}let c=n.get(a);if(!c){r.set(a,s.node),n.set(a,"visiting"),i.push({node:a,successors:[...e.get(a)?.importsFiles??[]].filter(p=>t.has(p)).sort(),offset:0});continue}if(c!=="visiting")continue;let l=[s.node];for(;l[l.length-1]!==a;){let p=r.get(l[l.length-1]);if(!p)return[];l.push(p)}l.reverse();let u=[];for(let p=0;p<l.length-1;p++)u.push({from:l[p],to:l[p+1]});return u.push({from:s.node,to:a}),u}}return[]}function cp(e,t){return dk(e,t).map(({from:n,to:r})=>({from:n,to:r,edgeKinds:[...e.get(n)?.edgeKinds.get(r)??new Set(["static-import"])].sort()}))}function lp(e){let t=new Map;return e.forEach((n,r)=>{for(let o of n)t.set(o,r)}),t}var mk=50,up=2e4,pp=5e4,dp=5e3;function Gr(e,t){let n=t.limit?e.slice(0,t.limit):e,r=n.length<e.length,o=t.pageSize??mk,i=t.page??1,s=Math.max(1,Math.ceil(n.length/o)),a=Math.min(Math.max(1,i),s),c=(a-1)*o;return{results:n.slice(c,c+o),pagination:{currentPage:a,totalPages:s,entriesPerPage:o,totalEntries:n.length,hasMore:a<s,...i>s?{outOfRange:!0}:{}},...r?{truncated:!0,partialReasons:["limit"],totalAvailable:e.length}:{}}}function fk(e,t){let n=(e.filesSkipped??0)>0;return!t&&!n?e:{...e,truncated:!0,partialReasons:[...new Set([...e.partialReasons??[],...t?["maxFiles"]:[],...n?["filesSkipped"]:[]])]}}function hk(e,t){let n=e.partialReasons?.includes("maxFiles")===!0&&(t.maxFiles??up)>=pp,r=e.partialReasons?.includes("limit")===!0&&t.limit!==void 0&&t.limit>=dp,o=e.pagination?.hasMore===!0&&e.pagination.currentPage>=1e3,i=e.partialReasons?.includes("filesSkipped")===!0;return n||r||o||i?{...e,terminalLimit:!0}:e}function gk(e,t,n){e.pagination?.outOfRange&&(e={...e,warnings:[...e.warnings??[],`page:${t.page} is out of range (only ${e.pagination.totalPages} page(s)) \u2014 returned page ${e.pagination.currentPage} instead.`]});let r={};if(e.pagination?.hasMore&&e.pagination.currentPage<1e3&&(r.nextPage=Ge("localAnalyzeGraph",{...t,page:e.pagination.currentPage+1},n)),e.partialReasons?.includes("maxFiles")&&(t.maxFiles??up)<pp){let o=t.maxFiles??up;r.expandScan=Ge("localAnalyzeGraph",{...t,maxFiles:Math.min(pp,Math.max(o+1,o*2)),page:1},"Re-run with a larger file-scan bound because this graph is partial.")}if(e.partialReasons?.includes("limit")&&t.limit!==void 0&&t.limit<dp&&(r.expandLimit=Ge("localAnalyzeGraph",{...t,limit:Math.min(dp,Math.max(t.limit+1,t.limit*2)),page:1},"Re-run with a larger result limit because additional graph results exist.")),t.operation==="deadCode"){let o=e.results[0];if(o&&typeof o.file=="string"&&typeof o.name=="string"&&typeof o.line=="number"){let i=t.path.replace(/\/+$/,"");r.verifyReferences={tool:be,query:{type:"references",uri:`${i}/${o.file}`,symbolName:o.name,lineHint:o.line,includeDeclaration:!1,groupByFile:!0},why:`Verify candidate "${o.name}" before deletion; repeat for each result, prioritizing viaHeuristic:"reexport-chain".`,confidence:"high"}}}return Object.keys(r).length>0?{...e,next:r}:e}function xb(e,t,n,r){return gk(hk(fk(e,n),t),t,r)}var yk=2e4,wb=1;function mp(e){return{entrypointsResolved:e,entrypointsResolvedCount:e.length}}function ga(e,t){return{status:"error",error:t,errorCode:"invalidGraphQuery",operation:e.operation,path:e.path,results:[]}}async function Pb(e,t={}){let n=pa(e.excludeDir),r=e.maxFiles??yk,o=await(t.getGraph?.(e.path,n,r)??Hr(e.path,n,r)),i=(d,m)=>xb(d,e,o.truncated,m);if(e.operation==="deadCode"){let d=await gb(e.path,e,o),m=Gr(d.deadExports,e),f=new Set(m.results.map(h=>h.clusterId).filter(h=>typeof h=="number"));return i({operation:e.operation,path:e.path,filesScanned:d.filesScanned,filesSkipped:d.filesSkipped,...m,summary:{...mp(d.entrypointsResolved),deadClusters:d.deadClusters.filter(h=>f.has(h.id)).map(h=>({...h,files:h.files,size:h.files.length,edgeKinds:ip(o.fileGraph,h.files),confidence:"syntactic"})),deadClusterCount:d.deadClusters.length,deadExportCount:d.deadExports.length},...d.warnings.length>0?{warnings:d.warnings}:{},...d.confidence?{confidence:d.confidence}:{}},"Continue dead-code candidates.")}let s=[...o.truncated?[`scan stopped at maxFiles (${r}) \u2014 graph results are partial`]:[],...o.filesSkipped>0?[`${o.filesSkipped} file(s) could not be read or parsed within the native graph bounds \u2014 graph results are partial`]:[]],a={operation:e.operation,path:e.path,filesScanned:o.filesScanned,filesSkipped:o.filesSkipped};if(e.operation==="cycles"){let d=sp(o.fileGraph),m=lp(d.layers),f=ap(d.edges),h=Rb(o.fileGraph),y=ma(h).map(R=>[...R.files].sort()),S=d.components.filter(R=>R.length>1||(o.fileGraph.get(R[0])?.importsFiles.has(R[0])??!1)).map(R=>{let C=d.componentOf.get(R[0]),P=new Set(R),T=y.filter(b=>b.every(w=>P.has(w))),E=cp(o.fileGraph,P),k=cp(h,P),x=C===void 0?[]:[...d.edges.get(C)??[]].sort((b,w)=>b-w);return{files:R,size:R.length,edgeKinds:ip(o.fileGraph,R),runtimeCycle:T.length>0,runtimeCycles:T,runtimeCycleCount:T.length,cycleEdges:E,runtimeCycleEdges:k,componentId:C,topologicalLayer:C===void 0?void 0:m.get(C),outgoingComponents:x,outgoingComponentCount:x.length,confidence:"syntactic"}}).sort((R,C)=>(R.files[0]??"").localeCompare(C.files[0]??""));return i({...a,...Gr(S,e),summary:{cycleCount:S.length,runtimeCycleCount:S.filter(R=>R.runtimeCycle).length,condensationComponentCount:d.components.length,condensationEdgeCount:[...d.edges.values()].reduce((R,C)=>R+C.size,0),topologicalLayerCount:d.layers.length,transitiveEdgeCount:f.size},...s.length>0?{warnings:s}:{}},"Continue cycle components.")}if(e.operation==="dependencies"||e.operation==="dependents"){if(!e.file)return i(ga(e,`${e.operation} requires file`),`Retry ${e.operation} after expanding the graph scan.`);let d=fa(e.file);if(!o.fileGraph.has(d))return i(ga(e,`file is not in the scanned graph: ${d}`),`Retry ${e.operation} after expanding the graph scan.`);let m=e.operation==="dependencies"?o.fileGraph:bb(o.fileGraph),f=sp(m),h=lp(f.layers),y=ap(f.edges),g=Cb(m,d),S=yb(m,d,e.depth??wb).map(R=>{let C=R.file,P=R.via,T=f.componentOf.get(P),E=f.componentOf.get(C);return{...R,immediateDominator:g.get(C)??null,topologicalLayer:E===void 0?void 0:h.get(E),transitiveEdge:T!==void 0&&E!==void 0?y.has(`${T}:${E}`):!1}});return i({...a,...Gr(S,e),summary:{source:d,depth:e.depth??wb,condensationComponentCount:f.components.length,topologicalLayerCount:f.layers.length,transitiveEdgeCount:y.size},...s.length>0?{warnings:s}:{}},`Continue ${e.operation}.`)}if(e.operation==="path"){if(!e.file||!e.target)return i(ga(e,"path requires file and target"),"Retry the path query after expanding the graph scan.");let d=fa(e.file),m=fa(e.target);return!o.fileGraph.has(d)||!o.fileGraph.has(m)?i(ga(e,"file and target must both be in the scanned graph"),"Retry the path query after expanding the graph scan."):i({...a,...Gr([Sb(o.fileGraph,d,m)],e),summary:{source:d,target:m},...s.length>0?{warnings:s}:{}},"Continue path results.")}let c=new Set(o.facts.keys()),l=da(e.path,e.entrypoints,e.includeTests??!0,c);if(l.lowConfidence&&l.entrypoints.length===0)return i({...a,status:"empty",results:[],summary:{...mp(l.entrypoints),classifiedCount:0,unclassifiedCount:o.fileGraph.size},warnings:[...s,...l.warnings],confidence:"low"},"Retry reachability after expanding the graph scan.");let u=Vo(o.fileGraph,l.entrypoints),p=[...o.fileGraph.keys()].sort().map(d=>({file:d,reachable:u.has(d),confidence:"syntactic"}));return i({...a,...Gr(p,e),summary:{...mp(l.entrypoints),reachableCount:u.size,unreachableCount:p.length-u.size},...s.length+l.warnings.length>0?{warnings:[...s,...l.warnings]}:{},...l.lowConfidence?{confidence:"low"}:{}},"Continue reachability classifications.")}async function Tb(e){let t=new Map,n=(r,o,i)=>{let s=JSON.stringify([r,[...o].sort(),i]),a=t.get(s);if(a)return a;let c=Hr(r,o,i);return t.set(s,c),c};return ge(e.queries||[],async r=>yt({toolName:I.LOCAL_ANALYZE_GRAPH,query:r,contextMessage:"localAnalyzeGraph execution failed",execute:async()=>{let o=ut(sn,r);if(o.ok===!1)return o.error;let i=rt(o.data,I.LOCAL_ANALYZE_GRAPH);return i.isValid?Pb({...o.data,path:i.sanitizedPath},{getGraph:n}):N(i.errorResult,o.data,{toolName:I.LOCAL_ANALYZE_GRAPH})}}),{toolName:I.LOCAL_ANALYZE_GRAPH},e)}import{access as kI}from"node:fs/promises";function Br(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 Xo(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)}}function Eb(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+Xo(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Br(r)})`}function Ab(e,t){let n=e.length,r=t.itemsPerPage||20,o=Math.max(1,Math.ceil(n/r)),i=t.page||1,s=Math.min(i,o),a=i>o,c=(s-1)*r,l=Math.min(c+r,n),u=s<o;return{paginatedEntries:e.slice(c,l),endIdx:l,pagination:{currentPage:s,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:u,...u&&s<1e3?{nextPage:s+1}:{},...a?{outOfRange:!0}:{}}}}function ya(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`]}function Lb(e){let t=e.find(r=>r.type==="file");if(t)return{fetch:{tool:"localGetFileContent",query:{path:t.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"}};let n=e.find(r=>r.type==="directory");if(n)return{viewStructure:{tool:"local.tree",query:{path:n.path},why:"Orient inside the first matched directory before reading files.",confidence:"exact"}}}var bk=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function Sk(e,t){let n=t??bk,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function _b(e){let t=e.detail==="full",n=e.detail==="modified"||t,r=n||(e.sortBy||"modified")==="modified";try{let o=rt(e,I.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:Sk(i.path,i.excludeDir)},{warnings:a,query:c}=Pk(s),l=e.limit??1e4,u={path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,extensions:c.extensions,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.time?.modifiedWithin,modifiedBefore:c.time?.modifiedBefore,accessedWithin:c.time?.accessedWithin,sizeGreater:c.size?.greater,sizeLess:c.size?.less,permissions:c.permissions,executable:c.access==="executable",readable:c.access==="readable",writable:c.access==="writable",excludeDir:c.excludeDir,limit:1e4},p=await D.queryFileSystem({...u,pathPattern:c.pathPattern}),d=p.totalDiscovered,m=p.wasCapped,f=p.entries.map(le=>Rk(le,r)),h=e.sortBy||"modified";Ck(f,h,r);let y=f.slice(0,l),g=y.length<f.length,S=m,R=xk(y,t,n),C=R.length,P=e.itemsPerPage||20,T=e.page||1,E=Math.max(1,Math.ceil(C/P)),k=(T-1)*P,x=Math.min(k+P,C),b=R.slice(k,x),w=C>0&&k>=C,L=b,O=[...p.warnings,...ya(p),...m?[`results capped at ${1e4} during the walk before sorting \u2014 sortBy:"${h}" only orders that partial set, not the true top-N across the whole tree`]:[],...w?[`page:${T} is out of range (only ${E} page(s), ${C} total file(s)) \u2014 returned 0 files. Use page:1..${E}.`]:[]],v=[...a,...O],A=T<E,Z=g&&l<1e4,te=A&&T>=1e3||(g||S)&&!Z,K={...Lb(L)??{},...A&&!te?{nextPage:Ge(I.LOCAL_FIND_FILES,{...i,page:T+1},"Continue to the next page of matched files.")}:{},...Z?{expandLimit:Ge(I.LOCAL_FIND_FILES,{...i,limit:Math.min(1e4,Math.max(l+1,l*2)),page:1},"Re-run with a larger file limit because matched files remain.")}:{}},ne={...C===0?{status:"empty"}:{},path:i.path,files:L,pagination:{currentPage:T,totalPages:E,filesPerPage:P,totalFiles:C,hasMore:A,...A&&!te?{nextPage:T+1}:{},...m||d>C?{totalFilesFound:d}:{},...w?{outOfRange:!0}:{}},...te?{terminalLimit:!0}:{},...g||S?{truncated:!0,partialReasons:[...g?["limit"]:[],...S?["walkLimit"]:[]],totalAvailable:Math.max(d,f.length)}:{},...Object.keys(K).length>0?{next:K}:{},...v.length>0&&{warnings:v}};return $(ne,p.entries.reduce((le,xe)=>le+xe.path.length,0))}catch(o){return N(o,e,{toolName:I.LOCAL_FIND_FILES})}}function Rk(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 Ck(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 xk(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(t?o.size=r.size:o.sizeFormatted=Br(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var wk=/^\d+[hdwm]$/;function Pk(e){let t=[],n=e.time;if(!n)return{warnings:t,query:e};let r={...n},o=[{key:"modifiedBefore",value:n.modifiedBefore},{key:"modifiedWithin",value:n.modifiedWithin},{key:"accessedWithin",value:n.accessedWithin}];for(let{key:i,value:s}of o)s&&!wk.test(s)&&(t.push(`time.${i}="${s}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete r[i]);return{warnings:t,query:{...e,time:r}}}function kb(e){let t=[],n=[];return!e||typeof e!="object"?(t.push("Query must be an object"),{isValid:!1,errors:t,warnings:n}):(e.mode!=="structural"&&(!e.searchText||typeof e.searchText!="string")&&t.push("`searchText` is required"),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.push('`matchWindow` requires output:"matchOnly"'),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.push('`unique` requires output:"matchOnly"'),{isValid:t.length===0,errors:t,warnings:n})}var hp=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],se={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,testPathPenalty:-3.5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},gp=2e3,yp=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Ib={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Yo={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Ib},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Ib},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},bp=/^\s*#{1,6}\s/,Zo=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,Tk=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,Ek=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,Ak=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,Lk=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,_k=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,kk=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,Ik=new Set(["typescript","javascript","rust","python","go","java","scala"]),ba=/\.([a-z0-9]+)$/i;function Jo(e){return ba.exec(e)?.[1]?.toLowerCase()??""}function Ok(e){let t=Jo(e);if(!t)return!1;for(let n of Ik)if(Yo[n].extensions.includes(t))return!0;return!1}function Sp(e,t,n){if(n&&n!=="auto")return Yo[n];let r=Jo(e),o=(t??"").toLowerCase();for(let i of hp){let s=Yo[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of hp){let s=Yo[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Yo.generic}function Sa(e){return Tk.test(e)?"generated":Ak.test(e)?"fixture":Ek.test(e)?"test":_k.test(e)?"config":Lk.test(e)?"docs":!Zo.test(e)&&(kk.test(e)||Ok(e))?"source":"unknown"}function Rp(e){if(!e)return!1;if(Zo.test(e))return!0;let t=Sa(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}function qo(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Ra(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cp(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function xp(e,t,n){if(e.indexOf(`
|
|
50
|
-
`)<0)return e;let o=e.split(`
|
|
51
|
-
`);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function wp(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(yp.test(e))return"comment";let o=vk(e,t,r);if(o<0)return"code";let i=Fk(e);return i>=0&&o>i?"comment":Ob(e,o)?"string":"code"}function vk(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function Fk(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function Ob(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function Mk(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function Nk(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function Dk(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Cp(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=xp(l,r,n.caseSensitive),p=0,d=[];r&&i&&(new RegExp(`(^|[^\\w$])${Ra(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(p+=se.exactWholeWord,d.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(p+=se.exactCaseInsensitive,d.push("case-insensitive match")):u.includes(r)&&(p+=se.substring,d.push("substring match")));let m=c.kind;if(m)p+=Hk(m,d);else{let f=wp(u,r,t.id,n.caseSensitive);f!=="code"?(p+=se.commentOrStringPenalty,d.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(qo(t.declaration,u)&&(p+=se.declarationLine,d.push("declaration line")),qo(t.export,u)&&(p+=se.exportLine,d.push("export/public line")),qo(t.import,u)&&(p+=se.importLine,d.push("import line")),t.id==="markdown"&&bp.test(u)&&(p+=se.headingLine,d.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&Gk(u,r)&&(p+=se.configKeyLine,d.push("config key match")))}p>s&&(s=p,a=d.join(", "))}return a&&o.push(a),s}function Hk(e,t){switch(e){case"declaration":return t.push("AST: declaration"),se.declarationLine;case"export":return t.push("AST: export/public"),se.exportLine;case"configKey":return t.push("AST: config key"),se.configKeyLine;case"heading":return t.push("AST: heading"),se.headingLine;case"import":return t.push("AST: import"),se.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),se.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function Gk(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function Bk(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(ba,"").includes(l))&&(s+=se.pathSegmentToken,i.push("query token in path"))}let a=Jo(e);return r.extensions.includes(a)&&t.langType&&(s+=se.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=se.sourceDir,i.push("source file")),s}function zk(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),se.lowSignalPathPenalty):e==="test"?(n.push("test file (penalized)"),se.testPathPenalty):0}function Qk(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*se.matchCountScale,r=Math.min(n,se.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function Pp(e,t){let n=Nk(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>Uk(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function Uk(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Ra(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function jk(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*se.rareQueryTokenScale,se.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function Tp(e,t,n){let r=Sp(e.path,t.langType,t.profileOverride),o=Sa(e.path),i=Mk(t.keyword),s=[],a=0;return a+=Dk(e.matches,r,t,i,s),a+=Bk(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=se.pathUnderQuery,s.push("under requested subtree")),a+=zk(o,t,s),Zo.test(e.path)&&!t.explicitLowSignal&&(a+=se.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=Qk(e.matchCount??0,s),a+=jk(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Ep(e,t,n,r={}){if(t==="matchCount"){let d=[...e].sort(vb);return{files:r.sortReverse?d.reverse():d,cappedCandidates:0}}if(t==="path"){let d=[...e].sort((m,f)=>m.path.localeCompare(f.path));return{files:r.sortReverse?d.reverse():d,cappedCandidates:0}}if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??gp,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(vb);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=Pp(i,n),l=i.map(d=>{try{return{file:d,s:Tp(d,n,c)}}catch{return{file:d,s:$k()}}});l.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let f=(m.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(m.file.path)});let u=[...l.map(d=>d.file),...s],p={files:r.sortReverse?u.reverse():u,cappedCandidates:a};return r.debug&&(p.debug=new Map(l.map(d=>[d.file.path,d.s]))),p}function $k(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function vb(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}var Fb=8,Wk=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),Vk=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Mb(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(n==="structural"&&e.some(a=>a.matches?.some(c=>c.capturesTruncated===!0))&&(s.expandCaptures={tool:"local.text",query:Ca({...t,captureText:!0}),why:"Replay this structural page with verbatim capture text because the default capture budget omitted or shortened capture payloads.",confidence:"exact"}),o?.path){if(i?.line){let c=Kk(i);s.fetch={tool:"localGetFileContent",query:Ca({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"low":"exact"};let a=Xk(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"low"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"low"}}}return r.currentPage<r.totalFilePages&&r.currentPage<1e3&&(s.nextPage={tool:"local.text",query:Ca({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&r.matchPage<1e3&&(s.nextMatchPage={tool:"local.text",query:Ca({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function Kk(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-Fb),endLine:n+Fb}}function Xk(e,t,n){if(t.output==="countLines"||t.output==="countMatches"||t.unique==="list"||t.unique==="count")return;if(n==="structural")return Yk(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.output==="matchOnly"){let o=Ap(e?.value);return o?{symbol:o}:void 0}let r=Ap(t.searchText);return r?{symbol:r}:void 0}function Yk(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=Ap(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function Ap(e){if(typeof e!="string")return;let t=e.trim();if(Vk.test(t)&&!Wk.has(t))return t}function Ca(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function xa(e,t,n,r,o){let i=t.sort??"relevance",s=n==="structural"&&i==="relevance"?"path":i,a;try{a=Ep(e,s,Jk(t),{debug:!1,sortReverse:t.sortReverse})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,p=t.output==="files"||t.output==="filesWithout",d=t.output==="countLines"||t.output==="countMatches",m=p||d,f=c.reduce((A,Z)=>A+(Z.matchCount??0),0),h=m?o?.totalOccurrences??o?.totalStructuralMatches??f:f,y=t,g=Math.min(y.itemsPerPage||Qt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=y.page||1,R=Math.max(1,Math.ceil(u/g)),C=(S-1)*g,P=Math.min(C+g,u),T=c.slice(C,P),E=u>0&&C>=u;E&&r.push(`page:${S} is out of range (only ${R} page(s), ${u} total file(s)) \u2014 returned 0 files. Use page:1..${R}.`);let k=y.maxMatchesPerFile||Qt.DEFAULT_MATCHES_PER_PAGE,x=T.map(A=>{let Z=A.matches?.length??0,te=Math.max(1,Math.ceil(Z/k)),Ie=Math.max(1,y.matchPage||1),K=(Ie-1)*k,ne=Z>0&&K>=Z,le=Math.min(K+k,Z),xe=m?void 0:A.matches?.slice(K,le),ye=xe?.length;ne&&r.push(`${A.path}: matchPage:${Ie} is out of range under maxMatchesPerFile:${k} (only ${te} page(s), ${Z} total match(es) for this file) \u2014 returned 0 rows for this file. Use matchPage:1..${te}, or drop matchPage to re-derive it from the current maxMatchesPerFile.`);let it=l?.get(A.path);return{path:A.path,...p?{}:t.output==="countLines"?{totalMatchedLines:A.matchCount||1}:t.output==="countMatches"?{totalOccurrences:A.matchCount||1}:{totalMatchRows:Z,...ye!==void 0?{returnedMatchRows:ye}:{}},...xe!==void 0&&{matches:xe},...it?{ranking:{score:it.score,profile:it.profile,pathRole:it.pathRole,reasons:it.reasons}}:{},pagination:!m&&(Z>k||ne)?{currentPage:Ie,totalPages:te,matchesPerPage:k,totalMatches:Z,hasMore:Ie<te,...Ie<te&&Ie<1e3?{nextMatchPage:Ie+1}:{},...ne?{outOfRange:!0}:{}}:void 0}}),b=x.filter(A=>A.pagination?.hasMore),w=S<R&&S>=1e3||b.length>0&&(y.matchPage||1)>=1e3||o?.capReached===!0&&(t.maxFiles??Qt.MAX_FILES_DEFAULT)>=1e5,L=Mb(x,t,n,{isFileListMode:m,currentPage:S,totalFilePages:R,matchPage:y.matchPage||1,matchesPerPage:k,hasFileWithMoreMatches:b.length>0}),O=t.maxFiles??Qt.MAX_FILES_DEFAULT;o?.capReached===!0&&O<1e5&&(L.expandScan={tool:"local.text",query:{...t,maxFiles:Math.min(1e5,Math.max(O+1,O*2)),page:1},why:"Re-run with a larger file-scan bound because this search is partial.",confidence:"exact"});let v={searchEngine:n,...o?{stats:o}:{},files:x,pagination:{currentPage:S,totalPages:R,filesPerPage:g,totalFiles:u,...p?{}:{totalMatches:h},hasMore:S<R,...S<R&&S<1e3?{nextPage:S+1}:{},...E?{outOfRange:!0}:{}},...r.length>0?{warnings:r}:{},...Object.keys(L).length>0?{next:L}:{},...w?{terminalLimit:!0}:{},...o?.capReached===!0?{truncated:!0,partialReasons:["maxFiles"]}:{}};return Zk(v,t,{totalMatches:h,totalFiles:u})}function Zk(e,t,n){return e}function Jk(e){let t=e.rankingProfile,n=!!(e.include?.length||Rp(e.path));return{queryPath:e.path,keyword:e.searchText,langType:e.langType,caseSensitive:e.caseMode==="sensitive",wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function Nb(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&qk(r)&&n.push(`pattern '${r}' looks literal \u2014 set regex:"fixed" to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&eI(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function qk(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function eI(e){return/\(\?[=!<]/.test(e)}function tI(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function nI(e){return{path:e.path,pattern:e.searchText??"",fixedString:e.regex==="fixed",perlRegex:e.regex==="perl",caseSensitive:e.caseMode==="sensitive",caseInsensitive:e.caseMode==="insensitive",wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline==="on"||e.multiline==="dotall",multilineDotall:e.multiline==="dotall",filesOnly:e.output==="files",filesWithoutMatch:e.output==="filesWithout",countLinesPerFile:e.output==="countLines",countMatchesPerFile:e.output==="countMatches",contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,maxDepth:e.maxDepth,sort:tI(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.output==="matchOnly",unique:e.unique==="list"||e.unique==="count",countUnique:e.unique==="count",matchWindow:e.matchWindow,maxCollectedFiles:1e4}}function rI(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function Db(e){let t=[],n=kb(e);if(!n.isValid)return N(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:I.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=hr.safeParse(e);if(!r.success){let h=r.error.issues.map(y=>y.message);return N(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:I.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return N(new Error("Path is required for search"),o,{toolName:I.LOCAL_RIPGREP,extra:{warnings:t}});let s=rt(o,I.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Nb({pattern:a.searchText??"",fixedString:a.regex==="fixed",perlRegex:a.regex==="perl"});if(!c.isValid)return N(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:I.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(nI(a))}catch(h){return N(h instanceof Error?h:new Error(String(h)),o,{toolName:I.LOCAL_RIPGREP})}let p=u.files.map(h=>({path:h.path,matchCount:h.matchCount,matches:h.matches.map(y=>{let g={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(g.count=y.count),y.kind!==void 0&&(g.kind=y.kind),y.scoreHint!==void 0&&(g.scoreHint=y.scoreHint),g})})),d=rI(p),m={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:p.length,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime,capped:u.stats.capped??void 0,capReason:u.stats.capReason??void 0};if(u.stats.capped&&l.push(`Search hit native collection cap (${u.stats.capReason??"resource limit"}); narrow path/include/keywords for exhaustive results.`),p.length===0){let h=['No matches. Try caseMode:"insensitive", a shorter term, or regex:"smart".',...a.include?.length||a.maxDepth!==void 0?["Remove include/maxDepth to search a wider tree."]:[],...a.wholeWord?["Set wholeWord:false to match substrings."]:[]];return $({status:"empty",searchEngine:"rg",stats:m,hints:h,warnings:[...t,...l]},d)}a.output!=="files"&&d>Qt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(d/1024)}KB).`);let f=await xa(p,o,"rg",[...t,...l],m);return $(f,d)}import{readFile as sI,stat as aI}from"node:fs/promises";var Hb={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},Gb={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}};function oI(e){return e.trim().replace(/^\./,"").toLowerCase()}function Bb(e){if(!e?.trim())return;let t=oI(e),n=Hb[t]??Gb[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function Lp(e){let t=Bb(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}var iI=/^\s*(\/\/|\/\*|\*|#)/;function Qb(e,t,n){let r=t&&Object.keys(t).length>0;if(n)return{...e?{metavars:e}:{},...r?{metavarRanges:t??void 0}:{}};let o=!1,i;if(e){i={};for(let[a,c]of Object.entries(e))c.length<=1?(c.some(l=>l.length>120)&&(o=!0),i[a]=c.map(zb)):o=!0;Object.keys(i).length===0&&(i=void 0)}let s;if(r&&t){s={};for(let[a,c]of Object.entries(t)){let u=c.length>1?c.filter(d=>!iI.test(d.text)):c;(u.length!==c.length||u.some(d=>d.text.length>120))&&(o=!0);let p=u.map(d=>({...d,text:zb(d.text)}));p.length>0&&(s[a]=p)}Object.keys(s).length===0&&(s=void 0)}return{...i?{metavars:i}:{},...s?{metavarRanges:s}:{},...o?{capturesTruncated:!0}:{}}}function zb(e){return e.length>120?`${e.slice(0,120)}\u2026`:e}var Ub=300;function cI(e){let t=e.replace(/\s+/g," ").trim();return t.length>Ub?`${t.slice(0,Ub-1)}\u2026`:t}var jb=[],$b=2e3,lI=1e6,uI="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`.";function Vb(e){if(!e||!/\)\s*\{/.test(e))return;let t=e.replace(/\)\s*\{/,"): $R {");return t===e?void 0:t}function pI(e){let t=Vb(e);return t?` Try: \`${t}\`.`:""}function Wb(e){return e.include?.length?e.include:Lp(e.langType)}async function dI(e){try{return(await aI(e)).isFile()}catch{return!1}}async function mI(e,t,n){let r=await sI(e,"utf8"),o=await D.structuralSearch(r,e,n??t.pattern,t.rule);return{files:o.length>0?[{path:e,matches:o}]:[],totalMatches:o.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Kb(e){let t=rt(e,I.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=await dI(t.sanitizedPath),r=!!e.captureText,o=R=>({path:t.sanitizedPath,pattern:R??e.pattern,rule:e.rule,...Wb(e)?{include:Wb(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:jb.length?{excludeDir:jb}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??$b,maxFileBytes:lI}),i=R=>n?mI(t.sanitizedPath,e,R):D.structuralSearchFiles(o(R)),s,a=!1,c;try{if(s=await i(),s.totalMatches===0&&e.pattern&&!e.rule&&!/[;}]\s*$/.test(e.pattern))try{let R=await i(`${e.pattern};`);R.totalMatches>0&&(s=R,a=!0)}catch{}if(s.totalMatches===0&&e.pattern&&!e.rule){let R=Vb(e.pattern);if(R)try{let C=await i(R);C.totalMatches>0&&(s=C,c=R)}catch{}}}catch(R){let C=R instanceof Error?R.message:String(R),P=e.langType||"source";return N(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${C} \u2014 use valid ${P} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearch --scheme\` for the live schema.`),e,{toolName:I.LOCAL_RIPGREP})}let l=s.files.map(R=>({path:R.path,matchCount:R.matches.length,matches:R.matches.map(C=>({line:C.startLine,endLine:C.endLine,value:cI(C.text),column:C.startCol,endColumn:C.endCol,...Qb(C.metavars,C.metavarRanges,r)}))})),u=e.maxDepth,p=l,d=0;if(typeof u=="number"&&!n){let R=t.sanitizedPath.replace(/\/+$/,"");p=l.filter(C=>(C.path.startsWith(`${R}/`)?C.path.slice(R.length+1):C.path).split("/").length<=u+1),d=l.length-p.length}let m=p.reduce((R,C)=>R+(C.matchCount??C.matches?.length??0),0),f=e.maxFiles??$b,y=(s.parsedFiles??0)+(s.skippedUnreadable??0)+(s.skippedLarge??0)>=f,g={totalStructuralMatches:typeof u=="number"?m:s.totalMatches,...y?{capReached:!0}:{}},S=[...s.warnings];if(d>0&&S.push(`maxDepth ${u}: dropped ${d} deeper file(s) \u2014 raise maxDepth or omit it to include them.`),a&&S.push(`Matched after appending ';' \u2014 statement patterns must parse as complete statements; the bare pattern parsed as an expression fragment. Results are for "${e.pattern};".`),c&&S.push(`Matched after adding a return-type metavar \u2014 the bare pattern missed functions that declare a return type. Results are for "${c}".`),s.totalMatches===0&&!n)try{let R=D.structuralSearchFilesDetailed(o()),C=R.query;if(C){let P=[`query parsed as ${C.kind}`];C.literalAnchor&&P.push(`literal anchor "${C.literalAnchor}"`),P.push(`pre-filter: ${C.preFilter}`),C.unsafeReason&&P.push(`unsafe: ${C.unsafeReason}`),S.push(`Engine explanation: ${P.join(", ")}.`);let T=[...C.diagnostics??[],...R.diagnostics??[]];for(let E of T.slice(0,3))S.push(`Engine ${E.severity} [${E.stage}/${E.code}]: ${E.message}${E.recovery?` \u2014 ${E.recovery}`:""}`);T.length>3&&S.push(`${T.length-3} additional engine diagnostic(s) omitted from this summary.`)}}catch{}return(p.length===0||g.totalStructuralMatches===0)&&e.pattern&&!e.rule&&d===0&&S.push(uI+pI(e.pattern)),await xa(p,e,"structural",S,g)}function fI(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.output==="content"?n.output="files":t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function ei(e){let t=fI(e);if(t.mode==="structural")return await Kb(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Db(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:Q.OUTPUT_TOO_LARGE}:N(n,t,{toolName:I.LOCAL_RIPGREP})}}var hI=new Set(["+","*","?"]),gI=1e3;function yI(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Xb(e,t){let n=e[t];return n===void 0?!1:hI.has(n)||n==="{"&&RI(e,t)}function bI(e,t,n){let r=n.pop()??!1,o=Xb(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?Zb(e,t+1):t+1})}function SI(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Zb(e,t)})}function Yb(e){if(e.length>gI)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=yI(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=bI(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Xb(e,r)){let i=SI(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function RI(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 Zb(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function Jb(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!Yb(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return n}function qb(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 eS(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 tS(e){let t={},n=e.find(o=>o.type==="file"&&o.path);n?.path&&(t.fetch={tool:"localGetFileContent",query:{path:n.path,minify:"standard"},why:'Read the first listed file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"});let r=e.find(o=>o.type==="directory"&&o.path);return r?.path&&(t.viewDeeper={tool:"local.tree",query:{path:r.path},why:"Descend into the first listed subdirectory.",confidence:"exact"}),t.fetch||t.viewDeeper?t:void 0}var CI=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function xI(e,t){let n=t??CI,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function nS(e){try{let t=rt(e,I.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.detail==="modified"||e.detail==="full"||e.sortBy==="time";return await wI(e,t.sanitizedPath,n)}catch(t){let n=nt.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}async function wI(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=TI(e),s=PI(e,i),a=r&&s?1e4:1e4,c=xI(t,e.excludeDir),l;try{l=await D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:EI(e),excludeDir:c,limit:a})}catch(O){return _I(O,e,t)}let u=l.entries.map(O=>AI(O,n,e.detail==="full")),p=Jb(u,e),d=e.sortBy??"name";p=p.sort((O,v)=>{let A=0;switch(d){case"size":{let Z=O.sizeBytes??(O.size?Xo(O.size):0),te=v.sizeBytes??(v.size?Xo(v.size):0);A=Z-te;break}case"time":n&&O.modified&&v.modified?A=O.modified.localeCompare(v.modified):A=O.name.localeCompare(v.name);break;case"extension":A=(O.extension||"").localeCompare(v.extension||"");break;default:A=O.name.localeCompare(v.name);break}return e.reverse?-A:A});let m=p.length;e.limit&&(p=p.slice(0,e.limit));let f=p.length<m,h=l.wasCapped,y=p.length,{paginatedEntries:g,pagination:S}=Ab(p,e),C=e.detail==="full"||e.detail==="modified"?{path:t,entries:g.map(O=>({...eS(O),path:O.path??`${t.replace(/\/$/,"")}/${O.name}`}))}:{path:t,...qb(g)},P=[...l.warnings,...ya({skipped:l.skipped,permissionDenied:l.permissionDenied}),...l.wasCapped?[`Results capped at ${a} entries during the walk before sorting \u2014 sortBy:"${d}" only orders that partial set, not the true top-N across the whole tree. Add pattern/extensions/entryType/excludeDir or reduce depth to narrow the scope.`]:[],...S.outOfRange?[`page:${e.page} is out of range (only ${S.totalPages} page(s), ${S.totalEntries} total entries) \u2014 returned page ${S.currentPage} instead.`]:[]],T=y===0,E=Eb(p),k=tS(g)??{},x=e.limit??1e4,b=f&&x<1e4,w=S.hasMore&&S.currentPage>=1e3||(f||h)&&!b,L={...k,...S.hasMore&&!w?{nextPage:Ge(I.LOCAL_VIEW_STRUCTURE,{...e,page:S.currentPage+1},"Continue to the next page of directory entries.")}:{},...b?{expandLimit:Ge(I.LOCAL_VIEW_STRUCTURE,{...e,limit:Math.min(1e4,Math.max(x+1,x*2)),page:1},"Re-run with a larger entry limit because directory entries remain.")}:{}};return $({...T?{status:"empty"}:{},...C,summary:E,...S.hasMore||S.totalPages>1||S.outOfRange?{pagination:S}:{},...Object.keys(L).length>0?{next:L}:{},...w?{terminalLimit:!0}:{},...f||h?{truncated:!0,partialReasons:[...f?["limit"]:[],...h?["walkLimit"]:[]],totalAvailable:Math.max(l.totalDiscovered,m)}:{},...P.length>0&&{warnings:P}},l.entries.reduce((O,v)=>O+v.path.length,0))}function PI(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function TI(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function EI(e){return e.entryType}function AI(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:Br(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=LI(e.permissions)),o}function LI(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 _I(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=nt.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return N(a,t,{toolName:I.LOCAL_VIEW_STRUCTURE})}var II={"local.text":"text","local.files":"files","local.tree":"tree"};async function rS(e){return ge(e.queries||[],t=>yt({toolName:Ue,query:t,contextMessage:"localSearch execution failed",execute:async()=>{let n=gr.safeParse(t);if(!n.success)throw n.error;try{await kI(n.data.path)}catch(r){throw nt.fileAccessFailed(n.data.path,r instanceof Error?r:void 0)}return _p(await OI(n.data))}}),{toolName:Ue},e)}async function OI(e){switch(e.operation){case"text":{let{operation:t,resultView:n,...r}=e;return ei(hr.parse(Rc(r,n)))}case"structural":{let{operation:t,resultView:n,...r}=e;return ei(hr.parse({...Rc(r,n),mode:"structural",output:n}))}case"files":{let{operation:t,pathRegex:n,limit:r,sort:o,pageSize:i,...s}=e;return _b({...s,regex:n,limit:r,sortBy:o,itemsPerPage:i})}case"tree":{let{operation:t,namePattern:n,limit:r,sort:o,pageSize:i,...s}=e;return nS({...s,pattern:n,limit:r,sortBy:o,itemsPerPage:i})}default:throw new Error("Unsupported localSearch operation")}}function _p(e){if(Array.isArray(e))return e.map(_p);if(!e||typeof e!="object")return e;let t=Object.fromEntries(Object.entries(e).map(([r,o])=>[r,_p(o)])),n=typeof t.tool=="string"?II[t.tool]:void 0;if(t.tool==="local.text"&&t.query&&typeof t.query=="object"&&t.query.mode==="structural"&&(n="structural"),n&&(t.tool=Ue,t.query&&typeof t.query=="object")){let r={...t.query};delete r.goal,delete r.reasoning,n==="text"?(r.resultView=typeof r.output=="string"&&r.output!=="content"?r.output:typeof r.mode=="string"&&r.mode!=="structural"?r.mode:"paginated",delete r.mode,delete r.output):n==="structural"&&(r.resultView=typeof r.output=="string"?r.output:"content",delete r.mode,delete r.output,delete r.searchText,delete r.regex,delete r.caseMode,delete r.wholeWord,delete r.invertMatch,delete r.multiline,delete r.unique,delete r.matchWindow),n==="text"||n==="structural"?(r.pageSize=r.itemsPerPage,r.reverse=r.sortReverse,delete r.itemsPerPage,delete r.sortReverse):(r.pageSize=r.itemsPerPage,r.sort=r.sortBy,delete r.itemsPerPage,delete r.sortBy,n==="files"?(r.pathRegex=r.regex,delete r.regex):(r.namePattern=r.pattern,delete r.pattern)),t.query={operation:n,...r}}return t}import{acquirePooledClientDetailed as CO,isLanguageServerAvailable as xO}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as wO}from"@octocodeai/octocode-engine/lsp/workspaceRoot";var vI=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"]);function FI(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function oS(e,t){if(t===void 0||t==="progressIdle")return e;let n=FI(e);if(!n||!vI.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}import{readFile as MI,stat as NI}from"node:fs/promises";import{SymbolResolver as DI,SymbolResolutionError as HI}from"@octocodeai/octocode-engine/lsp/resolver";import{toUri as GI}from"@octocodeai/octocode-engine/lsp/uri";import{LSP_ERROR_CODES as wa}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function kp(e,t){let n=e.uri,r=rt({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await NI(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory: ${o}.`,errorType:"not_a_file",errorCode:wa.LSP_REQUEST_FAILED,hints:["Choose a source file, or use workspaceSymbol with symbolName."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}.`,errorType:"file_not_found",errorCode:wa.LSP_REQUEST_FAILED,hints:['Use localSearch with operation:"files" to resolve the path.']}}}try{return{ok:!0,value:{uri:GI(o),absolutePath:o,content:await MI(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:wa.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function iS(e,t){let n=await kp(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 DI({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=e.lineHint!==void 0?Math.abs(o.foundAtLine-e.lineHint):void 0,l=a>1&&c!==void 0&&c>0?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.uri,range:BI(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l},...c!==void 0&&c>0?{lineDeviation:c}:{}}}}}catch(o){if(o instanceof HI)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:wa.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,'Run localSearch with operation:"text" and the exact symbol name to refresh lineHint, then retry.']}};throw o}}function BI(e){return{start:e,end:{line:e.line,character:e.character}}}import ri from"node:path";import{readFile as JI}from"node:fs/promises";import{resolveImportAliasDefinitions as qI}from"@octocodeai/octocode-engine/lsp/resolver";var Tn=40,Pa=40,Ip=10;function Op(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function vp(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Op(e.type,t),reason:t}}}function Rt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:$t(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Op(e,n),reason:n}}}function Ct(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,pageSize:r,...c&&i<1e3?{nextPage:i+1}:{}}}}function ti(e,t,n,r,o){let i=o.length>0,s=o.map(Ya),{pageItems:a,pagination:c}=Ct(s,e.page??1,e.pageSize??Pa);return{type:e.type,uri:t.uri,resolvedSymbol:$t(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function Fp(e,t,n,r){let o=n.map(p=>{let d=p.uri===t.uri&&p.range.start.line===t.resolvedSymbol.position.line&&p.range.start.character===t.resolvedSymbol.position.character;return{...p,...d?{isDefinition:!0}:{}}}),i=e.groupByFile?sS(o):void 0,s=i??o.map(Ya),{pageItems:a,pagination:c}=Ct(s,e.page??1,e.pageSize??Pa),l=o.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0,u=r?.possiblyTruncated===!0?[`Reference warmup opened ${r.warmedFiles}/${r.candidates} candidate file(s) and may be incomplete because the candidate set hit the warmup cap; narrow workspaceRoot/path or confirm with localSearch operation:"text" before unused/safe-delete claims.`]:[];return{type:"references",uri:t.uri,resolvedSymbol:$t(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...i?{byFile:a}:{locations:a},totalReferences:o.length,totalFiles:new Set(o.map(p=>p.uri)).size,...o.length>0&&o.every(p=>p.isDefinition)?{definitionOnly:!0}:{},...r?{warmup:r}:{},...l?{empty:l}:{}},pagination:c,...u.length>0?{warnings:u}:{}}}async function Mp(e,t,n){let r=aS(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:$t(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function sS(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 aS(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=>cS(r)).join(`
|
|
52
|
-
`).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 cS(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)}import{safeReadLineWindow as zI}from"@octocodeai/octocode-engine/lsp/validation";var QI={maxNodes:100,maxRequests:50},lS={truncatedByDepth:!1,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,cycleCount:0,failedRequestCount:0};function uS(e){return{...QI,...e,visitedNodeCount:0,requestCount:0,truncatedByBudget:!1}}function pS(e){return e.requestCount>=e.maxRequests?(e.truncatedByBudget=!0,!1):(e.requestCount+=1,!0)}function dS(e){return e.visitedNodeCount>=e.maxNodes?(e.truncatedByBudget=!0,!1):(e.visitedNodeCount+=1,!0)}function Ut(e,t){return{...e,truncatedByBudget:t.truncatedByBudget,visitedNodeCount:t.visitedNodeCount,requestCount:t.requestCount}}function ni(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function mS(e,t,n){if(t<=0)return e;let r=n?.[0]?.start.line??e.range.start.line,o=await zI(e.uri,r,t);if(!o)return e;let i=os(o).length,s=Math.max(0,r-t),a=s+Math.max(0,i-1);return{...e,content:o,displayRange:{startLine:s+1,endLine:a+1}}}async function UI(e,t){return Promise.all(e.map(async n=>({...n,from:await mS(n.from,t,n.fromRanges)})))}async function jI(e,t){return Promise.all(e.map(async n=>({...n,to:await mS(n.to,t)})))}async function Np(e,t,n,r,o,i=uS(void 0)){if(n<=0||!e)return{calls:[],...lS};if(!pS(i))return Ut({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getIncomingCalls(t),a=o>0?await UI(s,o):s;if(n===1)return Ut({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let l of a){let u=ni(l.from);if(r.has(u)){c.push(Ut({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!dS(i)||(r.add(u),c.push(await Np(e,l.from,n-1,r,o,i)),i.truncatedByBudget))break}return Ut({calls:[...a,...c.flatMap(l=>l.calls)],truncatedByDepth:c.some(l=>l.truncatedByDepth),cycleCount:c.reduce((l,u)=>l+u.cycleCount,0),failedRequestCount:c.reduce((l,u)=>l+u.failedRequestCount,0)},i)}catch{return Ut({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}async function Dp(e,t,n,r,o,i=uS(void 0)){if(n<=0||!e)return{calls:[],...lS};if(!pS(i))return Ut({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getOutgoingCalls(t),a=o>0?await jI(s,o):s;if(n===1)return Ut({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let l of a){let u=ni(l.to);if(r.has(u)){c.push(Ut({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!dS(i)||(r.add(u),c.push(await Dp(e,l.to,n-1,r,o,i)),i.truncatedByBudget))break}return Ut({calls:[...a,...c.flatMap(l=>l.calls)],truncatedByDepth:c.some(l=>l.truncatedByDepth),cycleCount:c.reduce((l,u)=>l+u.cycleCount,0),failedRequestCount:c.reduce((l,u)=>l+u.failedRequestCount,0)},i)}catch{return Ut({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}var $I=8;function hS(e){return $(e,G(e))}function gS(e,t){return e.format!=="compact"||!Hp(t)?t:WI(t)}function Hp(e){return kt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&kt(e.payload)}function WI(e){return{...e,format:"compact",payload:VI(e.payload)}}function VI(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(fS)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(XI)}:{locations:(e.locations??[]).map(fS)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:yS(e.root)}:{},direction:e.direction,calls:e.calls.map(YI),...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(KI)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function KI(e){if(!kt(e))return String(e);let t=ot(e,"line"),n=ot(e,"character"),r=ot(e,"endLine"),o=tn(e,"kind"),i=tn(e,"name"),s=ot(e,"childCount"),a=tn(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function fS(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${SS(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function XI(e){if(!kt(e))return String(e);let t=tn(e,"uri"),n=ot(e,"firstLine"),r=ot(e,"firstCharacter"),o=ot(e,"count"),i=bS(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 YI(e){if(!kt(e))return String(e);let t=tn(e,"direction"),n=yS(e.item),r=bS(e,"ranges").map(ZI).join(","),o=ot(e,"rangeCount"),i=ot(e,"rangeSampleCount"),s=tn(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${SS(s,180)}`:""].filter(Boolean).join(" ")}function yS(e){if(!kt(e))return String(e);let t=tn(e,"name"),n=tn(e,"kind"),r=tn(e,"uri"),o=ot(e,"line"),i=ot(e,"endLine"),s=ot(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function ZI(e){return kt(e)?`${ot(e,"line")}:${ot(e,"character")}`:String(e)}function kt(e){return typeof e=="object"&&e!==null}function tn(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function ot(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function bS(e,t){let n=e[t];return Array.isArray(n)?n:[]}function SS(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}function RS(e,t){let n=xS(e.fromRanges);return{direction:"incoming",item:Ta(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...wS(e.from,t)}}function CS(e,t){let n=xS(e.fromRanges);return{direction:"outgoing",item:Ta(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...wS(e.to,t)}}function Ta(e){return{name:e.name,kind:zr(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 xS(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>=$I))break}return n}function wS(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function zr(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"}}async function Gp(e,t,n){let o=(await n.prepareCallHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Rt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await Np(n,o,i,new Set([ni(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Dp(n,o,i,new Set([ni(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,p=c.calls.filter(S=>!l(S)),d=[...a.calls.map(S=>({direction:"incoming",...S})),...p.map(S=>({direction:"outgoing",...S}))],m=d.map(S=>S.direction==="incoming"?RS(S,e.contextLines??0):CS(S,e.contextLines??0)),{pageItems:f,pagination:h}=Ct(m,e.page??1,e.pageSize??Ip),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",g=!a.truncatedByDepth&&!c.truncatedByDepth&&!a.truncatedByBudget&&!c.truncatedByBudget&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:$t(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Ta(o),direction:y,calls:f,incomingCalls:a.calls.length,outgoingCalls:p.length,completeness:{complete:g,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,truncatedByBudget:a.truncatedByBudget||c.truncatedByBudget,visitedNodeCount:a.visitedNodeCount+c.visitedNodeCount,requestCount:a.requestCount+c.requestCount,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...d.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:h}}async function Bp(e,t,n){let o=(await n.prepareTypeHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Rt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=Ct(s,e.page??1,e.pageSize??Tn);return{type:e.type,uri:t.uri,resolvedSymbol:$t(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}var ES=new Set(["references","callers","callees","callHierarchy","implementation"]),PS=100,eO=512*1024,TS=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];async function AS(e,t,n){let r={candidates:0,warmedFiles:0,skippedLarge:0,possiblyTruncated:!1};if(typeof e.openDocument!="function")return r;try{let o=ri.extname(t.absolutePath).slice(1),i=TS.includes(o)?TS:[o],s=await ei({path:n,searchText:t.resolvedSymbol.name,regex:"fixed",wholeWord:!0,output:"files",maxFiles:PS,include:i.filter(Boolean).map(c=>`*.${c}`)}),a={candidates:s.files?.length??0,warmedFiles:0,skippedLarge:0,possiblyTruncated:(s.files?.length??0)>=PS||!!s.stats?.capped};for(let c of s.files??[]){let l=typeof c.path=="string"?c.path:void 0;if(!l)continue;let u=ri.isAbsolute(l)?l:ri.join(n,l);if(ri.resolve(u)!==ri.resolve(t.absolutePath))try{let p=await JI(u,"utf-8");if(p.length>eO){a.skippedLarge+=1;continue}await e.openDocument(u,p),a.warmedFiles+=1}catch{}}return a}catch{return r}}async function LS(e,t,n,r){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?ti(e,t,"definition","definitionProvider",await qI({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)})):Rt(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?ti(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):Rt(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?ti(e,t,"implementation","implementationProvider",await n.implementation(t.absolutePath,t.resolvedSymbol.position,t.content)):Rt(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?Fp(e,t,await n.findReferences(t.absolutePath,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content),r):Rt(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?Mp(e,t,await n.hover(t.absolutePath,t.resolvedSymbol.position,t.content)):Rt(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?Gp(e,t,n):Rt(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?Bp(e,t,n):Rt(e.type,t,"typeHierarchyProvider unsupported",!0)}}import Qp from"node:path";import{fileURLToPath as tO}from"node:url";import{unavailableHintFor as nO}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as rO}from"@octocodeai/octocode-engine/lsp/config";var zp;function Up(e){return zp||(zp=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),zp.has(Qp.extname(e).toLowerCase())}function It(e,t,n){let r=rO(e),o=nO(r,void 0),i=n?.message?` LSP startup detail (${n.kind??"startupFailed"}): ${n.message}.`:"";throw new Ne(Q.LSP_SERVER_UNAVAILABLE,`No ${r} language server is available for ${e}, so "${t}" cannot be answered semantically.${i} ${o} Meanwhile, use localSearch operation:"text" or "structural" to find occurrences, then localGetFileContent for surrounding code.`)}var oO=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];function _S(e,t){let n=e.startsWith("file://")?tO(e):e;return Qp.isAbsolute(n)?n:Qp.resolve(t,n)}function jp(){return[...D.getSupportedJsTsExtensions(),...oO]}function kS(){return jp().map(e=>`**/*.${e}`)}var iO=[".git","node_modules","dist","out","coverage","target"];async function IS(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:kS(),excludeDir:[...iO],maxSnippetChars:1})).files[0]?.path}catch{return}}async function $p(e,t){if(e.uri)return _S(e.uri,t);let n=await IS(e,t);if(n)return n;try{let o=(await D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:jp(),maxDepth:5,limit:1})).entries[0];if(o)return o.path}catch{}return t}function Wp(e){return e instanceof Error?e.message:String(e)}function Vp(e,t){if(!Up(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}function sO(e){if(!e||typeof e!="object")return!1;let t=e,n=r=>!!r&&typeof r=="object"&&typeof r.line=="number"&&typeof r.character=="number";return n(t.start)&&n(t.end)}function OS(e,t){if(!Up(e))return null;try{let n=D.extractGraphFacts(t,e);if(!n)return null;let r=JSON.parse(n),i=(Array.isArray(r.declarations)?r.declarations:[]).filter(s=>typeof s.name=="string"&&ca(s.name)&&typeof s.kind=="string"&&sO(s.range)).map(s=>({name:s.name,kind:s.kind,range:s.range}));return i.length>0?i:null}catch{return null}}import{acquirePooledClient as aO,isLanguageServerAvailable as cO}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as lO}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Yp(e){let t=await kp(e,be);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await lO(t.value.absolutePath),r=await cO(t.value.absolutePath,n),o=r?await aO(n,t.value.absolutePath):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Vp(t.value.uri,t.value.content),l=c?.length?null:OS(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(l?.length)s=l,a="native-graph-facts";else if(i&&o){let g=await o.documentSymbols(t.value.absolutePath,t.value.content);s=Array.isArray(g)?g:[],a="lsp"}else{let g=eh(t.value.content,t.value.uri);g&&(s=g,a="markdown")}let u=a!==void 0;!u&&!r&&It(t.value.uri,"documentSymbols");let p=vS(s),d=MS(s),{pageItems:m,pagination:f}=Ct(p,e.page??1,e.pageSize??Tn),h=NS(p,g=>g.kind),y=u?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:p.length,returnedSymbols:m.length,topLevelSymbols:d,kinds:h},payload:{kind:"documentSymbols",symbols:m,...y?{empty:y}:{}},pagination:f}}function vS(e){let t=[];for(let n of e)Zp(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Zp(e,t,n){if(!e||typeof e!="object")return;let r=e,o=FS(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:zr(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)&&uO.has(zr(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Zp(s,t,i)}}var uO=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"]);function FS(e){if(Kp(e.range))return e.range;let t=e.location;return t&&Kp(t.range)?t.range:void 0}function Kp(e){if(!e||typeof e!="object")return!1;let t=e;return Xp(t.start)&&Xp(t.end)}function Xp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function MS(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function NS(e,t){let n={};for(let r of e){let o=t(r),i=n[o];n[o]=typeof i=="number"?i+1:1}return n}import DS from"node:path";import{readFile as pO}from"node:fs/promises";import{acquirePooledClientDetailed as HS,isLanguageServerAvailable as GS}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as dO}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as BS}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Jp(e){let t=e.symbolName??"",n=DS.resolve(e.workspaceRoot??(e.uri?await BS(e.uri):process.cwd())),r=await $p(e,n);await GS(r,n)||It(r,"workspaceSymbol");let i=await HS(n,r);i.ok===!1&&It(r,"workspaceSymbol",i);let s=i.client;if(!s.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let a;try{DS.extname(r)&&await s.openDocument(r),a=await s.workspaceSymbol(t)}catch(p){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${Wp(p)}`}}}let c=await fO(s,zS(a)),{pageItems:l,pagination:u}=Ct(c,e.page??1,e.pageSize??Tn);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:c.length},payload:c.length>0?{kind:"workspaceSymbol",query:t,symbols:l,totalSymbols:c.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:u}}var mO=10;async function fO(e,t){return t.length===0||t.length>mO?t:Promise.all(t.map(async n=>{try{if(!n.uri)return n;let r=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri,o=await pO(r,"utf8");await e.openDocument(r);let i=await dO({anchorUri:r,symbolName:n.name,locations:await e.gotoDefinition(r,{line:n.line-1,character:n.character},o)});if(!Array.isArray(i)||i.length!==1)return n;let s=i[0],a=(s.range?.start?.line??-1)+1;return!s.uri||a<1||s.uri===n.uri&&a===n.line?n:{...n,uri:s.uri,line:a,endLine:(s.range?.end?.line??s.range?.start?.line??a-1)+1,character:s.range?.start?.character??n.character}}catch{return n}}))}function zS(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:zr(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function qp(e){let t=e.uri??"",n=e.workspaceRoot??(t?await BS(t):process.cwd());await GS(t,n)||It(t,"diagnostic");let o=await HS(n,t);o.ok===!1&&It(t,"diagnostic",o);let i=o.client;if(!i.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let s=await i.getDiagnostics(t),a=QS(s),c=a.filter(d=>d.severity===1).length,l=a.filter(d=>d.severity===2).length,{pageItems:u,pagination:p}=Ct(a,e.page??1,e.pageSize??Tn);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:a.length,errorCount:c,warningCount:l},payload:a.length>0?{kind:"diagnostic",diagnostics:u,totalDiagnostics:a.length,errorCount:c,warningCount:l}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:p}}function QS(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>US(r))}return[]}function US(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}var hO=new Set(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),gO=new Set(["symbolNotFound","anchorFailed"]);function yO(e){if(e.kind==="empty"&&typeof e.category=="string")return{category:e.category,...typeof e.reason=="string"?{reason:e.reason}:{}};let t=e.empty;if(kt(t)&&typeof t.category=="string")return{category:t.category,...typeof t.reason=="string"?{reason:t.reason}:{}}}function bO(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"rs":return"^\\s*pub\\s";case"py":case"pyi":return"^\\s*(def|class)\\s";case"go":return"^(func|type|var|const)\\s";case"java":case"kt":case"scala":case"cs":return"^\\s*(public|protected|internal)\\s";case"rb":return"^\\s*(def|class|module)\\s";default:return"^\\s*export\\s"}}function SO(e,t){let n=e.symbolName;if(typeof n=="string"&&n.trim())return n.trim();let r=t.resolvedSymbol?.name;if(typeof r=="string"&&r.trim())return r.trim()}function Ea(e){return e.startsWith("file://")?decodeURIComponent(e.slice(7)):e}function RO(e,t){if(!kt(t.pagination))return;let{hasMore:n,nextPage:r}=t.pagination;if(!(n!==!0||typeof r!="number"||r>1e3))return Ge("lspGetSemantics",{...e,page:r},`Continue semantic ${e.type} results on page ${r}.`)}function jS(e,t){if(!Hp(t))return t;let n=t;if(kt(n.pagination)&&n.pagination.hasMore===!0&&typeof n.pagination.currentPage=="number"&&n.pagination.currentPage>=1e3){let{nextPage:C,...P}=n.pagination;n={...n,pagination:P,terminalLimit:!0}}let r=n.payload,o=r.warmup?.possiblyTruncated===!0,i=r.completeness?.truncatedByDepth===!0,s=r.completeness?.truncatedByBudget===!0,a="depth"in e?e.depth??1:1,c=i&&a<20,l=SO(e,n),u=n.workspaceRoot??e.workspaceRoot??(n.uri?Ea(n.uri):void 0),p=[...o?["warmupCap"]:[],...i?["depth"]:[],...s?["budget"]:[]];p.length>0&&(n={...n,truncated:!0,partialReasons:p,...(s||i&&!c)&&{terminalLimit:!0}});let d=RO(e,n),m={...n.next??{},...d?{nextPage:d}:{},...c?{expandDepth:Ge("lspGetSemantics",{...e,depth:Math.min(20,Math.max(a+1,a*2)),page:1},"Re-run with a larger call-hierarchy depth because deeper calls remain.")}:{},...o&&l&&u?{verifyCompleteness:Ge("localSearch",{operation:"text",path:u,searchText:l,wholeWord:!0,resultView:"files"},"The LSP consumer warmup hit its file cap; search the complete workspace lexically for additional consumer files.")}:{}},f=r.locations?.[0],h=f?.displayRange?.startLine;if(f?.uri&&typeof h=="number"){let C=Ea(f.uri);return{...n,next:{...m,readSite:{tool:"localGetFileContent",query:{path:C,startLine:Math.max(1,h-3),endLine:(f.displayRange?.endLine??h)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}let y=yO(r);if(y?.category==="unsupportedOperation"&&n.type==="documentSymbols"&&n.uri){let C=Ea(n.uri);return{...n,next:{...m,textSearch:{tool:"localSearch",query:{operation:"text",path:C,searchText:bO(C),regex:"perl"},why:"documentSymbols is unsupported for this file's language server \u2014 fall back to a regex search over top-level declarations for an outline.",confidence:"low"}}}}if(!y||!l||!hO.has(y.category))return Object.keys(m).length>0?{...n,next:m}:n;let g=n.type==="workspaceSymbol"?n.workspaceRoot??e.workspaceRoot??n.uri??e.uri:n.uri??e.uri??n.workspaceRoot??e.workspaceRoot;if(!g)return n;let S=Ea(g),R={...m,textSearch:{tool:"localSearch",query:{operation:"text",path:S,searchText:l},why:`Semantic ${n.type} returned no result (${y.category}) \u2014 fall back to a text search for "${l}"`,confidence:"low"}};return gO.has(y.category)&&n.uri&&(R.reAnchor={tool:"lspGetSemantics",query:{type:"documentSymbols",uri:n.uri},why:"Re-anchor: list this file's symbols to find the correct lineHint, then retry the semantic query",confidence:"medium"}),{...n,next:R}}async function $S(e){return ge(e.queries||[],async t=>{let n=ut(Jr,t);if(n.ok===!1)return n.error;let r=n.data;return yt({toolName:be,query:r,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let o=await PO(r);return hS(jS(r,gS(r,o)))}})},{toolName:be,minQueryTimeoutMs:3e4},e)}async function PO(e){if(e.type==="documentSymbols")return Yp(e);if(e.type==="workspaceSymbol")return Jp(e);if(e.type==="diagnostic")return qp(e);let t=await iS(e,be);if(t.ok===!1){let l=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return vp(e,l)}let n=e.workspaceRoot??await wO(t.value.absolutePath);await xO(t.value.absolutePath,n)||It(t.value.uri,e.type);let o=await CO(n,t.value.absolutePath);o.ok===!1&&It(t.value.uri,e.type,o);let i=o.client,s=ES.has(e.type)?await AS(i,t.value,n):void 0,a=i.getReadiness?.(),c=await LS(e,t.value,i,s);return oS({...c,workspaceRoot:n},a)}var oi={security:"remote",requiresServerRuntime:!0,requiresProviders:!0},TO={[mt]:{isDefault:!0,isLocal:!1,type:"search",direct:{executionFn:oy,...oi}},[re.GITHUB_FETCH_CONTENT]:{isDefault:!0,isLocal:!1,type:"content",direct:{executionFn:Dg,...oi}},[de]:{isDefault:!0,isLocal:!1,type:"history",direct:{executionFn:Ly,...oi}},[fe]:{isDefault:!0,isLocal:!1,type:"history",direct:{executionFn:_y,...oi}},[re.PACKAGE_SEARCH]:{isDefault:!0,isLocal:!1,type:"search",direct:{executionFn:$y,security:"remote",requiresServerRuntime:!0}},[re.GITHUB_CLONE_REPO]:{isDefault:!0,isLocal:!0,isClone:!0,type:"content",direct:{executionFn:rg,timeoutMs:15e4,...oi}},[Ue]:{isDefault:!0,isLocal:!0,type:"search",direct:{executionFn:rS,security:"basic"}},[Mt]:{isDefault:!0,isLocal:!0,type:"search",direct:{executionFn:Tb,security:"basic"}},[re.LOCAL_FETCH_CONTENT]:{isDefault:!0,isLocal:!0,type:"content",direct:{executionFn:cb,security:"basic"}},[be]:{isDefault:!0,isLocal:!0,type:"content",direct:{executionFn:$S,security:"basic",requiresServerRuntime:!0}}};function EO(e){let t=TO[e.name];if(!t)throw new Error(`Missing runtime configuration for ${e.name}`);return{name:e.name,title:e.title,description:e.description,...t,direct:{schema:e.schema,inputSchema:e.inputSchema,...t.direct}}}function AO(){let e=new Map(qr.map(m=>{let f=EO(m);return[f.name,f]})),t=m=>{let f=e.get(m);if(!f)throw new Error(`Missing direct-tool specification for ${m}`);return f},n=t(mt),r=t(re.GITHUB_FETCH_CONTENT),o=t(de),i=t(fe),s=t(re.PACKAGE_SEARCH),a=t(re.GITHUB_CLONE_REPO),c=t(Ue),l=t(Mt),u=t(re.LOCAL_FETCH_CONTENT),p=t(be),d=qr.map(m=>t(m.name));return{GITHUB_SEARCH:n,GITHUB_FETCH_CONTENT:r,GITHUB_SEARCH_HISTORY:o,GITHUB_GET_HISTORY_ITEM:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_SEARCH:c,LOCAL_ANALYZE_GRAPH:l,LOCAL_FETCH_CONTENT:u,LSP_GET_SEMANTIC_CONTENT:p,ALL_TOOLS:d}}var Ot=AO(),mJ=Ot.GITHUB_SEARCH,fJ=Ot.GITHUB_FETCH_CONTENT,hJ=Ot.GITHUB_SEARCH_HISTORY,gJ=Ot.GITHUB_GET_HISTORY_ITEM,yJ=Ot.PACKAGE_SEARCH,bJ=Ot.GITHUB_CLONE_REPO,SJ=Ot.LOCAL_SEARCH,RJ=Ot.LOCAL_ANALYZE_GRAPH,CJ=Ot.LOCAL_FETCH_CONTENT,xJ=Ot.LSP_GET_SEMANTIC_CONTENT,WS=Ot.ALL_TOOLS;import{ContentSanitizer as _O}from"@octocodeai/octocode-engine/security";function VS(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:LO(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 LO(e){try{return JSON.stringify(e)}catch{return}}var kO="[content withheld: sanitization failed \u2014 retry the call; if this persists, report it]";function ed(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:Jt(t.structuredContent)}}catch{t={...t,structuredContent:{results:[],status:"error",code:"SANITIZATION_FAILED",error:"structuredContent withheld: sanitization failed \u2014 retry the call; if this persists, report it"},isError:!0}}return t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=_O.sanitizeContent(n.text);return{...n,text:r}}catch{return{...n,text:kO}}return n})}),t}var IO="TOOL_CALLBACK_EXCEPTION";function td(e,t){let n=VS(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
53
|
-
message: ${n.message}`}],structuredContent:{results:[],status:"error",tool:e,code:IO,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return ed(r)}catch{return r}}import{withSecurityValidation as OO,withBasicSecurityValidation as vO}from"@octocodeai/octocode-engine/security";function KS(e,t,n){let r=OO(e,(o,i)=>t(o,i),n);return(o,i)=>r(o,{authInfo:i?.http?.authInfo,sessionId:i?.sessionId,signal:i?.mcpReq.signal})}function XS(e,t,n){let r=vO((o,i)=>e(o,i),t,n);return(o,i)=>r(o,{signal:i?.mcpReq.signal})}var Aa=null,La=null,_a=null,MO=Tf;function NO(e){let t=e;return n=>t(n)}function DO(e){let{direct:t}=e;return{name:e.name,title:e.title,description:e.description,schema:t.schema,inputSchema:t.inputSchema,execute:NO(t.executionFn),security:t.security,isLocal:e.isLocal,isDefault:e.isDefault,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders,timeoutMs:t.timeoutMs}}var HO=WS.map(DO);function GO(e){return HO.find(t=>t.name===e)}async function YS(e,t){let n=GO(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=BO(n,t);return QO(n),await zO(n),await UO(n,r)}catch(r){return td(n.name,r)}}function BO(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function zO(e){e.requiresServerRuntime||(_a||(_a=qi(Dt()).then(()=>{}).catch(t=>{throw _a=null,t})),await _a),e.requiresServerRuntime&&(Aa||(Aa=MO().catch(t=>{throw Aa=null,t})),await Aa),e.requiresProviders&&(La||(La=Ih().then(()=>{}).catch(t=>{throw La=null,t})),await La)}function QO(e){let t=FO(),n=t.tools.enabled??[],r=t.tools.disabled??[];if(e.isLocal&&!t.local.enabled){let o=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw o.code="localToolsDisabled",o}if(e.isClone&&!t.local.enableClone){let o=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true to use it.`);throw o.code="cloneDisabled",o}if(n.length>0&&!n.includes(e.name)){let o=new Error(`Tool "${e.name}" is outside the TOOLS_TO_RUN allowlist.`);throw o.code="toolNotEnabled",o}if(!e.isDefault&&!n.includes(e.name)){let o=new Error(`Tool "${e.name}" is opt-in. Add it to TOOLS_TO_RUN or .octocoderc tools.enabled.`);throw o.code="toolNotEnabled",o}if(n.length===0&&r.includes(e.name)){let o=new Error(`Tool "${e.name}" is disabled by DISABLE_TOOLS.`);throw o.code="toolDisabled",o}}async function UO(e,t){try{let n=e.security==="remote"?await jO(e,t):await $O(e,t);return ed(n)}catch(n){return td(e.name,n)}}async function jO(e,t){return KS(e.name,async(r,o)=>e.execute({...r,authInfo:o.authInfo,sessionId:o.sessionId,signal:o.signal}),{timeoutMs:e.timeoutMs})(t)}async function $O(e,t){return XS(e.execute,e.name,{timeoutMs:e.timeoutMs})(t)}import{SYSTEM_PROMPT as WO}from"@octocodeai/octocode-core";var ZS={systemPrompt:WO,toolNames:st,baseSchema:En,tools:Object.fromEntries(Wd.map(e=>[e.name,{description:e.description}]))};var nd=null;function VO(){return nd||(nd=ZS),nd}async function KO(){return VO()}export{wc as DIRECT_TOOL_CATEGORIES,Tc as DIRECT_TOOL_DEFINITIONS,ft as DirectToolInputError,rx as buildDirectToolExampleQuery,YS as executeDirectTool,We as findDirectToolDefinition,PE as formatCallToolResultForOutput,XC as formatDirectToolMetadataSchemaText,KC as formatDirectToolSchemaText,YC as getDirectToolAutoFilledFields,Pc as getDirectToolCategory,ZC as getDirectToolDescription,to as getDirectToolDisplayFields,KO as loadToolContent,sm as prepareDirectToolInput,px as prepareDirectToolInputFromJsonText,WC as sortDirectToolNames};
|
|
8
|
+
import{a as me,b as de}from"./chunks/direct/chunk-DBI23PBG.js";import{c as ne,d as ie}from"./chunks/direct/chunk-DBSQWRFS.js";import{a as ce,b as le}from"./chunks/direct/chunk-O5ETB2W5.js";import{a as se,b as ae}from"./chunks/direct/chunk-43RVQWTG.js";import{b as ge,c as Se,d as Ce,e as Oe}from"./chunks/direct/chunk-ZUNPQVMO.js";import{a as ye,b as he}from"./chunks/direct/chunk-A4WMBDEC.js";import{a as d}from"./chunks/direct/chunk-3AA4F3QO.js";import"./chunks/direct/chunk-OA6NU4KO.js";import{K as Ae,p as Ee,q as be}from"./chunks/direct/chunk-RRSY2ZPX.js";import"./chunks/direct/chunk-CBIKUVP6.js";import"./chunks/direct/chunk-Y5OCKUQX.js";import"./chunks/direct/chunk-CBCZVCTZ.js";import{b as fe,c as Te}from"./chunks/direct/chunk-BICVXQ5F.js";import"./chunks/direct/chunk-MPTAIBY7.js";import{a as re}from"./chunks/direct/chunk-DKGYPFGX.js";import{a as ue,b as pe}from"./chunks/direct/chunk-IFPXDKUV.js";import{f as oe}from"./chunks/direct/chunk-USZL65FN.js";import{C as W,L as ee,M as te,P as _e,a as K,b as X,c as S,d as C,e as O,f as _,g as E,h as c,i as y,ia as De,ja as Xe}from"./chunks/direct/chunk-BMM5H6QF.js";import{z as D}from"zod";var We=W({name:"ghCloneRepo",type:"Github",shortDescription:"Clone a GitHub repo or subtree locally for repeated reads, search, or LSP.",instructions:d.ghCloneRepo,schema:{branch:"Branch, tag, or full 40-character commit SHA to check out; defaults to the repository default branch.",sparsePath:"Bound checkout to a repo-relative file/dir.",forceRefresh:"Bypass cached clone."}}),Re=te(We.schema,{...ee,owner:D.string(),repo:D.string(),branch:D.string().optional(),sparsePath:D.string().optional(),forceRefresh:D.boolean().optional()});var G=re(Re),we=oe(G);var R=[{name:O,title:"GitHub Search",description:d.ghSearch,schema:ce,inputSchema:le},{name:c.GITHUB_FETCH_CONTENT,title:"GitHub File Content Fetch",description:d.ghGetFileContent,schema:se,inputSchema:ae},{name:_,title:"GitHub History Search",description:d.ghSearchHistory,schema:ge,inputSchema:Se},{name:E,title:"GitHub History Item",description:d.ghGetHistoryItem,schema:Ce,inputSchema:Oe},{name:c.PACKAGE_SEARCH,title:"Package Search",description:d.npmSearch,schema:ye,inputSchema:he},{name:c.GITHUB_CLONE_REPO,title:"Clone / Fetch GitHub Repository Locally",description:d.ghCloneRepo,schema:G,inputSchema:we},{name:C,title:"Local Search",description:d.localSearch,schema:fe,inputSchema:Te},{name:S,title:"Local Analyze Graph",description:d.localAnalyzeGraph,schema:ue,inputSchema:pe},{name:c.LOCAL_FETCH_CONTENT,title:"Local Fetch Content",description:d.localGetFileContent,schema:me,inputSchema:de},{name:y,title:"Get Semantic Content",description:d.lspGetSemantics,schema:ne,inputSchema:ie}];var q=["GitHub","Local Code","Package","Other"],Le=new Map([O,_,E,c.GITHUB_FETCH_CONTENT,c.GITHUB_CLONE_REPO,C,S,c.LOCAL_FETCH_CONTENT,y,c.PACKAGE_SEARCH].map((e,t)=>[e,t])),f=class extends Error{constructor(o,r=[]){super(o);this.details=r;this.name="DirectToolInputError"}details},et=["goal","reasoning"],w=new Set([...et]);function tt(e){return{name:e.name,title:e.title,description:e.description,schema:e.schema,inputSchema:e.inputSchema}}var B=R.map(e=>tt(e)),xe=[...B];function p(e){return B.find(t=>t.name===e)}function M(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===c.PACKAGE_SEARCH?"Package":"Other"}function ot(e){return[...e].sort((t,o)=>{let r=q.indexOf(M(t)),n=q.indexOf(M(o));if(r!==n)return r-n;let i=Le.get(t)??Number.MAX_SAFE_INTEGER,s=Le.get(o)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(o)})}function Ie(e){return e!==O?[]:[{label:"code search",query:{operation:"code",keywords:["localSearch"],owner:"bgauryy",repo:"octocode",pageSize:5}},{label:"repository search",query:{operation:"repositories",keywords:["code research"],language:"TypeScript",pageSize:5}},{label:"repository tree",query:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}]}function He(e){let t=Ie(e);return t.length>0?t:e===_?[{label:"PR search (list)",query:{operation:"pullRequests",owner:"bgauryy",repo:"octocode",keywords:["localSearch"],concise:!0,pageSize:5}},{label:"issue search (list)",query:{operation:"issues",owner:"bgauryy",repo:"octocode",keywords:["schema"],state:"open",pageSize:5}},{label:"commit history",query:{operation:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"6m",pageSize:10}}]:e===c.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===C?[{label:"text anchors",query:{operation:"text",path:"/ABS/repo/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural matches",query:{operation:"structural",path:"/ABS/repo/src",pattern:"eval($X)",langType:"typescript"}},{label:"file discovery",query:{operation:"files",path:"/ABS/repo",names:["package.json"],entryType:"f"}},{label:"tree orientation",query:{operation:"tree",path:"/ABS/repo/src",maxDepth:2}}]:e===c.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"/ABS/repo/packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"/ABS/repo/packages/octocode-tools-core/src/tools/directToolCatalog/toolCommandPatternQueries.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===S?[{label:"dead code from detected entrypoints",query:{operation:"deadCode",path:"/ABS/repo",limit:20}},{label:"cycles",query:{operation:"cycles",path:"/ABS/repo",limit:20}},{label:"dependencies of one file",query:{operation:"dependencies",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"dependents of one file",query:{operation:"dependents",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"shortest dependency path",query:{operation:"path",path:"/ABS/repo",file:"src/index.ts",target:"src/responses.ts"}},{label:"reachability from detected entrypoints",query:{operation:"reachability",path:"/ABS/repo",limit:20}}]:e===c.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===E?[{label:"pull request detail",query:{operation:"pullRequest",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,patches:{mode:"all"}}}},{label:"issue detail",query:{operation:"issue",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,comments:{discussion:!0}}}},{label:"exact commit",query:{operation:"commit",owner:"bgauryy",repo:"octocode",ref:"main"}},{label:"compare two refs (base...head)",query:{operation:"compare",owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===c.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{keywords:["schema","validation"],page:1}}]:e===y?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}import{z as Ne}from"zod";function L(e){let t=p(e);if(!t)return[];let o=Ne.toJSONSchema(t.schema,{io:"input"});if(!g(o))return[];let r=v(o),n=it(r),i=st(r,n);return z(n,i)}function ke(e,t){let o=p(e);if(!o)return new Set;let r=Ne.toJSONSchema(o.schema,{io:"input"});if(!g(r))return new Set;let n=v(r),i=n.filter(a=>rt(a,t)),s=i.length>0?i:n;return new Set(s.flatMap(a=>T(a.properties)?Object.keys(a.properties):[]))}function rt(e,t){if(!T(e.properties))return!0;for(let[o,r]of Object.entries(t)){let n=e.properties[o];if(g(n)&&("const"in n&&r!==n.const||Array.isArray(n.enum)&&!n.enum.some(i=>i===r)))return!1}return!0}function nt(e){let t=[],o=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return o!==void 0&&r!==void 0?t.push(`${o}-${r}`):o!==void 0?t.push(`>=${o}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function H(e){if("const"in e)return`enum(${String(e.const)})`;if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let o=g(e.items)?e.items:void 0;return`array<${o?H(o):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let o=t.filter(g).map(H).filter(r=>r!=="value");if(o.length>0)return[...new Set(o)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function v(e){return T(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(g).flatMap(o=>v(o))}function it(e){let t=new Map;for(let o of e)if(T(o.properties))for(let[r,n]of Object.entries(o.properties)){if(!g(n))continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return Object.fromEntries([...t].map(([o,r])=>{let n=r.filter(s=>"const"in s).map(s=>s.const);return n.length===r.length?[o,{enum:[...new Set(n)],description:o==="operation"?"Required operation selector.":r[0]?.description}]:new Set(r.map(H)).size>1?[o,{anyOf:r}]:[o,r[0]??{}]}))}function st(e,t){if(e.length===0)return new Set;let o=e.map(n=>new Set(Array.isArray(n.required)?n.required:[])),r=[...o[0]??new Set].filter(n=>o.every(i=>i.has(n)));return new Set(r.filter(n=>!w.has(n)&&!j(t[n])))}function z(e,t,o=""){let r=[];for(let[n,i]of Object.entries(e)){if(!o&&w.has(n))continue;let s=g(i)?i:{},a=o?`${o}.${n}`:n;if(r.push({name:a,required:t.has(n),type:H(s),constraints:nt(s),description:typeof s.description=="string"?s.description:void 0}),T(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(m=>typeof m=="string"?!j(s.properties?.[m]):!1):[]);r.push(...z(s.properties,u,a))}let l=s.type==="array"&&g(s.items)?s.items:void 0;if(l&&T(l.properties)){let u=new Set(Array.isArray(l.required)?l.required.filter(m=>typeof m=="string"?!j(l.properties?.[m]):!1):[]);r.push(...z(l.properties,u,a))}}return r}function Pe(e,t){if(t.startsWith("array<")){let o=t.slice(6,-1);return[Fe(e,o)]}return Fe(e,t)}function Fe(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return e}}function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function g(e){return T(e)}function j(e){return g(e)&&"default"in e}function Ge(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function at(e){let t=He(e);if(t.length>0)return t.map(r=>({...r,command:Ge(e,r.query)}));let o=lt(e);return Object.keys(o).length===0?[]:[{label:"schema-derived",query:o,command:Ge(e,o)}]}function ct(e){return at(e)[0]?.query??{}}function lt(e){if(!p(e))return{};let t=L(e),o=t.filter(i=>!i.name.includes(".")),r=ut(o),n={};for(let i of r)n[i.name]=Pe(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(n.uri??="uri"),e===y&&(n.type??="definition",n.symbolName??="symbolName",n.lineHint??=1),n}var qe=4,U=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),Me=new Set(["page","itemsPerPage","limit","pageSize","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function ut(e){let t=e.filter(i=>i.required),o=new Map;for(let i of t)o.set(i.name,i);let r=e.filter(i=>!i.required&&pt(i)).sort(mt),n=Math.max(qe,t.length);for(let i of r){if(o.size>=n)break;o.set(i.name,i)}return o.size>0?[...o.values()]:e.filter(i=>!Me.has(i.name)).filter(i=>i.type!=="boolean").slice(0,qe)}function pt(e){return Me.has(e.name)||e.type==="boolean"?!1:dt(e)?U.has(e.name):!0}function mt(e,t){let o=U.get(e.name)??Number.MAX_SAFE_INTEGER,r=U.get(t.name)??Number.MAX_SAFE_INTEGER;return o!==r?o-r:e.name.localeCompare(t.name)}function dt(e){return e.constraints?.includes("default ")===!0}import{getConfigSync as Et}from"@octocodeai/config";var x={security:"remote",requiresServerRuntime:!0,requiresProviders:!0},ft={[O]:{isDefault:!0,isLocal:!1,type:"search",direct:{executionFn:async e=>(await import("./chunks/direct/execution-3T4B776P.js")).executeGitHubSearch(e),...x}},[c.GITHUB_FETCH_CONTENT]:{isDefault:!0,isLocal:!1,type:"content",direct:{executionFn:async e=>(await import("./chunks/direct/execution-5BJNS7D7.js")).fetchMultipleGitHubFileContents(e),...x}},[_]:{isDefault:!0,isLocal:!1,type:"history",direct:{executionFn:async e=>(await import("./chunks/direct/historyExecutions-6F3AA5PY.js")).searchMultipleGitHubHistory(e),...x}},[E]:{isDefault:!0,isLocal:!1,type:"history",direct:{executionFn:async e=>(await import("./chunks/direct/historyExecutions-6F3AA5PY.js")).getMultipleGitHubHistoryItems(e),...x}},[c.PACKAGE_SEARCH]:{isDefault:!0,isLocal:!1,type:"search",direct:{executionFn:async e=>(await import("./chunks/direct/execution-XA6PXPRB.js")).searchPackages(e),security:"remote",requiresServerRuntime:!0}},[c.GITHUB_CLONE_REPO]:{isDefault:!0,isLocal:!0,isClone:!0,type:"content",direct:{executionFn:async e=>(await import("./chunks/direct/execution-A4NK3BQO.js")).executeCloneRepo(e),timeoutMs:15e4,...x}},[C]:{isDefault:!0,isLocal:!0,type:"search",direct:{executionFn:async e=>(await import("./chunks/direct/execution-5O6QHKBR.js")).executeLocalSearch(e),security:"basic"}},[S]:{isDefault:!0,isLocal:!0,type:"search",direct:{executionFn:async e=>(await import("./chunks/direct/execution-X4MUJL4L.js")).executeAnalyzeGraph(e),security:"basic"}},[c.LOCAL_FETCH_CONTENT]:{isDefault:!0,isLocal:!0,type:"content",direct:{executionFn:async e=>(await import("./chunks/direct/execution-SWWZOOA7.js")).executeFetchContent(e),security:"basic"}},[y]:{isDefault:!0,isLocal:!0,type:"content",direct:{executionFn:async e=>(await import("./chunks/direct/execution-K4UOPXRQ.js")).executeLspGetSemantics(e),security:"basic",requiresServerRuntime:!0}}};function Tt(e){let t=ft[e.name];if(!t)throw new Error(`Missing runtime configuration for ${e.name}`);return{name:e.name,title:e.title,description:e.description,...t,direct:{schema:e.schema,inputSchema:e.inputSchema,...t.direct}}}function yt(){let e=new Map(R.map(b=>{let A=Tt(b);return[A.name,A]})),t=b=>{let A=e.get(b);if(!A)throw new Error(`Missing direct-tool specification for ${b}`);return A},o=t(O),r=t(c.GITHUB_FETCH_CONTENT),n=t(_),i=t(E),s=t(c.PACKAGE_SEARCH),a=t(c.GITHUB_CLONE_REPO),l=t(C),u=t(S),m=t(c.LOCAL_FETCH_CONTENT),Z=t(y),I=R.map(b=>t(b.name));return{GITHUB_SEARCH:o,GITHUB_FETCH_CONTENT:r,GITHUB_SEARCH_HISTORY:n,GITHUB_GET_HISTORY_ITEM:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_SEARCH:l,LOCAL_ANALYZE_GRAPH:u,LOCAL_FETCH_CONTENT:m,LSP_GET_SEMANTIC_CONTENT:Z,ALL_TOOLS:I}}var h=yt(),Qo=h.GITHUB_SEARCH,Jo=h.GITHUB_FETCH_CONTENT,Yo=h.GITHUB_SEARCH_HISTORY,Vo=h.GITHUB_GET_HISTORY_ITEM,Zo=h.PACKAGE_SEARCH,Ko=h.GITHUB_CLONE_REPO,Xo=h.LOCAL_SEARCH,Wo=h.LOCAL_ANALYZE_GRAPH,er=h.LOCAL_FETCH_CONTENT,tr=h.LSP_GET_SEMANTIC_CONTENT,Be=h.ALL_TOOLS;import{ContentSanitizer as gt}from"@octocodeai/octocode-engine/security";function ze(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,o=typeof t.message=="string"?t.message:ht(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",n=typeof t.code=="string"?t.code:void 0;return{name:r,message:o,code:n}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function ht(e){try{return JSON.stringify(e)}catch{return}}var St="[content withheld: sanitization failed \u2014 retry the call; if this persists, report it]";function $(e,t="full"){let o=t==="structured"&&e.structuredContent!=null&&!e.isError?{...e,content:[]}:e;if(o.structuredContent)try{o={...o,structuredContent:De(o.structuredContent)}}catch{o={...o,structuredContent:{results:[],status:"error",code:"SANITIZATION_FAILED",error:"structuredContent withheld: sanitization failed \u2014 retry the call; if this persists, report it"},isError:!0}}return o.content?.length&&(o={...o,content:o.content.map(r=>{if(r.type==="text"&&"text"in r&&typeof r.text=="string")try{let{content:n}=gt.sanitizeContent(r.text);return{...r,text:n}}catch{return{...r,text:St}}return r})}),o}var Ct="TOOL_CALLBACK_EXCEPTION";function Q(e,t){let o=ze(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
9
|
+
message: ${o.message}`}],structuredContent:{results:[],status:"error",tool:e,code:Ct,error:{name:o.name,message:o.message,code:o.code}},isError:!0};try{return $(r)}catch{return r}}import{withSecurityValidation as Ot,withBasicSecurityValidation as _t}from"@octocodeai/octocode-engine/security";function je(e,t,o){let r=Ot(e,(n,i)=>t(n,i),o);return(n,i)=>r(n,{authInfo:i?.http?.authInfo,sessionId:i?.sessionId,signal:i?.mcpReq.signal})}function ve(e,t,o){let r=_t((n,i)=>e(n,i),t,o);return(n,i)=>r(n,{signal:i?.mcpReq.signal})}var F=null,N=null,k=null,bt=be;function At(e){let t=e;return o=>t(o)}function Dt(e){let{direct:t}=e;return{name:e.name,title:e.title,description:e.description,schema:t.schema,inputSchema:t.inputSchema,execute:At(t.executionFn),security:t.security,isLocal:e.isLocal,isDefault:e.isDefault,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders,timeoutMs:t.timeoutMs}}var Rt=Be.map(Dt);function wt(e){return Rt.find(t=>t.name===e)}async function Lt(e,t,o){try{let r=wt(e);if(!r)throw new Error(`Unknown tool: ${e}`);let n=xt(r,t);return Ht(r),await It(r),await Ft(r,n,o?.resultProjection)}catch(r){return Q(e,r)}}function xt(e,t){let o=e.inputSchema.safeParse(t);if(!o.success)throw o.error;return o.data}async function It(e){e.requiresServerRuntime||(k||(k=Ee(_e()).then(()=>{}).catch(t=>{throw k=null,t})),await k),e.requiresServerRuntime&&(F||(F=bt().catch(t=>{throw F=null,t})),await F),e.requiresProviders&&(N||(N=Ae().then(()=>{}).catch(t=>{throw N=null,t})),await N)}function Ht(e){let t=Et(),o=t.tools.enabled??[],r=t.tools.disabled??[];if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}if(e.isClone&&!t.local.enableClone){let n=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true to use it.`);throw n.code="cloneDisabled",n}if(o.length>0&&!o.includes(e.name)){let n=new Error(`Tool "${e.name}" is outside the TOOLS_TO_RUN allowlist.`);throw n.code="toolNotEnabled",n}if(!e.isDefault&&!o.includes(e.name)){let n=new Error(`Tool "${e.name}" is opt-in. Add it to TOOLS_TO_RUN or .octocoderc tools.enabled.`);throw n.code="toolNotEnabled",n}if(o.length===0&&r.includes(e.name)){let n=new Error(`Tool "${e.name}" is disabled by DISABLE_TOOLS.`);throw n.code="toolDisabled",n}}async function Ft(e,t,o){try{let r=e.security==="remote"?await Nt(e,t):await kt(e,t);return $(r,o)}catch(r){return Q(e.name,r)}}async function Nt(e,t){return je(e.name,async(r,n)=>e.execute({...r,authInfo:n.authInfo,sessionId:n.sessionId,signal:n.signal}),{timeoutMs:e.timeoutMs})(t)}async function kt(e,t){return ve(e.execute,e.name,{timeoutMs:e.timeoutMs})(t)}import{z as Ue}from"zod";var Pt=["goal","reasoning"];function Gt(e){let t=p(e);if(!t)return"{}";try{return JSON.stringify(Ue.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Ue.toJSONSchema(t.schema,{io:"input"}),null,2)}}function qt(e){return JSON.stringify(e??{},null,2)}function Mt(e){return p(e)?[...Pt]:[]}function Bt(e,t){return p(e)?.description??e}import{z as Ye}from"zod";var zt={ghSearch:["Use only fields listed for the selected operation.","match: code=file|path; repositories=name|description|readme.","code cannot select branch; it searches GitHub's indexed default branch."],localSearch:["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."],localAnalyzeGraph:["dependencies | dependents -> requires file; depth applies.","path -> requires file + target.","deadCode/reachability use entrypoints and includeTests as roots."],localGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString."],lspGetSemantics:["workspaceSymbol needs symbolName and may use workspaceRoot.","documentSymbols/diagnostic need uri.","definition | references | hover | callers | callees | callHierarchy | implementation | typeDefinition | supertypes | subtypes -> requires uri + symbolName + lineHint."],ghGetFileContent:["Optionally choose fullContent, a line range, or matchString; extraction modes are exclusive.","A line range needs startLine and endLine.","matchString options apply with matchString.",'type:"directory" materializes; extraction fields read files.'],npmSearch:["Set exactly one non-empty packageName or keywords.","page applies only to keyword discovery."]};function J(e){return[...zt[e]??[]]}var jt={ghSearch:[{name:"code",when:"Search code contents or file paths",requires:["operation"],excludes:["branch"],fields:["keywords","owner","repo","extension","filename","path","language","match","pageSize","page","concise"],example:{operation:"code",keywords:["toolSchemas"],owner:"bgauryy",repo:"octocode"}},{name:"repositories",when:"Discover repositories",requires:["operation"],fields:["keywords","topics","language","owner","stars","forks","goodFirstIssues","updated","created","size","match","sort","pageSize","page","archived","visibility","license","concise"],example:{operation:"repositories",keywords:["octocode"]}},{name:"tree",when:"Browse a known repository tree",requires:["operation","owner","repo"],fields:["owner","repo","branch","path","maxDepth","page","pageSize","include"],example:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}],localSearch:[{name:"text",when:"Search lexical text or regular expressions",requires:["operation","path","searchText"],example:{operation:"text",path:".",searchText:"toolSchemas"}},{name:"structural",when:"Match AST structure",requires:["operation","path","pattern"],example:{operation:"structural",path:".",pattern:"console.log($A)",langType:"typescript"}},{name:"files",when:"Discover paths by name or metadata",requires:["operation","path"],example:{operation:"files",path:".",names:["*.ts"]}},{name:"tree",when:"Browse a directory tree",requires:["operation","path"],example:{operation:"tree",path:".",maxDepth:5}}],localAnalyzeGraph:[{name:"dependencies",when:"Find files imported by a file",requires:["path","operation","file"],example:{path:".",operation:"dependencies",file:"src/index.ts"}},{name:"dependents",when:"Find files importing a file",requires:["path","operation","file"],example:{path:".",operation:"dependents",file:"src/index.ts"}},{name:"path",when:"Find a shortest dependency path",requires:["path","operation","file","target"],example:{path:".",operation:"path",file:"src/a.ts",target:"src/b.ts"}},{name:"cycles",when:"Find dependency cycles",requires:["path","operation"],example:{path:".",operation:"cycles"}},{name:"deadCode",when:"Find unreachable file candidates",requires:["path","operation"],example:{path:".",operation:"deadCode"}},{name:"reachability",when:"Classify files from explicit or inferred roots",requires:["path","operation"],example:{path:".",operation:"reachability",entrypoints:["src/index.ts"]}}],lspGetSemantics:[{name:"anchored",when:"Query a named symbol near a source line",requires:["uri","type","symbolName","lineHint"],example:{uri:"src/index.ts",type:"definition",symbolName:"main",lineHint:1}},{name:"document",when:"Query a whole document",requires:["uri","type"],example:{uri:"src/index.ts",type:"documentSymbols"}},{name:"workspace",when:"Search symbols across the workspace",requires:["workspaceRoot","type","symbolName"],example:{workspaceRoot:".",type:"workspaceSymbol",symbolName:"Schema"}}]};function $e(e){return jt[e]??[]}import{z as vt}from"zod";function P(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qe(e){return P(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(P).flatMap(Qe)}function Ut(e){let t=p(e)?.schema;if(!t)return new Map;let o=vt.toJSONSchema(t),r=new Map;for(let n of Qe(o)){if(!P(n.properties))continue;let i=n.properties.operation;if(!P(i)||typeof i.const!="string")continue;let s=r.get(i.const)??new Set;for(let a of Object.keys(n.properties))["goal","reasoning","operation"].includes(a)||s.add(a);r.set(i.const,s)}return new Map([...r].map(([n,i])=>[n,[...i]]))}function Y(e){if(e==="ghSearch"){let[t,...o]=J(e);return[...t?[t]:[],"code and repositories need at least one search term or scope filter.",...o]}return e==="localSearch"?["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."]:e==="ghSearchHistory"?["Choose pullRequests, issues, or commits; fields cannot cross operations.","issues and commits require owner+repo; pullRequests may search globally.","Search/list operations reject exact identities, content, and diff pagination."]:e==="ghGetHistoryItem"?["Every operation requires owner+repo.","pullRequest and issue need number; commit needs ref; compare needs base+head.","Fields and pagination axes cannot cross operations."]:J(e)}function Je(e){let t=Ut(e);return(e==="ghSearchHistory"?[{name:"pullRequests",when:"Search or list pull requests",requires:["operation"],example:{operation:"pullRequests",keywords:["schema"]}},{name:"issues",when:"Search or list issues",requires:["operation","owner","repo"],example:{operation:"issues",owner:"o",repo:"r"}},{name:"commits",when:"List commit history",requires:["operation","owner","repo"],example:{operation:"commits",owner:"o",repo:"r"}}]:e==="ghGetHistoryItem"?[{name:"pullRequest",when:"Retrieve one pull request",requires:["operation","owner","repo","number"],example:{operation:"pullRequest",owner:"o",repo:"r",number:1}},{name:"issue",when:"Retrieve one issue",requires:["operation","owner","repo","number"],example:{operation:"issue",owner:"o",repo:"r",number:1}},{name:"commit",when:"Retrieve one commit",requires:["operation","owner","repo","ref"],example:{operation:"commit",owner:"o",repo:"r",ref:"main"}},{name:"compare",when:"Compare two refs",requires:["operation","owner","repo","base","head"],example:{operation:"compare",owner:"o",repo:"r",base:"main",head:"next"}}]:$e(e)).map(r=>({...r,...e==="localSearch"&&r.name==="structural"?{requires:["operation","path"]}:{},...e==="lspGetSemantics"&&r.name==="workspace"?{requires:["type","symbolName"]}:{},...t.has(r.name)?{fields:t.get(r.name)}:{}}))}function $t(e,t,o={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new f("Tool input must be valid JSON.")}return Ve(e,r,o)}function Ve(e,t,o={}){let r=Yt(e,t,o),n=p(e);if(!n)throw new f(`Unknown tool: ${e}`);let i=n.inputSchema.safeParse(r);if(!i.success)throw new f("Check the query fields.",[...Qt(e),...Jt(i.error)]);return i.data}function Qt(e){if(e==="npmSearch")return Y(e).slice(0,1);if(e==="localSearch"){let t=Je(e).map(o=>o.name);return t.length>0?[`operation must be one of ${t.map((o,r)=>r===t.length-1&&t.length>1?`or ${o}`:o).join(", ")}.`]:[]}if(e==="lspGetSemantics"){let t=Y(e);return t.length>0?[t.join(" ")]:[]}return[]}function Jt(e){let t=o=>{let r=o.errors;if(o.code!=="invalid_union"||!Array.isArray(r))return[o];let n=r.filter(s=>Array.isArray(s));return n.length===0?[o]:n.reduce((s,a)=>a.length<s.length?a:s).map(s=>({...s,path:[...o.path,...s.path]}))};return e.issues.flatMap(t).map(o=>`${o.path.length>0?o.path.join("."):"input"}: ${o.message}`)}function Yt(e,t,o){let r;if(Array.isArray(t))r=t;else if(T(t)&&Array.isArray(t.queries))r=t.queries;else if(T(t))r=[t];else throw new f('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new f("At least one query is required.");let n=T(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>Vt(e,eo(e,s,a,o),{sourceLabel:o.sourceLabel}));return{...n,queries:i}}function Vt(e,t,o){let r={...t},n=o.sourceLabel??"direct tool execution",i=Zt(e,n);return(typeof r.goal!="string"||r.goal.trim().length===0)&&(r.goal=i),(typeof r.reasoning!="string"||r.reasoning.trim().length===0)&&(r.reasoning=`Executed via ${n} tool command`),r}function Zt(e,t){return`Execute ${e} via ${t}`}function Kt(e,t){let o=e.length+1,r=t.length+1,n=Array.from({length:o*r},()=>0);for(let i=0;i<o;i++)n[i*r]=i;for(let i=0;i<r;i++)n[i]=i;for(let i=1;i<o;i++)for(let s=1;s<r;s++){let a=e[i-1]===t[s-1]?0:1;n[i*r+s]=Math.min(n[(i-1)*r+s]+1,n[i*r+s-1]+1,n[(i-1)*r+s-1]+a)}return n[o*r-1]}function Xt(e,t){let o=e.toLowerCase(),r,n=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let l=a.toLowerCase(),u=Kt(o,l);if(l.includes(o)||o.includes(l)){u<n&&(r=a,n=u);continue}if(o.length<3)continue;let m=Math.max(2,Math.floor(a.length/3));u<=m&&u<s&&(i=a,s=u)}return r??i}var Wt={npmSearch:{name:"packageName"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri",itemsPerPage:"pageSize",limit:""},localGetFileContent:{filePath:"path"},localSearch:{itemsPerPage:"pageSize",maxResults:["maxFiles","limit","pageSize"],keywords:"searchText",language:"langType",regexType:"regex",sortBy:"sort",sortReverse:"reverse"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:"minify"},ghSearch:{itemsPerPage:"pageSize",limit:"",topicsToSearch:"topics"},localAnalyzeGraph:{itemsPerPage:"pageSize",maxResults:"limit",maxDepth:"depth"}};function eo(e,t,o,r={}){if(!T(t))throw new f("Tool input must be a JSON object or an array of objects.");let n=new Set([...L(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Ze(p(e)?.schema),...w]),i={},s=[];for(let[a,l]of Object.entries(t)){if(n.has(a)){i[a]=l;continue}s.push(a)}if(s.length>0&&n.size>0&&(r.onUnknownFields?.(s,o),r.rejectUnknownFields===!0)){let a=ke(e,t),l=s.map(u=>{let m=Wt[e]?.[u],I=(Array.isArray(m)?m:m===void 0?[]:[m]).find(b=>a.has(b))??Xt(u,a);return I?`'${u}' \u2192 did you mean '${I}'?`:""}).filter(Boolean);throw new f(`Unknown field(s): ${s.join(", ")}`,[...l,`Remove unknown field(s) from query ${o+1}: ${s.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return i}function Ze(e){if(!e)return[];if(e instanceof Ye.ZodObject)return Object.keys(e.shape);let t=e.options,o=e instanceof Ye.ZodUnion?e.options:Array.isArray(t)?t:[];return o.length>0?[...new Set(o.flatMap(r=>Ze(r)))]:[]}import{SYSTEM_PROMPT as to}from"@octocodeai/octocode-core";var Ke={systemPrompt:to,toolNames:K,baseSchema:X,tools:Object.fromEntries(xe.map(e=>[e.name,{description:e.description}]))};var V=null;function oo(){return V||(V=Ke),V}async function ro(){return oo()}export{q as DIRECT_TOOL_CATEGORIES,B as DIRECT_TOOL_DEFINITIONS,f as DirectToolInputError,ct as buildDirectToolExampleQuery,Lt as executeDirectTool,p as findDirectToolDefinition,Xe as formatCallToolResultForOutput,qt as formatDirectToolMetadataSchemaText,Gt as formatDirectToolSchemaText,Mt as getDirectToolAutoFilledFields,M as getDirectToolCategory,Bt as getDirectToolDescription,L as getDirectToolDisplayFields,ro as loadToolContent,Ve as prepareDirectToolInput,$t as prepareDirectToolInputFromJsonText,ot as sortDirectToolNames};
|