@octocodeai/octocode-tools-core 16.2.0 → 16.5.1
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 +546 -0
- package/dist/config.d.ts +7 -0
- package/dist/direct.js +34 -41
- package/dist/errors/pathUtils.d.ts +1 -1
- package/dist/github/directoryFetch.d.ts +2 -1
- package/dist/github/githubAPI.d.ts +10 -1
- package/dist/github/repoStructureRecursive.d.ts +6 -0
- package/dist/index.d.ts +15 -27
- package/dist/index.js +41 -48
- package/dist/providers/providerQueries.d.ts +9 -0
- package/dist/providers/providerResults.d.ts +2 -0
- package/dist/scheme/coreSchemas.d.ts +5 -5
- package/dist/scheme/fields.d.ts +6 -6
- package/dist/serverConfig.d.ts +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/shared/config/defaults.d.ts +15 -0
- package/dist/shared/config/index.d.ts +10 -0
- package/dist/shared/config/index.js +10 -0
- package/dist/shared/config/loader.d.ts +7 -0
- package/dist/shared/config/resolver.d.ts +2 -0
- package/dist/shared/config/resolverCache.d.ts +12 -0
- package/dist/shared/config/resolverSections.d.ts +12 -0
- package/dist/shared/config/runtimeSurface.d.ts +21 -0
- package/dist/shared/config/schemas.d.ts +12 -0
- package/dist/shared/config/types.d.ts +100 -0
- package/dist/shared/config/validator.d.ts +2 -0
- package/dist/shared/credentials/constants.d.ts +2 -0
- package/dist/shared/credentials/credentialCache.d.ts +13 -0
- package/dist/shared/credentials/credentialEncryption.d.ts +10 -0
- package/dist/shared/credentials/credentialUtils.d.ts +4 -0
- package/dist/shared/credentials/envTokens.d.ts +9 -0
- package/dist/shared/credentials/ghCli.d.ts +1 -0
- package/dist/shared/credentials/index.d.ts +3 -0
- package/dist/shared/credentials/index.js +9 -0
- package/dist/shared/credentials/schemas.d.ts +22 -0
- package/dist/shared/credentials/storage.d.ts +30 -0
- package/dist/shared/credentials/testing.d.ts +2 -0
- package/dist/shared/credentials/testing.js +8 -0
- package/dist/shared/credentials/tokenRefresh.d.ts +24 -0
- package/dist/shared/credentials/tokenResolution.d.ts +30 -0
- package/dist/shared/credentials/types.d.ts +28 -0
- package/dist/shared/fs-utils.d.ts +2 -0
- package/dist/shared/fs-utils.js +8 -0
- package/dist/shared/index.d.ts +7 -0
- package/dist/shared/logger/index.d.ts +2 -0
- package/dist/shared/logger/logger.d.ts +17 -0
- package/dist/shared/paths.d.ts +33 -0
- package/dist/shared/paths.js +8 -0
- package/dist/shared/platform/index.d.ts +1 -0
- package/dist/shared/platform/index.js +8 -0
- package/dist/shared/platform/platform.d.ts +8 -0
- package/dist/shared/session/index.d.ts +5 -0
- package/dist/shared/session/index.js +9 -0
- package/dist/shared/session/schemas.d.ts +103 -0
- package/dist/shared/session/sessionCache.d.ts +9 -0
- package/dist/shared/session/sessionDiskIO.d.ts +6 -0
- package/dist/shared/session/statsDefaults.d.ts +4 -0
- package/dist/shared/session/storage.d.ts +20 -0
- package/dist/shared/session/types.d.ts +53 -0
- package/dist/tools/github_clone_repo/cache.d.ts +4 -0
- package/dist/tools/github_clone_repo/scheme.d.ts +56 -9
- package/dist/tools/github_clone_repo/types.d.ts +1 -1
- package/dist/tools/github_fetch_content/scheme.d.ts +8 -4
- package/dist/tools/github_fetch_content/types.d.ts +12 -0
- package/dist/tools/github_search_code/scheme.d.ts +6 -6
- package/dist/tools/github_search_pull_requests/contentResponse.d.ts +0 -1
- package/dist/tools/github_search_pull_requests/execution.d.ts +1 -11
- package/dist/tools/github_search_pull_requests/scheme.d.ts +6 -2
- package/dist/tools/github_search_repos/scheme.d.ts +7 -6
- package/dist/tools/github_view_repo_structure/execution.d.ts +0 -9
- package/dist/tools/github_view_repo_structure/scheme.d.ts +10 -6
- package/dist/tools/local_binary_inspect/archiveOps.d.ts +2 -0
- package/dist/tools/local_binary_inspect/binaryInspector.d.ts +48 -7
- package/dist/tools/local_binary_inspect/binaryOps.d.ts +16 -7
- package/dist/tools/local_binary_inspect/scheme.d.ts +10 -7
- package/dist/tools/local_fetch_content/scheme.d.ts +2 -2
- package/dist/tools/local_find_files/scheme.d.ts +2 -2
- package/dist/tools/local_ripgrep/lspBoost.d.ts +54 -0
- package/dist/tools/local_ripgrep/rankingProfile.d.ts +113 -0
- package/dist/tools/local_ripgrep/ripgrepResultBuilder.d.ts +10 -1
- package/dist/tools/local_ripgrep/scheme.d.ts +29 -4
- package/dist/tools/local_ripgrep/structuralSearch.d.ts +3 -4
- package/dist/tools/local_view_structure/scheme.d.ts +2 -2
- package/dist/tools/local_view_structure/structureFilters.d.ts +1 -3
- package/dist/tools/local_view_structure/structureResponse.d.ts +1 -0
- package/dist/tools/lsp/semantic_content/scheme.d.ts +4 -8
- package/dist/tools/lsp/shared/callHierarchyTraversal.d.ts +2 -2
- package/dist/tools/lsp/shared/semanticTypes.d.ts +2 -1
- package/dist/tools/package_search/scheme.d.ts +9 -7
- package/dist/tools/providerMappers.d.ts +19 -0
- package/dist/tools/toolMetadata/proxies.d.ts +0 -6
- package/dist/tools/utils.d.ts +3 -7
- package/dist/types/bulk.d.ts +0 -2
- package/dist/types/execution.d.ts +1 -2
- package/dist/types/toolResults.d.ts +2 -3
- package/dist/utils/contextUtils.d.ts +35 -2
- package/dist/utils/core/lines.d.ts +16 -0
- package/dist/utils/core/types.d.ts +10 -0
- package/dist/utils/file/filters.d.ts +2 -11
- package/dist/utils/parsers/diff.d.ts +18 -0
- package/dist/utils/ranking/evidenceRanker.d.ts +86 -0
- package/dist/utils/response/error.d.ts +38 -4
- package/dist/utils/response/groupedFinalizer.d.ts +0 -2
- package/package.json +43 -14
- package/dist/commands/RipgrepCommandBuilder.d.ts +0 -27
- package/dist/hints/dynamic.d.ts +0 -6
- package/dist/hints/index.d.ts +0 -2
- package/dist/hints/types.d.ts +0 -1
- package/dist/tools/github_clone_repo/hints.d.ts +0 -2
- package/dist/tools/github_fetch_content/hints.d.ts +0 -2
- package/dist/tools/github_search_code/hints.d.ts +0 -2
- package/dist/tools/github_search_pull_requests/hints.d.ts +0 -2
- package/dist/tools/github_search_repos/hints.d.ts +0 -2
- package/dist/tools/github_view_repo_structure/hints.d.ts +0 -2
- package/dist/tools/local_fetch_content/hints.d.ts +0 -2
- package/dist/tools/local_find_files/hints.d.ts +0 -2
- package/dist/tools/local_ripgrep/grepFallbackExecutor.d.ts +0 -3
- package/dist/tools/local_ripgrep/hints.d.ts +0 -2
- package/dist/tools/local_ripgrep/ripgrepParser.d.ts +0 -9
- package/dist/tools/local_view_structure/hints.d.ts +0 -2
- package/dist/tools/local_view_structure/structureParser.d.ts +0 -3
- package/dist/tools/local_view_structure/structureWalker.d.ts +0 -24
- package/dist/tools/lsp/semantic_content/hints.d.ts +0 -4
- package/dist/tools/package_search/hints.d.ts +0 -2
- package/dist/types/metadata.d.ts +0 -69
- package/dist/utils/exec/commandAvailability.d.ts +0 -19
- package/dist/utils/exec/ripgrepBinary.d.ts +0 -3
package/dist/index.js
CHANGED
|
@@ -5,60 +5,53 @@ 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
|
-
|
|
9
|
-
`)[0]??"").trim();if(r&&Ze(r))return r}}catch{}return null}function Vi(){let e=process.platform,t=process.arch;return e==="darwin"&&t==="arm64"?"darwin-arm64":e==="darwin"&&t==="x64"?"darwin-x64":e==="linux"&&t==="arm64"?"linux-arm64":e==="linux"&&t==="x64"?"linux-x64":e==="win32"&&t==="x64"?"windows-x64":null}var In=class extends Ln{constructor(){super(On()),this.addFlag("--no-config")}simple(t,n){return this.addFlag("-n"),this.addFlag("--column"),this.addFlag("-S"),this.addOption("--color","never"),this.addOption("--sort","path"),this.addArg("--"),this.addArg(t),this.addArg(n),this}filesOnly(){return this.addFlag("-l"),this}context(t){return this.addOption("-C",t),this}include(t){return this.addOption("-g",t),this}exclude(t){return this.addOption("-g",`!${t}`),this}excludeDir(t){return this.addOption("-g",`!${t}/`),this}type(t){return this.addOption("-t",t),this}fixedString(){return this.addFlag("-F"),this}perlRegex(){return this.addFlag("-P"),this}maxMatches(t){return this.addOption("-m",t),this}fromQuery(t){return this._applyMatchFlags(t),this._applyContextFlags(t),this.addFlag("-n"),this.addFlag("--column"),this._applyOutputModeFlags(t),this._applyFilterFlags(t),this._isPlainTextOutput(t)||this.addFlag("--json"),this._applyExecutionFlags(),this._applySortFlags(t),this._applyDiagnosticFlags(t),this.addArg("--"),this.addArg(t.keywords??""),this.addArg(t.path),this}_isPlainTextOutput(t){return!!(t.filesOnly||t.filesWithoutMatch||t.countLinesPerFile||t.countMatchesPerFile)}_applyMatchFlags(t){t.fixedString?this.addFlag("-F"):t.perlRegex&&this.addFlag("-P"),t.caseSensitive?this.addFlag("-s"):t.caseInsensitive?this.addFlag("-i"):this.addFlag("-S"),t.wholeWord&&this.addFlag("-w"),t.invertMatch&&this.addFlag("-v")}_applyContextFlags(t){t.contextLines!==void 0&&t.contextLines>0&&this.addOption("-C",t.contextLines)}_applyOutputModeFlags(t){t.filesOnly?this.addFlag("-l"):t.filesWithoutMatch?this.addFlag("--files-without-match"):t.countMatchesPerFile?this.addFlag("--count-matches"):t.countLinesPerFile&&this.addFlag("-c")}_applyFilterFlags(t){if(t.langType&&this.addOption("-t",t.langType),t.include&&t.include.length>0){let n=this._consolidateGlobs(t.include);for(let r of n)this.addOption("-g",r)}if(t.exclude&&t.exclude.length>0)for(let n of t.exclude)this.addOption("-g",`!${n}`);if(t.excludeDir&&t.excludeDir.length>0)for(let n of t.excludeDir)this.addOption("-g",`!${n}/`);t.noIgnore&&this.addFlag("--no-ignore"),t.hidden&&this.addFlag("--hidden"),t.multiline&&(this.addFlag("-U"),t.multilineDotall&&this.addFlag("--multiline-dotall"))}_applyExecutionFlags(){this.addOption("-j",4)}_applySortFlags(t){let n=t.sort||"path";t.sortReverse?(this.clearSortOption(),this.addOption("--sortr",n)):(this.clearSortrOption(),this.addOption("--sort",n))}_applyDiagnosticFlags(t){this.addOption("--color","never")}_consolidateGlobs(t){let n=/^\*\.([a-zA-Z0-9]+)$/,r=[],o=[];for(let s of t){let a=s.match(n);a&&a[1]?r.push(a[1]):o.push(s)}let i=[];return r.length>1?i.push(`*.{${r.join(",")}}`):r.length===1&&i.push(`*.${r[0]}`),i.push(...o),i}clearSortOption(){let t=this.args.indexOf("--sort");t!==-1&&t<this.args.length-1&&this.args.splice(t,2)}clearSortrOption(){let t=this.args.indexOf("--sortr");t!==-1&&t<this.args.length-1&&this.args.splice(t,2)}};var De=30,me=100,WC=10,KC=100,Wi=200,bt=20,Ki=100,Yi=20,kn=50,It=1e4,kt=20,vn=1e3,Xi=100,vt=5e4,Ji=8e3,Fn=1e5;var Qr={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},at={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"}},ct={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})`}},jd={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"}},Ae={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}`}},We={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"}},ne={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}`}},Vd={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}`}},lt={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Mn={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}`}},XC={...Qr,...at,...ct,...jd,...Ae,...We,...ne,...Vd,...lt,...Mn};var B={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"},Wd=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(Wd||{}),Zi={[B.PATH_VALIDATION_FAILED]:{code:B.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[B.FILE_ACCESS_FAILED]:{code:B.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[B.FILE_READ_FAILED]:{code:B.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[B.FILE_TOO_LARGE]:{code:B.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[B.BINARY_FILE_UNSUPPORTED]:{code:B.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[B.NO_MATCHES]:{code:B.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[B.OUTPUT_TOO_LARGE]:{code:B.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[B.COMMAND_NOT_AVAILABLE]:{code:B.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[B.COMMAND_EXECUTION_FAILED]:{code:B.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[B.COMMAND_TIMEOUT]:{code:B.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[B.TOOL_EXECUTION_FAILED]:{code:B.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"}};var Pe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Zi[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
|
|
10
|
-
Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function jr(e){return e instanceof Pe}function qi(e,t=B.TOOL_EXECUTION_FAILED,n){if(jr(e))return e;if(e instanceof Error)return new Pe(t,e.message,n,e);let r=String(e);return new Pe(t,r,n)}import{redactPath as nn}from"octocode-security/pathUtils";var Fe={pathValidationFailed:(e,t,n)=>new Pe(B.PATH_VALIDATION_FAILED,t||`Path validation failed: ${nn(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=nn(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Pe(B.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Pe(B.FILE_READ_FAILED,`Failed to read file: ${nn(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Pe(B.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Pe(B.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${nn(e)}`,{path:e}),outputTooLarge:(e,t)=>new Pe(B.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Pe(B.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 Pe(B.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Pe(B.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as ip}from"octokit";import{throttling as sp}from"@octokit/plugin-throttling";import{createHash as ap}from"crypto";import{resolveTokenFull as es,getConfigSync as ts,invalidateConfigCache as Yd}from"octocode-shared";var qe="16.2.0";import{maskSensitiveData as Xd}from"octocode-security/mask";var St=null,Ft=null,Vr=es;function mP(e){e.resolveTokenFull&&(Vr=e.resolveTokenFull)}function fP(){Vr=es}var Jd=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"]);async function Wr(){try{let e=await Vr({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:Jd.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function ns(){if(St!==null)return;if(Ft!==null)return Ft;let e=(async()=>{let t=ts(),n=await Wr();St={version:qe,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,loggingEnabled:t.telemetry.logging,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Ft=e;try{await e}catch(t){throw Ft===e&&(St=null,Ft=null),t}}function hP(){St=null,Ft=null,Yd()}function Nn(){if(!St){let e=Xd(Qr.NOT_INITIALIZED.message);throw new Error(e)}return St}async function rs(){return(await Wr()).token}function gP(){return Nn().enableLocal}function Hn(){let e=Nn();return e.enableLocal&&e.enableClone}function os(){return St?.loggingEnabled??!1}async function yP(){return(await Wr()).source}function rn(){return"github"}function Kr(){let e=ts().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{getOrCreateSession as ep,incrementToolCalls as tp,incrementErrors as np,incrementRateLimits as rp,incrementGitHubCacheRateLimits as op,updateSessionStats as ss}from"octocode-shared";import{completeMetadata as Zd}from"@octocodeai/octocode-core";var Re="lspGetSemantics",is=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation"];function Mt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Yr(e){return{uri:e.uri,...e.content!==void 0&&{content:e.content},...e.displayRange&&{displayRange:e.displayRange},...e.isDefinition&&{isDefinition:!0}}}var K=Zd.toolNames,qd=new Set([K.LOCAL_RIPGREP,K.LOCAL_FETCH_CONTENT,K.LOCAL_FIND_FILES,K.LOCAL_VIEW_STRUCTURE,K.LOCAL_BINARY_INSPECT,Re]);function Xr(e){return qd.has(e)}var Jr=class{session;logEndpoint="https://octocode-mcp-host.onrender.com/log";constructor(){this.session=ep()}getSessionId(){return this.session.sessionId}getSession(){return this.session}async logInit(){await this.sendLog("init",{})}async logToolCall(t,n,r,o,i){let s=tp(1);s.session&&(this.session=s.session);let a={tool_name:t,repos:Xr(t)?[]:n.map(()=>"[redacted]"),provider:Xr(t)?void 0:rn()};await this.sendLog("tool_call",a)}async logError(t,n){let r=np(1);r.session&&(this.session=r.session),await this.sendLog("error",{error:`${t}:${n}`})}async logRateLimit(t){let n=t.provider?ss({rateLimits:1,rateLimitsByProvider:{[t.provider]:1}}):rp(1);if(n.session&&(this.session=n.session),t.provider==="github"){let r=op(1);r.session&&(this.session=r.session)}await this.sendLog("rate_limit",t)}logPackageRegistryFailure(t){let n=ss({packageRegistryFailures:{[t]:1}});n.session&&(this.session=n.session)}async sendLog(t,n){if(!(t!=="init"&&!os()))try{let r={sessionId:this.session.sessionId,intent:t,data:n,timestamp:new Date().toISOString(),version:qe};await fetch(this.logEndpoint,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)})}catch{}}},on=null;function _P(){return on||(on=new Jr),on}function Nt(){return on}async function AP(){let e=Nt();e&&await e.logInit()}async function LP(e,t,n,r,o){let i=Nt();i&&await i.logToolCall(e,t,n,r,o)}async function OP(e){let t=Nt();t&&await t.logToolCall(e,[],void 0,void 0,void 0)}async function D(e,t){let n=Nt();n&&await n.logError(e,t)}async function ut(e){let t=Nt();t&&await t.logRateLimit(e)}function as(e){let t=Nt();t&&t.logPackageRegistryFailure(e)}function IP(){on=null}function cp(e){return ap("sha256").update(e).digest("hex").substring(0,16)}var lp=ip.plugin(sp),up=300*1e3,Zr=50,dp=60*1e3;function qr(e){return Date.now()-e.createdAt>up}var Ge=new Map,Ht=null,dt=null;function ms(){for(let[e,t]of Ge.entries())qr(t)&&Ge.delete(e);if(Ge.size>Zr){let e=[...Ge.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=Ge.size-Zr;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ge.delete(r[0])}}}function pp(){dt||(dt=setInterval(ms,dp),typeof dt=="object"&&"unref"in dt&&dt.unref())}var cs=3,ls=60;function us(e,t,n){ut({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var mp=()=>({onRateLimit:(e,t,n,r)=>(us("primary",e,t),r<cs&&e<ls),onSecondaryRateLimit:(e,t,n,r)=>(us("secondary",e,t),r<cs&&e<ls)});function ds(e){let t=Nn(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${qe}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:mp(),log:r,...e&&{auth:e}};return new lp(o)}async function re(e){if(pp(),e?.token){let n=cp(e.token),r=Ge.get(n);if(r&&!qr(r))return r.client;Ge.size>=Zr&&ms();let o=ds(e.token);return Ge.set(n,{client:o,createdAt:Date.now()}),o}let t=Ge.get("DEFAULT");return t&&!qr(t)?t.client:Ht||(Ht=(async()=>{try{let n=await rs(),r=ds(n??void 0);return Ge.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{Ht=null}})(),Ht)}var fp=200,Dt=new Map;async function $e(e,t,n){let r=`${e}/${t}`,o=Dt.get(r);if(o)return o;let i=await re(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return ps(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),ps(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function ps(e,t){if(Dt.size>=fp){let n=Dt.keys().next().value;n!==void 0&&Dt.delete(n)}Dt.set(e,t)}function $P(){Ge.clear(),Ht=null,Dt.clear(),dt&&(clearInterval(dt),dt=null)}import{ContentSanitizer as Zp}from"octocode-security/contentSanitizer";import{createRequire as hp}from"node:module";var gp=hp(import.meta.url),fs="@octocodeai/octocode-context-utils",Dn,yp=()=>gp(fs),eo=class extends Error{constructor(n){super(`Failed to load native dependency ${fs}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function ue(){if(Dn)return Dn;try{return Dn=yp(),Dn}catch(e){throw new eo(e)}}var z={applyContentViewMinification(e,t){return ue().applyContentViewMinification(e,t)},applyMinification(e,t){return ue().applyMinification(e,t)},minifyContent(e,t){return ue().minifyContent(e,t)},minifyContentSync(e,t){return ue().minifyContentSync(e,t)},minifyContentResult(e,t){return ue().minifyContentResult(e,t)},minifyMarkdownCore(e){return ue().minifyMarkdownCore(e)},extractSignatures(e,t){return ue().extractSignatures(e,t)},structuralSearch(e,t,n,r){return ue().structuralSearch(e,t,n,r)},getSemanticBoundaryOffsets(e,t){return ue().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ue().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ue().parseRipgrepJson(e,t)},queryFileSystem(e){return ue().queryFileSystem(e)},extractMatchingLines(e,t,n){return ue().extractMatchingLines(e,t,n)},filterPatch(e,t){return ue().filterPatch(e,t)},charToByteOffset(e,t){return ue().charToByteOffset(e,t)},byteToCharOffset(e,t){return ue().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ue().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ue().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ue().SIGNATURES_ONLY_HINT}};import{RequestError as gs}from"octokit";var j={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"},de={[j.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."},[j.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."},[j.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},[j.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)."},[j.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."},[j.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."},[j.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."},[j.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."},[j.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."},[j.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},hs={401:j.AUTH_REQUIRED,403:j.FORBIDDEN_PERMISSIONS,404:j.NOT_FOUND,422:j.INVALID_REQUEST,502:j.SERVER_UNAVAILABLE,503:j.SERVER_UNAVAILABLE,504:j.SERVER_UNAVAILABLE},to={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},no={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Gn={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var Rp=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function Ct(e){if(!(e instanceof gs)||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 Rp.some(o=>r.includes(o))})}function Z(e){return e instanceof gs?bp(e):e instanceof Error?_p(e):{error:typeof e=="string"?e:de[j.UNKNOWN].message,type:"unknown"}}function bp(e){let{status:t,message:n,response:r}=e;if(t===403)return Cp(n,r);if(t===429)return Sp(n,r);let o=hs[t];return o?xp(o,t):Gt(j.UNKNOWN,{error:n||de[j.UNKNOWN].message,status:t})}function ro(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function Sp(e,t){let n=t?.headers,r=ro(n,"retry-after"),o=ro(n,"x-ratelimit-reset"),i=ro(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Gn.RESET_BUFFER_SECONDS,0):void 0);return ut({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Gt(j.RATE_LIMIT_PRIMARY,{error:e||de[j.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:de[j.RATE_LIMIT_PRIMARY].suggestion})}function Cp(e,t){let n=t?.headers;if(no.SECONDARY.test(e))return Pp(n);let r=n?.["x-ratelimit-remaining"],o=wp(t);return r==="0"||o?Ep(n):Tp(n)}function Pp(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Gn.SECONDARY_FALLBACK_SECONDS:t;return ut({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Gt(j.RATE_LIMIT_SECONDARY,{error:de[j.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:de[j.RATE_LIMIT_SECONDARY].suggestion})}function Ep(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)+Gn.RESET_BUFFER_SECONDS,0):void 0,i=r?de[j.RATE_LIMIT_PRIMARY].messageWithTime(r,o):de[j.RATE_LIMIT_PRIMARY].messageWithoutTime;return ut({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Gt(j.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:de[j.RATE_LIMIT_PRIMARY].suggestion})}function Tp(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=de[j.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Ap(String(t),String(n))),Gt(j.FORBIDDEN_PERMISSIONS,{error:de[j.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function wp(e){return e?.data?.errors?.some(n=>n.type===no.GRAPHQL_TYPE)??!1}function xp(e,t){let n=de[e];return Gt(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function _p(e){return to.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:de[j.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:de[j.NETWORK_CONNECTION_FAILED].suggestion}:to.TIMEOUT.some(t=>e.message.includes(t))?{error:de[j.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:de[j.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Gt(e,t){return{type:"http",...t}}function Ap(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?de[j.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):de[j.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Lp(e){return`user:${e}`}var Op=/[@/]/,Ip=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,kp=/^[A-Za-z0-9_-]+$/;function ys(e){return e.startsWith('"')||kp.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var sn=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(Lp(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=Op.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},oo=class extends sn{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(ys))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Ip):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}},io=class extends sn{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(ys)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},so=class extends sn{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function Rs(e){return new oo().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function bs(e){return new io().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function Ss(e){return new so().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Cs(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import vp from"node-cache";import Fp from"crypto";import{incrementGitHubCacheHits as Mp}from"octocode-shared";var Np="v1",Hp=300*1e3,Ue=new vp({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),be={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Ps={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},$t=new Map;function Dp(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Gp(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function $p(e){let t=Dp(e);if(!(!t||!Gp(t)))try{Mp(t,1)}catch{}}function Up(){let e=Date.now();for(let[t,n]of $t.entries())e-n.startedAt>Hp&&$t.delete(t)}var Bp=new Set([]);function zp(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(Bp.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Ee(e,t,n){let r=ao(zp(t)),o=n?`${n}:${r}`:r,i=Fp.createHash("sha256").update(o).digest("hex");return`${Np}-${e}:${i}`}function ao(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=>ao(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${ao(i,t)}`}).join(",")}}`)}function Qp(e){return Ps[e]||Ps.default}function jp(e,t,n){try{return Ue.set(e,t,n),be.sets++,be.totalKeys=Ue.keys().length,!0}catch{try{let r=Ue.keys();for(let o of r)Ue.get(o);return Ue.set(e,t,n),be.sets++,be.totalKeys=Ue.keys().length,!0}catch{return!1}}}async function Te(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Ue.get(e);if(i!==void 0)return be.hits++,$p(e),i}catch{}Up();let r=$t.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||be.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Qp(l)}jp(e,i,a)}return i}finally{$t.delete(e)}})();return $t.set(e,{promise:o,startedAt:Date.now()}),o}function qP(){Ue.flushAll(),$t.clear(),be.hits=0,be.misses=0,be.sets=0,be.totalKeys=0,be.lastReset=new Date}function pt(e){let t=Ue.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Ue.del(r)>0&&n++}return n>0&&(be.totalKeys=Ue.keys().length),n}function eE(){return pt("local-")}function tE(){return pt("lsp-")}function nE(){let e=0;return e+=pt("gh-api-"),e+=pt("bb-api-"),e+=pt("gh-repo-"),e+=pt("bb-repo-"),e+=pt("github-user"),e+=pt("npm-search"),e}function rE(){let e=be.hits+be.misses;return{...be,hitRate:e>0?be.hits/e*100:0,cacheSize:Ue.keys().length}}var Es=[".github",".git",".vscode",".devcontainer",".config",".cargo",".changeset",".husky",".aspect",".eslint-plugin-local",".yarn",".gemini",".ng-dev",".configurations",".tx","dist","build","out","output","target","release","node_modules","vendor","third_party","tmp","temp","cache",".cache",".tmp",".pytest_cache",".tox",".venv",".mypy_cache",".next",".svelte-kit",".turbo",".angular",".dart_tool","__pycache__",".ruff_cache",".nox","htmlcov","cover",".gradle",".m2",".sbt",".bloop",".metals",".bsp","bin","obj","TestResults","BenchmarkDotNet.Artifacts",".vendor-new","Godeps","composer.phar",".phpunit.result.cache",".bundle",".byebug_history",".rspec_status",".mvn",".aws",".gcp","fastlane","DerivedData","xcuserdata","local.properties",".navigation","captures",".externalNativeBuild",".cxx",".idea",".idea_modules",".vs",".history","coverage",".nyc_output","logs","log",".DS_Store"],Vp=["package-lock.json",".secrets",".secret","secrets.json","secrets.yaml","secrets.yml","credentials.json","credentials.yaml","credentials.yml","auth.json","auth.yaml","auth.yml","api-keys.json","api_keys.json","service-account.json","service_account.json","private-key.pem","private_key.pem","id_rsa","id_dsa","id_ecdsa","id_ed25519","keyfile","keyfile.json","gcloud-service-key.json","firebase-adminsdk.json","google-services.json","GoogleService-Info.plist",".DS_Store","Thumbs.db","db.sqlite3","db.sqlite3-journal",".eslintcache",".stylelintcache",".node_repl_history",".yarn-integrity","celerybeat-schedule","celerybeat.pid","ThirdPartyNoticeText.txt","ThirdPartyNotices.txt","cglicenses.json","cgmanifest.json"],Wp=[".lock",".log",".tmp",".temp",".cache",".bak",".backup",".orig",".swp",".swo",".rej",".pid",".seed",".old",".save",".temporary",".exe",".dll",".so",".dylib",".a",".lib",".o",".obj",".bin",".class",".pdb",".dSYM",".pyc",".pyo",".pyd",".jar",".war",".ear",".nar",".db",".sqlite",".sqlite3",".mdb",".accdb",".zip",".tar",".gz",".bz2",".xz",".lz",".lzma",".Z",".tgz",".rar",".7z",".deb",".rpm",".pkg",".dmg",".msi",".appx",".snap",".map",".d.ts.map",".min.js",".min.css",".key",".pem",".p12",".pfx",".crt",".cer",".der",".csr",".jks",".keystore",".truststore",".kate-swp",".gnome-desktop",".sublime-project",".sublime-workspace",".iml",".iws",".ipr",".patch",".diff",".prof",".profile",".trace",".perf",".coverage",".egg-info",".egg",".mo",".pot",".setup",".paket.template"];function an(e){return Es.includes(e)}function Ut(e){let t=e.split("/").pop()||"";for(let r of Wp)if(t.endsWith(r))return!0;if(Vp.includes(t))return!0;let n=e.split("/");for(let r of n)if(Es.includes(r))return!0;return!1}function iE(e,t){let n=e.split(".");if(n.length<=1||n.length===2&&n[0]==="")return t?.fallback??"";let r=n[n.length-1];return t?.lowercase?r.toLowerCase():r}import{completeMetadata as co}from"@octocodeai/octocode-core";var S=new Proxy({},{get(e,t){return co.toolNames[t]},ownKeys(){return Object.keys(co.toolNames)},getOwnPropertyDescriptor(e,t){let n=co.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as Kp}from"@octocodeai/octocode-core";var lo=new Proxy({},{get(e,t){return Kp.tools[t]?.description??""}});import{completeMetadata as Yp}from"@octocodeai/octocode-core";function uo(e){return Object.prototype.hasOwnProperty.call(Yp.tools,e)}import{completeMetadata as Xp}from"@octocodeai/octocode-core";function po(){return Xp.baseSchema}var Jp=new Proxy({},{get(e,t){return po()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(po())]))},getOwnPropertyDescriptor(e,t){let n=po();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as et}from"@octocodeai/octocode-core";function Ts(e){return et.tools[e]?.hints??{hasResults:[],empty:[]}}var gE=new Proxy({},{get(e,t){if(typeof t=="string")return t==="base"?et.baseHints:Ts(t)},ownKeys(){return["base",...Object.keys(et.tools)]},getOwnPropertyDescriptor(e,t){if(typeof t=="string"&&(t==="base"||t in et.tools))return{enumerable:!0,configurable:!0,value:t==="base"?et.baseHints:Ts(t)}}}),yE=new Proxy([],{get(e,t){return et.genericErrorHints[t]}});function RE(e,t){return et.tools[e]?.hints?.[t]??[]}function bE(e,t){return et.tools[e]?.hints?.dynamic?.[t]??[]}function SE(){return et.genericErrorHints}var ws=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 xs(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function U(e,t){let n=typeof t=="number"?xs(t):G(t);if(n===void 0)return e;try{Object.defineProperty(e,ws,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ee(e){if(!(typeof e!="object"||e===null))return xs(e[ws])}function $n(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var _s=30;async function As(e,t,n){let r=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},n);return await Te(r,async()=>await qp(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function qp(e,t){try{let n=await re(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(y=>y&&y.trim()).length===0)return await D(S.GITHUB_SEARCH_CODE,ne.QUERY_EMPTY.code),{error:ne.QUERY_EMPTY.message,type:"http",status:400};let r=Rs(e);if(!r.trim())return await D(S.GITHUB_SEARCH_CODE,ne.QUERY_EMPTY.code),{error:ne.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:_s,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 em(a.data.items,a.data.total_count),l=c.total_count,d=Math.min(l,1e3),u=Math.min(Math.ceil(d/o),10),m=Math.min(i,Math.max(1,u)),p=m<u,f=Math.min(d,u*o);return{data:{total_count:c.total_count,items:c.items,repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:m,totalPages:u,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:f,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:p,uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:$n(a.headers),rawResponseChars:G(a.data)}}catch(n){if(Ct(n)){let o=Math.min(typeof e.limit=="number"?e.limit:_s,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}async function em(e,t){let n=tm(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Ut(p.path)),c=0,l=0,d=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],h=await Promise.allSettled((p.text_matches||[]).map(async T=>{let P=T.fragment,x=Zp.sanitizeContent(P||"",p.path);P=x.content,x.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${x.secretsDetected.join(", ")}`),x.warnings.length>0&&x.warnings.forEach(I=>r.add(`${p.path}: ${I}`));try{let I=await z.minifyContent(P||"",p.path);P=I.content,I.failed?o=!0:I.type!=="failed"&&(f.push(I.type),i.push(I.type))}catch{o=!0}return{context:P||"",positions:T.matches?.map(I=>Array.isArray(I.indices)&&I.indices.length>=2?[I.indices[0],I.indices[1]]:[0,0])||[]}})),y=h.filter(T=>T.status==="fulfilled").map(T=>T.value),b=h.filter(T=>T.status==="rejected").length;b>0&&(l+=b);let g=p,C=Array.from(new Set(f));return{path:p.path,matches:y,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...g.last_modified_at&&{lastModifiedAt:g.last_modified_at},...C.length>0&&{minificationType:C.join(",")}}})),u=d.filter(p=>p.status==="fulfilled").map(p=>p.value);c=d.filter(p=>p.status==="rejected").length;let m={items:u,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function tm(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}import{writeFileSync as Pm,mkdirSync as Fs,existsSync as Vn,rmSync as Em,readdirSync as Tm,statSync as wm}from"node:fs";import{join as ho,dirname as xm,resolve as Ms,sep as Ns}from"node:path";import{getOctocodeDir as _m}from"octocode-shared";import{existsSync as un,readFileSync as nm,writeFileSync as rm,mkdirSync as om,rmSync as ln,readdirSync as im,statSync as sm}from"node:fs";import{join as Ke}from"node:path";import{createHash as am}from"node:crypto";import{getDirectorySizeBytes as cm}from"octocode-shared";var lm=1440*60*1e3,um=600*1e3,dm=2*1024*1024*1024,pm=50,Os=".octocode-clone-meta.json",Bt=null;function Is(e){return Ke(e,"repos")}function mm(e){return e?`__sp_${am("sha256").update(e).digest("hex").substring(0,6)}`:""}function Un(e,t,n,r,o){let i=`${r}${mm(o)}`;return Ke(Is(e),t,n,i)}function fm(e){return typeof e=="object"&&e!==null}function hm(e){if(!fm(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),t}function mo(e){let t=Ke(e,Os);if(!un(t))return null;try{return hm(JSON.parse(nm(t,"utf-8")))}catch{return null}}function Bn(e,t){try{rm(Ke(e,Os),JSON.stringify(t,null,2),"utf-8")}catch{}}function ks(e){return Date.now()<new Date(e.expiresAt).getTime()}function zn(e){let t=mo(e);return t?ks(t)?un(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function gm(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return lm}function ym(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return dm}function Rm(){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 pm}function Qn(e,t,n,r,o,i){let s=new Date;return{clonedAt:s.toISOString(),expiresAt:new Date(s.getTime()+gm()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{}}}function jn(e){let t=Ke(e,"..");try{un(t)||om(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 fo(e){try{un(e)&&ln(e,{recursive:!0,force:!0})}catch{}}function cn(e){try{return sm(e).isDirectory()}catch{return!1}}function Pt(e){try{return im(e)}catch{return[]}}function*vs(e){for(let t of Pt(e)){let n=Ke(e,t);if(cn(n))for(let r of Pt(n)){let o=Ke(n,r);if(cn(o))for(let i of Pt(o)){let s=Ke(o,i);cn(s)&&(yield s)}}}}function Ls(e){for(let t of[...Pt(e)]){let n=Ke(e,t);if(cn(n)){for(let r of[...Pt(n)]){let o=Ke(n,r);if(cn(o)&&Pt(o).length===0)try{ln(o,{recursive:!0,force:!0})}catch{}}if(Pt(n).length===0)try{ln(n,{recursive:!0,force:!0})}catch{}}}}function bm(e){let t=0;for(let n of vs(e))try{let r=mo(n);(!r||!ks(r))&&(ln(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Sm(e){let t=[];for(let n of vs(e)){let r=mo(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??cm(n)})}return t}function Cm(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{ln(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function zt(e){let t=Is(e);if(!un(t))return 0;let n=0;try{n+=bm(t)}catch{return n}Ls(t);let r=Cm(Sm(t),ym(),Rm());return n+=r,r>0&&Ls(t),n}function VE(e){Bt||(zt(e),Bt=setInterval(()=>{zt(e)},um),Bt.unref())}function WE(){Bt&&(clearInterval(Bt),Bt=null)}var Am=50,Lm=5*1024*1024,Om=300*1024,Im=5,km=1e4,vm=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".eot",".otf",".pyc",".class",".o",".obj",".lock",".min.js",".min.css"]);async function Ds(e,t,n,r,o,i=!1){let s=_m(),a=Un(s,e,t,r),c=Ms(ho(a,n));if(!c.startsWith(a+Ns)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=zn(a);if(l.hit){if(l.meta.source==="clone"){if(Vn(c)){let T=Hs(c,a);return{localPath:c,files:T.files,fileCount:T.fileCount,totalSize:T.totalSize,cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}throw new Error(`Path "${n}" not found in the cloned repository (${e}/${t}@${r}). To refresh the clone, use ghCloneRepo with forceRefresh: true.`)}if(!i&&Vn(c)){let T=Hs(c,a);return{localPath:c,files:T.files,fileCount:T.fileCount,totalSize:T.totalSize,cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}}let d=await re(o),{data:u}=await d.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(u))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let m=u.filter(C=>{if(C.type!=="file"||!C.download_url||C.size>Om)return!1;let T=Hm(C.name);return!vm.has(T)}).slice(0,Am),p=o?.token,f=await Fm(m,Im,p),h=0,y=[];for(let{entry:C,content:T}of f){if(h+T.length>Lm)break;h+=T.length,y.push({entry:C,content:T})}zt(s),jn(a),Vn(c)&&Em(c,{recursive:!0,force:!0}),Fs(c,{recursive:!0,mode:448});let b=[];for(let{entry:C,content:T}of y){let P=Ms(ho(a,C.path));if(!P.startsWith(a+Ns))continue;let x=xm(P);Vn(x)||Fs(x,{recursive:!0,mode:448}),Pm(P,T,"utf-8"),b.push({path:C.path,size:T.length,type:"file"})}let g=Qn(e,t,r,"directoryFetch");return Bn(a,g),{localPath:c,files:b,fileCount:b.length,totalSize:h,cached:!1,expiresAt:g.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function Fm(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 Nm(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var Mm=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function Nm(e,t){try{let o=new URL(e);if(!Mm.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(),km);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 Hs(e,t){let n=[],r=0;function o(i){let s;try{s=Tm(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=ho(i,a);try{let l=wm(c);if(l.isDirectory())o(c);else if(l.isFile()){let d=c.substring(t.length+1);r+=l.size,n.push({path:d,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function Hm(e){let t=e.lastIndexOf(".");return t===-1?"":e.substring(t).toLowerCase()}import{RequestError as Gs}from"octokit";async function Dm(e,t,n,r,o,i,s,a){let c=await $e(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let d=Z(t),u=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await Qs(e,r,o,i,s||c);return m.length>0&&(d.hints=[...d.hints||[],...zs(i,m)]),{...d,...u&&{scopesSuggestion:u}}}async function Gm(e,t,n,r,o,i){let s=Z(t),a=await Qs(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...zs(o,a)]),s}async function $s(e,t){let n=e.replace(/\s/g,"");if(!n)return await D(S.GITHUB_FETCH_CONTENT,Ae.FILE_EMPTY.code),{error:Ae.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?(await D(S.GITHUB_FETCH_CONTENT,Ae.BINARY_FILE.code),{error:Ae.BINARY_FILE.message,type:"unknown",status:415}):{data:r.toString("utf-8"),status:200}}catch{return await D(S.GITHUB_FETCH_CONTENT,Ae.DECODE_FAILED.code),{error:Ae.DECODE_FAILED.message,type:"unknown",status:422}}}async function Us(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"?$s(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return Z(i)}}async function $m(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 $e(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let d=l.data.find(m=>m.name===a&&m.type==="file");if(!d)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let u=await Us(e,t,n,d.sha,r);return"error"in u?u:{data:{rawContent:u.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return Z(s)}}async function Bs(e,t){try{let n=await re(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(u){if(u instanceof Gs&&u.status===404)if(s){let m=await Dm(n,u,a,r,o,i,s,t);if("result"in m)c=m.result,l=m.actualBranch;else return m}else return await Gm(n,u,r,o,i,s);else{if(u instanceof Gs&&u.status===413)return await $m(n,r,o,i,s||l,t);throw u}}let d=c.data;if(Array.isArray(d))return await D(S.GITHUB_FETCH_CONTENT,Ae.PATH_IS_DIRECTORY.code),{error:Ae.PATH_IS_DIRECTORY.message(S.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let u=typeof d.content=="string"?d.content:"",m=d.size??0,p;if(u.length>0)p=await $s(u,i);else if(m>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)p=await Us(n,r,o,d.sha,i);else return await D(S.GITHUB_FETCH_CONTENT,Ae.FILE_EMPTY.code),{error:Ae.FILE_EMPTY.message,type:"unknown",status:404};if("error"in p)return p;if(!l&&!s)try{l=await $e(r,o,t)}catch{}return{data:{rawContent:p.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:G(d)}}return await D(S.GITHUB_FETCH_CONTENT,Ae.UNSUPPORTED_TYPE.code),{error:Ae.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(n){return Z(n)}}function zs(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Qs(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],d=c.find(p=>p.name.toLowerCase()===s.toLowerCase());d&&l.push(d.path);let u=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(u+".")).forEach(p=>l.push(p.path)),l.length===0&&u.length>=3&&c.filter(f=>{let h=f.name.replace(/\.[^/.]+$/,"");return h!==u&&h.length>=3&&(u.startsWith(h)||h.startsWith(u))}).forEach(f=>l.push(f.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}import{getConfigSync as Um}from"octocode-shared";import{DEFAULT_OUTPUT_CONFIG as Bm}from"octocode-shared";function we(){try{return Um().output.pagination.defaultCharLength}catch{return Bm.pagination.defaultCharLength}}var js=1e5;function Vs(e){let t=Math.min(Math.max(we(),1),js),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,js)}import{ContentSanitizer as Xs}from"octocode-security/contentSanitizer";function zm(e,t,n){return z.byteSliceContent(e,t,n)}function Wn(e,t){return z.byteToCharOffset(e,t)}function Ws(e,t){return z.charToByteOffset(e,t)}function Ks(e){return z.charToByteOffset(e,e.length)}function fT(e,t,n){let r=zm(e,t,t+n);return{charOffset:Wn(e,t),charLength:r.length,text:r}}function go(e,t,n,r){return z.sliceContent(e,t,n,r)}function tt(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Ks(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,d,u,m,p,f,h;if(o==="bytes"){let y=Math.min(t,s),b=Math.min(y+n,s);u=Wn(e,y),m=Wn(e,b),m<i&&Ws(e,m)<b&&(m+=1);let g=go(e,u,m-u);c=g.text,u=g.charOffset,m=g.charOffset+g.charLength,l=g.byteOffset,d=g.byteOffset+g.byteLength,p=d<s;let C=r.actualOffset??y;f=Math.floor(C/a)+1,h=Math.max(f,Math.ceil(s/a))}else{let y=go(e,t,n);c=y.text,u=y.charOffset,m=y.charOffset+y.charLength,l=y.byteOffset,d=y.byteOffset+y.byteLength,p=m<i;let b=r.actualOffset??u;f=Math.floor(b/a)+1,h=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:d-l,totalBytes:s,nextByteOffset:p?d:void 0,charOffset:u,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:h}}function yT(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function dn(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}}}function RT(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
|
|
11
|
-
`){let l=e.lastIndexOf(`
|
|
12
|
-
|
|
13
|
-
`,
|
|
14
|
-
`,
|
|
15
|
-
|
|
16
|
-
`)
|
|
17
|
-
`).length,...
|
|
18
|
-
`),P
|
|
19
|
-
`);let
|
|
20
|
-
`),
|
|
8
|
+
import{withSecurityValidation as Gm,withBasicSecurityValidation as Um}from"@octocodeai/octocode-engine/security";function Qa(e,t){let n=Gm(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function ja(e,t){let n=Um(r=>e(r),t);return(r,o)=>n(r,o)}var $a=class{command;args=[];constructor(t){this.command=t}addFlag(t){return this.args.push(t),this}addOption(t,n){return this.args.push(t,String(n)),this}addArg(t){return this.args.push(t),this}build(){return{command:this.command,args:[...this.args]}}reset(){return this.args=[],this}getArgs(){return[...this.args]}};var Be=30,pe=100,Gx=10,Ux=100,Va=200,Mt=20,Wa=100,Ka=20,Hr=50,tn=1e4,nn=20,Gr=1e3,Ya=100,rn=5e4,Xa=8e3,Ur=1e5,Ja=500;var hi={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},bt={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"}},St={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})`}},Bm={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"}},Oe={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}`}},et={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"}},oe={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}`}},zm={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}`}},Ct={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Br={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}`}},zx={...hi,...bt,...St,...Bm,...Oe,...et,...oe,...zm,...Ct,...Br};var H={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"},Qm=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(Qm||{}),Za={[H.PATH_VALIDATION_FAILED]:{code:H.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[H.FILE_ACCESS_FAILED]:{code:H.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[H.FILE_READ_FAILED]:{code:H.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[H.FILE_TOO_LARGE]:{code:H.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[H.BINARY_FILE_UNSUPPORTED]:{code:H.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[H.NO_MATCHES]:{code:H.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[H.OUTPUT_TOO_LARGE]:{code:H.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[H.COMMAND_NOT_AVAILABLE]:{code:H.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[H.COMMAND_EXECUTION_FAILED]:{code:H.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[H.COMMAND_TIMEOUT]:{code:H.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[H.TOOL_EXECUTION_FAILED]:{code:H.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"}};var Te=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Za[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}
|
|
9
|
+
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 yi(e){return e instanceof Te}function qa(e,t=H.TOOL_EXECUTION_FAILED,n){if(yi(e))return e;if(e instanceof Error)return new Te(t,e.message,n,e);let r=String(e);return new Te(t,r,n)}import{redactPath as Nn}from"@octocodeai/octocode-engine/pathUtils";var De={pathValidationFailed:(e,t,n)=>new Te(H.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Nn(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Nn(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Te(H.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Te(H.FILE_READ_FAILED,`Failed to read file: ${Nn(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Te(H.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Te(H.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Nn(e)}`,{path:e}),outputTooLarge:(e,t)=>new Te(H.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Te(H.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 Te(H.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Te(H.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as oh}from"octokit";import{throttling as ih}from"@octokit/plugin-throttling";import{createHash as sh}from"crypto";var Ri=null;function jm(e){let t=`[${e.module}]`,n=e.data&&Object.keys(e.data).length>0?` ${JSON.stringify(e.data)}`:"";process.stderr.write(`${t} ${e.level}: ${e.message}${n}
|
|
10
|
+
`)}function ec(e){Ri=e}function tc(){return Ri}function tt(e){function t(n,r,o){let i={level:n,module:e,message:r,...o&&{data:o}};(Ri??jm)(i)}return{debug:(n,r)=>t("debug",n,r),info:(n,r)=>t("info",n,r),warn:(n,r)=>t("warn",n,r),error:(n,r)=>t("error",n,r)}}function nt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function ct(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 Dn(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Hn=new Map,$m=300*1e3;function Vm(e){let t=nt(e),n=Hn.get(t);return!n||Date.now()-n.cachedAt>=$m?!1:n.credentials?!ct(n.credentials):!0}function Gn(e){e?Hn.delete(nt(e)):Hn.clear()}function nc(e){let t=nt(e);if(Vm(t))return Hn.get(t).credentials}function rc(e,t){let n=nt(e);Hn.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as Qr,readFileSync as fc,writeFileSync as mc,unlinkSync as dc,statSync as tg,chmodSync as ng}from"node:fs";import{createCipheriv as rg,createDecipheriv as og,randomBytes as gc}from"node:crypto";import{existsSync as Dt,mkdirSync as Ht}from"node:fs";import{join as fe}from"node:path";import on from"node:os";import oc from"node:path";var Nt=on.platform()==="win32",Un=on.platform()==="darwin",bi=on.platform()==="linux",ut=on.homedir();function zr(){return Nt?process.env.APPDATA||oc.join(ut,"AppData","Roaming"):ut}function ic(){return Nt?process.env.LOCALAPPDATA||oc.join(ut,"AppData","Local"):ut}function sc(){return Un?"macOS":Nt?"Windows":bi?"Linux":on.platform()}function ac(){return on.arch()}var Si=".octocode",Gt=448;function Wm(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function cc(){return Nt?fe(zr(),Si):Un?fe(ut,Si):fe(Wm("XDG_CONFIG_HOME")??fe(ut,".config"),Si)}var be=cc(),W={home:be,config:fe(be,".octocoderc"),credentials:fe(be,"credentials.json"),key:fe(be,".key"),session:fe(be,"session.json"),stats:fe(be,"stats.json"),tmp:fe(be,"tmp"),clone:fe(be,"tmp","clone"),tree:fe(be,"tmp","tree"),binary:fe(be,"tmp","binary"),repos:fe(be,"tmp","clone"),logs:fe(be,"logs"),unzip:fe(be,"tmp","unzip"),cliConfig:fe(be,"config.json"),lspConfig:fe(be,"lsp-servers.json")};function Bn(){Dt(W.home)||Ht(W.home,{recursive:!0,mode:Gt})}function Km(){uc()}function zn(){Bn(),Dt(W.tmp)||Ht(W.tmp,{recursive:!0,mode:Gt})}function uc(){zn(),Dt(W.clone)||Ht(W.clone,{recursive:!0,mode:Gt})}function Ym(){Bn(),Dt(W.logs)||Ht(W.logs,{recursive:!0,mode:Gt})}function Xm(){zn(),Dt(W.tree)||Ht(W.tree,{recursive:!0,mode:Gt})}function Jm(){zn(),Dt(W.binary)||Ht(W.binary,{recursive:!0,mode:Gt})}function Zm(){zn(),Dt(W.unzip)||Ht(W.unzip,{recursive:!0,mode:Gt})}import{z as me}from"zod";var qm=me.object({token:me.string(),tokenType:me.literal("oauth"),scopes:me.array(me.string()).optional(),refreshToken:me.string().optional(),expiresAt:me.string().optional(),refreshTokenExpiresAt:me.string().optional()}),eg=me.object({hostname:me.string(),username:me.string(),token:qm,gitProtocol:me.enum(["ssh","https"]),createdAt:me.string(),updatedAt:me.string()}),lc=me.object({version:me.number(),credentials:me.record(me.string(),eg)});var pc=tt("token-storage");function ig(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***")}var Ci=W.home,Ye=W.credentials,rt=W.key,hc="aes-256-gcm",sg=16;function Pt(){Bn()}function yc(){if(Pt(),Qr(rt))return tg(rt).mode&511&63&&ng(rt,384),Buffer.from(fc(rt,"utf8"),"hex");let e=gc(32);return mc(rt,e.toString("hex"),{mode:384}),e}function jr(e){let t=yc(),n=gc(sg),r=rg(hc,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 $r(e){let t=yc(),[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=og(hc,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function lt(){if(Pt(),!Qr(Ye))return{version:1,credentials:{}};try{let e=fc(Ye,"utf8"),t=$r(e),n=JSON.parse(t),r=lc.safeParse(n);return r.success?r.data:(pc.warn("Credentials file has invalid format \u2014 starting fresh",{file:Ye}),{version:1,credentials:{}})}catch(e){let t=e instanceof Error&&e.message?ig(e.message):void 0;return pc.warn("Could not read credentials file \u2014 you may need to login again",{file:Ye,...t&&{reason:t}}),{version:1,credentials:{}}}}function Pi(e){Pt();let t=jr(JSON.stringify(e,null,2));mc(Ye,t,{mode:384})}function Rc(){try{Qr(Ye)&&dc(Ye),Qr(rt)&&dc(rt)}catch{}}import{refreshToken as ag}from"@octokit/oauth-methods";import{request as cg}from"@octokit/request";var sn="178c6fc778ccc68e1d6a",Et="github.com";function ug(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 lg(e){return e==="github.com"||e===Et?"https://api.github.com":`https://${e}/api/v3`}async function Ei(e,t=Et,n=sn){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(Dn(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await ag({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:cg.defaults({baseUrl:lg(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?ug(o.message):"Token refresh failed"}}}async function bc(e,t=Et,n=sn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!ct(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Ei(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var an=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN"];function Vr(){for(let e of an){let t=process.env[e];if(t&&t.trim())return t.trim()}return null}function Ti(){for(let e of an){let t=process.env[e];if(t&&t.trim())return`env:${e}`}return null}function xi(){return Vr()!==null}function Sc(){for(let e of an){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}import{execFile as dg}from"child_process";var pg=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Wr(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=pg.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;dg("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Kr=null;function Cc(e){Kr=e}function _i(){Kr=null}function fg(){if(!Kr)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Kr}async function Tt(e){let t=e?.hostname??Et,n=e?.clientId??sn,r=e?.getGhCliToken??Wr,o=Sc();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await fg().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{}return null}async function wi(e=Et){let t=await Tt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Ai(e=Et,t=sn){let n=await Tt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var mg=tt("token-storage");async function Li(e){let t=nt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=lt();return r.credentials[t]=n,Pi(r),Gn(t),{success:!0}}catch(r){let o=r instanceof Error?r.message:String(r);throw mg.error("CRITICAL: Storage failed",{error:o.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***")}),new Error("Failed to store credentials")}}async function Ut(e="github.com",t){let n=nt(e);if(!t?.bypassCache){let i=nc(n);if(i!==void 0)return i}let o=lt().credentials[n]||null;return rc(n,o),o}function Yr(e="github.com"){let t=nt(e);return lt().credentials[t]||null}async function Pc(e="github.com"){let t=nt(e),n=!1,r=lt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Rc():Pi(r),n=!0),Gn(t),{success:n,deletedFromFile:n}}async function Ec(){let e=lt();return Object.keys(e.credentials)}function Tc(){let e=lt();return Object.keys(e.credentials)}async function xc(e="github.com"){return await Ut(e)!==null}function _c(e="github.com"){return Yr(e)!==null}async function Xr(e,t){let n=await Ut(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Li(n),!0):!1}function wc(){return Ye}async function Ac(e="github.com"){let t=await Ut(e);return!t||!t.token||ct(t)?null:t.token.token}function Lc(e="github.com"){let t=Yr(e);return!t||!t.token||ct(t)?null:t.token.token}async function Oc(e,t){return Ei({getCredentials:Ut,updateToken:Xr},e,t)}async function Oi(e,t){return bc({getCredentials:Ut,updateToken:Xr},e,t)}Cc({getTokenWithRefresh:Oi});import{randomUUID as Ag}from"node:crypto";import{existsSync as Ii,readFileSync as Mc,writeFileSync as bg,unlinkSync as Sg,renameSync as Cg}from"node:fs";import{z}from"zod";var gg=z.object({rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),calls:z.number()}),hg=z.object({hits:z.record(z.string(),z.number()).default({}),rateLimits:z.number().default(0)}),Jr=z.record(z.string(),z.number()).default({}),yg=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:Jr,rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),charSavingsCalls:z.number(),githubCacheHits:z.number(),githubCacheRateLimits:z.number(),packageRegistryFailures:z.number().default(0),packageRegistryFailuresByRegistry:Jr}),Zr=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:Jr,charsSavedByTool:z.record(z.string(),gg).default({}),githubCacheHits:hg.default({hits:{},rateLimits:0}),packageRegistryFailures:Jr,totalUsage:yg.optional()}),Ic=z.object({version:z.literal(1),sessionId:z.string(),createdAt:z.string(),lastActiveAt:z.string(),stats:Zr.optional()}),kc=z.object({version:z.literal(1),stats:Zr});function vc(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Rg(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:vc(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:vc(o),packageRegistryFailuresByRegistry:o}}function dt(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Rg(t)}}function Qn(){return dt({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Nc=tt("session"),xt=W.session,_t=W.stats;function Fc(e,t){let n=`${e}.tmp`;bg(n,JSON.stringify(t,null,2),{mode:384}),Cg(n,e)}function Pg(e){let{stats:t,...n}=e;return n}function Eg(e){let t=JSON.parse(e),n=kc.safeParse(t);if(n.success)return dt(n.data.stats);let r=Zr.safeParse(t);return r.success?dt(r.data):null}function Tg(e){let t=e?dt(e):Qn();if(!Ii(_t))return t;try{let n=Mc(_t,"utf8"),r=Eg(n);return r||(Nc.warn("Stats file has invalid format",{file:_t}),t)}catch{return t}}function qr(e){Pt(),Fc(_t,{version:e.version,stats:dt(e.stats)}),Fc(xt,Pg(e))}function Dc(){if(!Ii(xt))return null;try{let e=Mc(xt,"utf8"),t=JSON.parse(e),n=Ic.safeParse(t);return n.success?{...n.data,stats:Tg(n.data.stats)}:(Nc.warn("Session file has invalid format",{file:xt}),null)}catch{return null}}function Hc(){let e=!1;for(let t of[xt,_t])if(Ii(t))try{Sg(t),e=!0}catch{return!1}return e}var xg=6e4,Xe=null,wt=!1,cn=null,ki=!1,jn=null,$n=null,Vn=null,eo=!1;function _g(){ki||(ki=!0,jn=()=>{Wn()},$n=()=>{Wn()},Vn=()=>{Wn()},process.on("exit",jn),process.on("SIGINT",$n),process.on("SIGTERM",Vn))}function vi(){jn&&(process.removeListener("exit",jn),jn=null),$n&&(process.removeListener("SIGINT",$n),$n=null),Vn&&(process.removeListener("SIGTERM",Vn),Vn=null),ki=!1}function wg(){cn||(cn=setInterval(()=>{wt&&Xe&&(qr(Xe),wt=!1)},xg),cn.unref())}function Fi(){cn&&(clearInterval(cn),cn=null)}function Kn(){if(Xe)return Xe;let e=Dc();return e&&(Xe=e),e}function un(e){Xe=e,wt=!0,_g(),wg()}function Yn(){wt&&Xe&&(qr(Xe),wt=!1)}function Wn(){if(!eo&&wt&&Xe){eo=!0;try{qr(Xe),wt=!1}catch{}finally{eo=!1}}}function Mi(){Xe=null,wt=!1,eo=!1}function Gc(){Mi(),Fi(),vi()}var Lg=1;function Og(e){return dt(e)}function Ig(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 Uc(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 kg(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 Bc(){let e=new Date().toISOString();return{version:Lg,sessionId:Ag(),createdAt:e,lastActiveAt:e,stats:Qn()}}function zc(){Yn()}function Qc(){Wn()}function to(e){if(e?.forceNew){let r=Bc();return un(r),Yn(),r}let t=Kn();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return un(r),Yn(),r}let n=Bc();return un(n),Yn(),n}function jc(){return Kn()?.sessionId??null}function He(e){let t=Kn();if(!t)return{success:!1,session:null};let n=Og(t.stats),r=dt({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Uc(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Ig(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:kg(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Uc(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return un(o),{success:!0,session:o}}function no(e=1){return He({toolCalls:e})}function ro(e=1){return He({errors:e})}function oo(e=1){return He({rateLimits:e})}function $c(e,t=1){return He({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function io(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return He({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function so(e,t=1){return He({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ao(e=1){return He({githubCacheHits:{hits:{},rateLimits:e}})}function Vc(e,t=1){return He({packageRegistryFailures:{[e]:t}})}function Wc(){let e=Kn();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Qn()};return un(t),{success:!0,session:t}}function Kc(){return Mi(),Fi(),vi(),Hc()}function Yc(){Gc()}var Xn=1,Xc=".octocoderc";var Jn={apiUrl:"https://api.github.com"},At={enabled:!1,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},Bt={enabled:null,enableAdditional:null,disabled:null},ln={timeout:3e4,maxRetries:3},Zn={logging:!0},qn={configPath:void 0},pt={format:"yaml",pagination:{defaultCharLength:2e4}},co={version:1,github:Jn,local:At,tools:Bt,network:ln,telemetry:Zn,lsp:qn,output:pt},dn=5e3,pn=3e5,fn=0,mn=10,gn=1e3,hn=5e4;import{existsSync as Jc,readFileSync as vg}from"node:fs";import{z as te}from"zod";var uo=te.looseObject({$schema:te.string().optional(),version:te.number().int().optional(),github:te.record(te.string(),te.unknown()).optional(),local:te.record(te.string(),te.unknown()).optional(),tools:te.record(te.string(),te.unknown()).optional(),network:te.record(te.string(),te.unknown()).optional(),telemetry:te.record(te.string(),te.unknown()).optional(),lsp:te.record(te.string(),te.unknown()).optional(),output:te.record(te.string(),te.unknown()).optional()});var er=W.config;function Fg(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
|
|
11
|
+
`;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t=t.replace(/,(\s*[}\]])/g,"$1"),t}function Mg(e){let t=Fg(e);return JSON.parse(t)}function lo(){return Jc(er)}async function Zc(){return tr()}function tr(){let e=er;if(!Jc(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=vg(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=Mg(t),r=uo.safeParse(n);return r.success?{success:!0,config:r.data,path:e}:{success:!1,error:`Config file has invalid structure: ${r.error.issues[0]?.message??"unknown error"}`,path:e}}catch(t){return{success:!1,error:`Failed to parse config file: ${t instanceof Error?t.message:"Unknown error"}`,path:e}}}function qc(){return er}function zt(){return W.home}function Ng(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function Di(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Hi(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function eu(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function Dg(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function Ni(e,t){return e===void 0||e===null?null:eu(e,t)}function tu(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function Hg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=Ng(e.apiUrl,"github.apiUrl");r&&t.push(r)}function Gg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Hi(n.enabled,"local.enabled");r&&t.push(r);let o=Hi(n.enableClone,"local.enableClone");o&&t.push(o);let i=eu(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=Dg(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=tu(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function Ug(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=Ni(n.enabled,"tools.enabled");r&&t.push(r);let o=Ni(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=Ni(n.disabled,"tools.disabled");i&&t.push(i)}function Bg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=Di(n.timeout,"network.timeout",dn,pn);r&&t.push(r);let o=Di(n.maxRetries,"network.maxRetries",fn,mn);o&&t.push(o)}function zg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("telemetry: Must be an object");return}let r=Hi(e.logging,"telemetry.logging");r&&t.push(r)}function Qg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=tu(e.configPath,"lsp.configPath");r&&t.push(r)}function jg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=Di(r.defaultCharLength,"output.pagination.defaultCharLength",gn,hn);o&&t.push(o)}}function po(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>1&&n.push(`version: Config version ${r.version} is newer than supported version ${1}`)),Hg(r.github,t),Gg(r.local,t),Ug(r.tools,t),Bg(r.network,t),zg(r.telemetry,t),Qg(r.lsp,t),jg(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","telemetry","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}var $g="__octocodeRuntimeSurface__";function Gi(){return globalThis[$g]??"mcp"}function nu(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Ui(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function fo(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function Bi(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!=="")return!(t==="false"||t==="0")}function ru(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||Jn.apiUrl}}function ou(e){let t=Gi()==="cli",n=nu(process.env.ENABLE_LOCAL),r=nu(process.env.ENABLE_CLONE),o=fo(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??(t?!0:At.enabled),enableClone:r??e?.enableClone??(t?!0:At.enableClone),allowedPaths:o??e?.allowedPaths??At.allowedPaths,workspaceRoot:i??e?.workspaceRoot??At.workspaceRoot}}function iu(e){let t=fo(process.env.TOOLS_TO_RUN),n=fo(process.env.ENABLE_TOOLS),r=fo(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??Bt.enabled,enableAdditional:n??e?.enableAdditional??Bt.enableAdditional,disabled:r??e?.disabled??Bt.disabled}}function su(e){let t=Ui(process.env.REQUEST_TIMEOUT),n=Ui(process.env.MAX_RETRIES),r=t??e?.timeout??ln.timeout;r=Math.max(dn,Math.min(pn,r));let o=n??e?.maxRetries??ln.maxRetries;return o=Math.max(fn,Math.min(mn,o)),{timeout:r,maxRetries:o}}function au(e){return{logging:Bi(process.env.LOG)??e?.logging??Zn.logging}}function cu(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??qn.configPath}}var Vg=new Set(["yaml","json"]);function uu(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=Ui(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||pt.format,o=n??e?.pagination?.defaultCharLength??pt.pagination.defaultCharLength,i=Math.max(gn,Math.min(hn,o));return{format:Vg.has(r)?r:pt.format,pagination:{defaultCharLength:i}}}var mo=tt("octocode-config");function zi(e,t){let n=e!==void 0,r=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.LOG!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??co.version,github:ru(e?.github),local:ou(e?.local),tools:iu(e?.tools),network:su(e?.network),telemetry:au(e?.telemetry),lsp:cu(e?.lsp),output:uu(e?.output),source:o,configPath:n?t:void 0}}function rr(){let e=tr();if(e.success&&e.config){let t=po(e.config);if(t.warnings.length>0)for(let n of t.warnings)mo.warn(`Warning: ${n}`);if(!t.valid){for(let n of t.errors)mo.warn(`Validation error: ${n}`);return mo.warn("Config file has validation errors \u2014 falling back to defaults with env overrides"),zi(void 0)}return zi(e.config,e.path)}return e.error&&lo()&&mo.warn(e.error),zi(void 0)}async function Qi(){return rr()}var Qt=null,nr=0,Wg=6e4;function ae(){let e=Date.now();return Qt&&e-nr<Wg||(Qt=rr(),nr=e),Qt}async function go(){return ae()}async function ji(){return yn(),go()}function yn(){Qt=null,nr=0}function $i(){Qt=null,nr=0}function Vi(){return{cached:Qt!==null,timestamp:nr}}function lu(e){let t=ae(),n=e.split("."),r=t;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}import{existsSync as Kg,readdirSync as Yg,lstatSync as Xg}from"node:fs";import{join as Jg}from"node:path";function or(e){if(!Kg(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Yg(r)}catch{continue}for(let i of o){let s=Jg(r,i);try{let a=Xg(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function Zg(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}var ft="16.5.1";import{maskSensitiveData as eh}from"@octocodeai/octocode-engine/mask";var jt=null,Rn=null,Wi=Tt;function RA(e){e.resolveTokenFull&&(Wi=e.resolveTokenFull)}function bA(){Wi=Tt}var th=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"]);async function Ki(){try{let e=await Wi({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:th.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function du(){if(jt!==null)return;if(Rn!==null)return Rn;let e=(async()=>{let t=ae(),n=await Ki();jt={version:ft,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,loggingEnabled:t.telemetry.logging,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Rn=e;try{await e}catch(t){throw Rn===e&&(jt=null,Rn=null),t}}function SA(){jt=null,Rn=null,yn()}function ho(){if(!jt){let e=eh(hi.NOT_INITIALIZED.message);throw new Error(e)}return jt}async function pu(){return(await Ki()).token}function CA(){return ho().enableLocal}function PA(){let e=ho();return e.enableLocal&&e.enableClone}function fu(){return jt?.loggingEnabled??!1}async function EA(){return(await Ki()).source}function ir(){return"github"}function Yi(){let e=ae().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{completeMetadata as nh}from"@octocodeai/octocode-core";var Ie="lspGetSemantics",mu=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation"];function bn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Xi(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 ge=nh.toolNames,rh=new Set([ge.LOCAL_RIPGREP,ge.LOCAL_FETCH_CONTENT,ge.LOCAL_FIND_FILES,ge.LOCAL_VIEW_STRUCTURE,ge.LOCAL_BINARY_INSPECT,Ie]);function Ji(e){return rh.has(e)}var Zi=class{session;logEndpoint="https://octocode-mcp-host.onrender.com/log";constructor(){this.session=to()}getSessionId(){return this.session.sessionId}getSession(){return this.session}async logInit(){await this.sendLog("init",{})}async logToolCall(t,n,r,o,i){let s=no(1);s.session&&(this.session=s.session);let a={tool_name:t,repos:Ji(t)?[]:n.map(()=>"[redacted]"),provider:Ji(t)?void 0:ir()};await this.sendLog("tool_call",a)}async logError(t,n){let r=ro(1);r.session&&(this.session=r.session),await this.sendLog("error",{error:`${t}:${n}`})}async logRateLimit(t){let n=t.provider?He({rateLimits:1,rateLimitsByProvider:{[t.provider]:1}}):oo(1);if(n.session&&(this.session=n.session),t.provider==="github"){let r=ao(1);r.session&&(this.session=r.session)}await this.sendLog("rate_limit",t)}logPackageRegistryFailure(t){let n=He({packageRegistryFailures:{[t]:1}});n.session&&(this.session=n.session)}async sendLog(t,n){if(!(t!=="init"&&!fu()))try{let r={sessionId:this.session.sessionId,intent:t,data:n,timestamp:new Date().toISOString(),version:ft};await fetch(this.logEndpoint,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)})}catch{}}},sr=null;function vA(){return sr||(sr=new Zi),sr}function Sn(){return sr}async function FA(){let e=Sn();e&&await e.logInit()}async function MA(e,t,n,r,o){let i=Sn();i&&await i.logToolCall(e,t,n,r,o)}async function NA(e){let t=Sn();t&&await t.logToolCall(e,[],void 0,void 0,void 0)}async function M(e,t){let n=Sn();n&&await n.logError(e,t)}async function Lt(e){let t=Sn();t&&await t.logRateLimit(e)}function gu(e){let t=Sn();t&&t.logPackageRegistryFailure(e)}function DA(){sr=null}function ah(e){return sh("sha256").update(e).digest("hex").substring(0,16)}var ch=oh.plugin(ih),uh=300*1e3,qi=50,lh=60*1e3;function es(e){return Date.now()-e.createdAt>uh}var ze=new Map,Cn=null,Ot=null;function Cu(){for(let[e,t]of ze.entries())es(t)&&ze.delete(e);if(ze.size>qi){let e=[...ze.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=ze.size-qi;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&ze.delete(r[0])}}}function dh(){Ot||(Ot=setInterval(Cu,lh),typeof Ot=="object"&&"unref"in Ot&&Ot.unref())}var hu=3,yu=60;function Ru(e,t,n){Lt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var ph=()=>({onRateLimit:(e,t,n,r)=>(Ru("primary",e,t),r<hu&&e<yu),onSecondaryRateLimit:(e,t,n,r)=>(Ru("secondary",e,t),r<hu&&e<yu)});function bu(e){let t=ho(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${ft}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:ph(),log:r,...e&&{auth:e}};return new ch(o)}async function ie(e){if(dh(),e?.token){let n=ah(e.token),r=ze.get(n);if(r&&!es(r))return r.client;ze.size>=qi&&Cu();let o=bu(e.token);return ze.set(n,{client:o,createdAt:Date.now()}),o}let t=ze.get("DEFAULT");return t&&!es(t)?t.client:Cn||(Cn=(async()=>{try{let n=await pu(),r=bu(n??void 0);return ze.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{Cn=null}})(),Cn)}var fh=200,Pn=new Map;async function Ge(e,t,n){let r=`${e}/${t}`,o=Pn.get(r);if(o)return o;let i=await ie(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Su(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),Su(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Su(e,t){if(Pn.size>=fh){let n=Pn.keys().next().value;n!==void 0&&Pn.delete(n)}Pn.set(e,t)}function VA(){ze.clear(),Cn=null,Pn.clear(),Ot&&(clearInterval(Ot),Ot=null)}import{ContentSanitizer as Kh}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as mh}from"node:module";var gh=mh(import.meta.url),Pu="@octocodeai/octocode-engine",yo,hh=()=>gh(Pu),ts=class extends Error{constructor(n){super(`Failed to load native dependency ${Pu}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function K(){if(yo)return yo;try{return yo=hh(),yo}catch(e){throw new ts(e)}}var O={applyContentViewMinification(e,t){return K().applyContentViewMinification(e,t)},applyMinification(e,t){return K().applyMinification(e,t)},minifyContent(e,t){return K().minifyContent(e,t)},minifyContentSync(e,t){return K().minifyContentSync(e,t)},minifyContentResult(e,t){return K().minifyContentResult(e,t)},minifyMarkdownCore(e){return K().minifyMarkdownCore(e)},extractSignatures(e,t){return K().extractSignatures(e,t)},extractJsSymbols(e,t){return K().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return K().findInFileReferences(e,t,n,r)},getSupportedJsTsExtensions(){return K().getSupportedJsTsExtensions()},structuralSearch(e,t,n,r){return K().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return K().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return K().getSupportedStructuralExtensions()},inspectBinaryNative(e){return K().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return K().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return K().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return K().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return K().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return K().parseRipgrepJson(e,t)},searchRipgrep(e){return K().searchRipgrep(e)},queryFileSystem(e){return K().queryFileSystem(e)},extractMatchingLines(e,t,n){return K().extractMatchingLines(e,t,n)},filterPatch(e,t){return K().filterPatch(e,t)},charToByteOffset(e,t){return K().charToByteOffset(e,t)},byteToCharOffset(e,t){return K().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return K().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return K().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return K().SIGNATURES_ONLY_HINT}};import{RequestError as xu}from"octokit";var G={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},le={[G.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."},[G.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."},[G.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},[G.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)."},[G.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."},[G.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."},[G.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."},[G.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."},[G.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."},[G.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Eu={401:G.AUTH_REQUIRED,403:G.FORBIDDEN_PERMISSIONS,404:G.NOT_FOUND,422:G.INVALID_REQUEST,502:G.SERVER_UNAVAILABLE,503:G.SERVER_UNAVAILABLE,504:G.SERVER_UNAVAILABLE},ns={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},rs={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ro={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};function xe(e){return t=>{}}function Tu(e,t){return n=>t}var yh=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function $t(e){if(!(e instanceof xu)||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 yh.some(o=>r.includes(o))})}function Z(e){return e instanceof xu?Rh(e):e instanceof Error?_h(e):{error:typeof e=="string"?e:le[G.UNKNOWN].message,type:"unknown"}}function Rh(e){let{status:t,message:n,response:r}=e;if(t===403)return Sh(n,r);if(t===429)return bh(n,r);let o=Eu[t];return o?xh(o,t):En(G.UNKNOWN,{error:n||le[G.UNKNOWN].message,status:t})}function os(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function bh(e,t){let n=t?.headers,r=os(n,"retry-after"),o=os(n,"x-ratelimit-reset"),i=os(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ro.RESET_BUFFER_SECONDS,0):void 0);return Lt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}).catch(xe("rate-limit logging")),En(G.RATE_LIMIT_PRIMARY,{error:e||le[G.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:le[G.RATE_LIMIT_PRIMARY].suggestion})}function Sh(e,t){let n=t?.headers;if(rs.SECONDARY.test(e))return Ch(n);let r=n?.["x-ratelimit-remaining"],o=Th(t);return r!==void 0&&String(r)==="0"||o?Ph(n):Eh(n)}function Ch(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ro.SECONDARY_FALLBACK_SECONDS:t;return Lt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}).catch(xe("rate-limit logging")),En(G.RATE_LIMIT_SECONDARY,{error:le[G.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:le[G.RATE_LIMIT_SECONDARY].suggestion})}function Ph(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)+Ro.RESET_BUFFER_SECONDS,0):void 0,i=r?le[G.RATE_LIMIT_PRIMARY].messageWithTime(r,o):le[G.RATE_LIMIT_PRIMARY].messageWithoutTime;return Lt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}).catch(xe("rate-limit logging")),En(G.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:le[G.RATE_LIMIT_PRIMARY].suggestion})}function Eh(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=le[G.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=wh(String(t),String(n))),En(G.FORBIDDEN_PERMISSIONS,{error:le[G.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Th(e){return e?.data?.errors?.some(n=>n.type===rs.GRAPHQL_TYPE)??!1}function xh(e,t){let n=le[e];return En(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function _h(e){return ns.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:le[G.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:le[G.NETWORK_CONNECTION_FAILED].suggestion}:ns.TIMEOUT.some(t=>e.message.includes(t))?{error:le[G.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:le[G.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function En(e,t){return{type:"http",...t}}function wh(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?le[G.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):le[G.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Ah(e){return`user:${e}`}var Lh=/[@/]/,Oh=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Ih=/^[A-Za-z0-9_-]+$/;function _u(e){return e.startsWith('"')||Ih.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var ar=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(Ah(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=Lh.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},is=class extends ar{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(_u))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Oh):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}},ss=class extends ar{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(_u)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},as=class extends ar{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function wu(e){return new is().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function Au(e){return new ss().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function Lu(e){return new as().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ou(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import kh from"node-cache";import vh from"crypto";var Fh="v1",Mh=300*1e3,Qe=new kh({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Se={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Iu={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},Tn=new Map;function Nh(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Dh(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Hh(e){let t=Nh(e);if(!(!t||!Dh(t)))try{so(t,1)}catch{}}function Gh(){let e=Date.now();for(let[t,n]of Tn.entries())e-n.startedAt>Mh&&Tn.delete(t)}var Uh=new Set([]);function Bh(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(Uh.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function _e(e,t,n){let r=cs(Bh(t)),o=n?`${n}:${r}`:r,i=vh.createHash("sha256").update(o).digest("hex");return`${Fh}-${e}:${i}`}function cs(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=>cs(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${cs(i,t)}`}).join(",")}}`)}function zh(e){return Iu[e]||Iu.default}function Qh(e,t,n){try{return Qe.set(e,t,n),Se.sets++,Se.totalKeys=Qe.keys().length,!0}catch{try{let r=Qe.keys();for(let o of r)Qe.get(o);return Qe.set(e,t,n),Se.sets++,Se.totalKeys=Qe.keys().length,!0}catch{return!1}}}async function we(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Qe.get(e);if(i!==void 0)return Se.hits++,Hh(e),i}catch{}Gh();let r=Tn.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Se.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=zh(u)}Qh(e,i,a)}return i}finally{Tn.delete(e)}})();return Tn.set(e,{promise:o,startedAt:Date.now()}),o}function aL(){Qe.flushAll(),Tn.clear(),Se.hits=0,Se.misses=0,Se.sets=0,Se.totalKeys=0,Se.lastReset=new Date}function It(e){let t=Qe.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Qe.del(r)>0&&n++}return n>0&&(Se.totalKeys=Qe.keys().length),n}function cL(){return It("local-")}function uL(){return It("lsp-")}function lL(){let e=0;return e+=It("gh-api-"),e+=It("bb-api-"),e+=It("gh-repo-"),e+=It("bb-repo-"),e+=It("github-user"),e+=It("npm-search"),e}function dL(){let e=Se.hits+Se.misses;return{...Se,hitRate:e>0?Se.hits/e*100:0,cacheSize:Qe.keys().length}}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as gL,DISCOVERY_IGNORED_FILE_NAMES as hL,DISCOVERY_IGNORED_FOLDER_NAMES as yL,getDiscoveryExtension as ku,shouldIgnoreDiscoveryDir as cr,shouldIgnoreDiscoveryFile as xn}from"@octocodeai/octocode-engine/security";import{completeMetadata as us}from"@octocodeai/octocode-core";var S=new Proxy({},{get(e,t){return us.toolNames[t]},ownKeys(){return Object.keys(us.toolNames)},getOwnPropertyDescriptor(e,t){let n=us.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as jh}from"@octocodeai/octocode-core";var ls=new Proxy({},{get(e,t){return jh.tools[t]?.description??""}});import{completeMetadata as $h}from"@octocodeai/octocode-core";function ds(e){return Object.prototype.hasOwnProperty.call($h.tools,e)}import{completeMetadata as Vh}from"@octocodeai/octocode-core";function ps(){return Vh.baseSchema}var Wh=new Proxy({},{get(e,t){return ps()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(ps())]))},getOwnPropertyDescriptor(e,t){let n=ps();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});var vu=Symbol.for("octocode.rawResponseChars");function N(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Fu(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function U(e,t){let n=typeof t=="number"?Fu(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,vu,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ne(e){if(!(typeof e!="object"||e===null))return Fu(e[vu])}function bo(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var Mu=30;async function Nu(e,t,n){let r=_e("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await we(r,async()=>await Yh(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Yh(e,t){try{let n=await ie(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(R=>R&&R.trim()).length===0)return await M(S.GITHUB_SEARCH_CODE,oe.QUERY_EMPTY.code),{error:oe.QUERY_EMPTY.message,type:"http",status:400};let r=wu(e);if(!r.trim())return await M(S.GITHUB_SEARCH_CODE,oe.QUERY_EMPTY.code),{error:oe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Mu,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 Xh(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,d=Math.min(l,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),f=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...u?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:f,...f?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:bo(a.headers),rawResponseChars:N(a.data)}}catch(n){if($t(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Mu,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}async function Xh(e,t){let n=Jh(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!xn(p.path)),c=0,u=0,l=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],g=await Promise.allSettled((p.text_matches||[]).map(async x=>{let C=x.fragment,_=Kh.sanitizeContent(C||"",p.path);C=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(I=>r.add(`${p.path}: ${I}`));try{let I=await O.minifyContent(C||"",p.path);C=I.content,I.failed?o=!0:I.type!=="failed"&&(f.push(I.type),i.push(I.type))}catch{o=!0}return{context:C||"",positions:x.matches?.map(I=>Array.isArray(I.indices)&&I.indices.length>=2?[I.indices[0],I.indices[1]]:[0,0])||[]}})),h=g.filter(x=>x.status==="fulfilled").map(x=>x.value),R=g.filter(x=>x.status==="rejected").length;R>0&&(u+=R);let b=p,P=Array.from(new Set(f));return{path:p.path,matches:h,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...b.last_modified_at&&{lastModifiedAt:b.last_modified_at},...P.length>0&&{minificationType:P.join(",")}}})),d=l.filter(p=>p.status==="fulfilled").map(p=>p.value);c=l.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),u>0&&r.add(`${u} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function Jh(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}import{writeFileSync as Yu,mkdirSync as ys,existsSync as yr,rmSync as Sy,readdirSync as Cy,statSync as Xu}from"node:fs";import{join as Po,dirname as Ju,resolve as Rs,sep as bs}from"node:path";import{RequestError as Du}from"octokit";async function Zh(e,t,n,r,o,i,s,a){let c=await Ge(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 l=Z(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await Bu(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Uu(i,m)]),{...l,...d&&{scopesSuggestion:d}}}async function qh(e,t,n,r,o,i){let s=Z(t),a=await Bu(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Uu(o,a)]),s}async function Hu(e,t){let n=e.replace(/\s/g,"");if(!n)return await M(S.GITHUB_FETCH_CONTENT,Oe.FILE_EMPTY.code),{error:Oe.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?(await M(S.GITHUB_FETCH_CONTENT,Oe.BINARY_FILE.code),{error:Oe.BINARY_FILE.message,type:"unknown",status:415}):{data:r.toString("utf-8"),status:200}}catch{return await M(S.GITHUB_FETCH_CONTENT,Oe.DECODE_FAILED.code),{error:Oe.DECODE_FAILED.message,type:"unknown",status:422}}}async function Gu(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"?Hu(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return Z(i)}}async function ey(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 Ge(t,n,i).catch(()=>"HEAD"),u=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(u.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let l=u.data.find(m=>m.name===a&&m.type==="file");if(!l)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await Gu(e,t,n,l.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return Z(s)}}async function So(e,t){try{let n=await ie(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,u=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof Du&&d.status===404)if(s){let m=await Zh(n,d,a,r,o,i,s,t);if("result"in m)c=m.result,u=m.actualBranch;else return m}else return await qh(n,d,r,o,i,s);else{if(d instanceof Du&&d.status===413)return await ey(n,r,o,i,s||u,t);throw d}}let l=c.data;if(Array.isArray(l))return await M(S.GITHUB_FETCH_CONTENT,Oe.PATH_IS_DIRECTORY.code),{error:Oe.PATH_IS_DIRECTORY.message(S.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in l&&l.type==="file"){let d=typeof l.content=="string"?l.content:"",m=l.size??0,p;if(d.length>0)p=await Hu(d,i);else if(m>0&&"sha"in l&&typeof l.sha=="string"&&l.sha)p=await Gu(n,r,o,l.sha,i);else return await M(S.GITHUB_FETCH_CONTENT,Oe.FILE_EMPTY.code),{error:Oe.FILE_EMPTY.message,type:"unknown",status:404};if("error"in p)return p;if(!u&&!s)try{u=await Ge(r,o,t)}catch{}return{data:{rawContent:p.data,branch:u||void 0,resolvedRef:u||s||"HEAD"},status:200,rawResponseChars:N(l)}}return await M(S.GITHUB_FETCH_CONTENT,Oe.UNSUPPORTED_TYPE.code),{error:Oe.UNSUPPORTED_TYPE.message(l.type),type:"unknown",status:415}}catch(n){return Z(n)}}function Uu(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Bu(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,u=[],l=c.find(p=>p.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>u.push(p.path)),u.length===0&&d.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(f=>u.push(f.path)),Array.from(new Set(u)).slice(0,3)}catch{return[]}}import{existsSync as pr,readFileSync as ty,writeFileSync as ny,mkdirSync as ry,rmSync as lr,readdirSync as oy,statSync as iy}from"node:fs";import{join as je}from"node:path";import{createHash as sy}from"node:crypto";var ay=1440*60*1e3,cy=600*1e3,uy=2*1024*1024*1024,ly=50,Qu=".octocode-clone-meta.json",_n=null;function sO(e){return fs(e)}function fs(e){return je(e,"tmp","clone")}function ju(e){return je(e,"tmp","tree")}function dy(e){return e?`__sp_${sy("sha256").update(e).digest("hex").substring(0,6)}`:""}function $u(e,t,n,r,o){let i=`${r}${dy(o)}`;return je(fs(e),t,n,i)}function ms(e,t,n,r){return je(ju(e),t,n,r)}function py(e){return typeof e=="object"&&e!==null}function fy(e){if(!py(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),t}function gs(e){let t=je(e,Qu);if(!pr(t))return null;try{return fy(JSON.parse(ty(t,"utf-8")))}catch{return null}}function fr(e,t){try{ny(je(e,Qu),JSON.stringify(t,null,2),"utf-8")}catch{}}function Vu(e){return Date.now()<new Date(e.expiresAt).getTime()}function mr(e){let t=gs(e);return t?Vu(t)?pr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function my(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return ay}function gy(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return uy}function hy(){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 ly}function gr(e,t,n,r,o,i){let s=new Date;return{clonedAt:s.toISOString(),expiresAt:new Date(s.getTime()+my()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{}}}function hr(e){let t=je(e,"..");try{pr(t)||ry(t,{recursive:!0,mode:448})}catch(n){throw new Error(`Failed to create clone parent directory '${t}': ${n instanceof Error?n.message:String(n)}`)}}function hs(e){try{pr(e)&&lr(e,{recursive:!0,force:!0})}catch{}}function ur(e){try{return iy(e).isDirectory()}catch{return!1}}function Vt(e){try{return oy(e)}catch{return[]}}function*Wu(e){for(let t of Vt(e)){let n=je(e,t);if(ur(n))for(let r of Vt(n)){let o=je(n,r);if(ur(o))for(let i of Vt(o)){let s=je(o,i);ur(s)&&(yield s)}}}}function zu(e){for(let t of[...Vt(e)]){let n=je(e,t);if(ur(n)){for(let r of[...Vt(n)]){let o=je(n,r);if(ur(o)&&Vt(o).length===0)try{lr(o,{recursive:!0,force:!0})}catch{}}if(Vt(n).length===0)try{lr(n,{recursive:!0,force:!0})}catch{}}}}function yy(e){let t=0;for(let n of Wu(e))try{let r=gs(n);(!r||!Vu(r))&&(lr(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Ry(e){let t=[];for(let n of Wu(e)){let r=gs(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??or(n)})}return t}function by(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{lr(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Ku(e){if(!pr(e))return 0;let t=0;try{t+=yy(e)}catch{return t}zu(e);let n=by(Ry(e),gy(),hy());return t+=n,n>0&&zu(e),t}function Co(e){return Ku(fs(e))}function dr(e){return Ku(ju(e))}function aO(e){_n||(Co(e),dr(e),_n=setInterval(()=>{Co(e),dr(e)},cy),_n.unref())}function cO(){_n&&(clearInterval(_n),_n=null)}var Py=50,Ey=5*1024*1024,Ty=300*1024,xy=5,_y=1e4,wy=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".eot",".otf",".pyc",".class",".o",".obj",".lock",".min.js",".min.css"]);async function Zu(e,t,n,r,o,i=!1){let s=zt(),a=ms(s,e,t,r),c=Rs(Po(a,n));if(!c.startsWith(a+bs)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=mr(a);if(u.hit&&!i&&yr(c)){let P=Iy(c,a);return{localPath:c,repoRoot:a,files:P.files,fileCount:P.fileCount,totalSize:P.totalSize,cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await ie(o),{data:d}=await l.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(d))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let m=d.filter(P=>{if(P.type!=="file"||!P.download_url||P.size>Ty)return!1;let x=ku(P.name,{lowercase:!0,leadingDot:!0});return!wy.has(x)}).slice(0,Py),p=o?.token,f=await Ay(m,xy,p),g=0,h=[];for(let{entry:P,content:x}of f){if(g+x.length>Ey)break;g+=x.length,h.push({entry:P,content:x})}dr(s),hr(a),yr(c)&&Sy(c,{recursive:!0,force:!0}),ys(c,{recursive:!0,mode:448});let R=[];for(let{entry:P,content:x}of h){let C=Rs(Po(a,P.path));if(!C.startsWith(a+bs))continue;let _=Ju(C);yr(_)||ys(_,{recursive:!0,mode:448}),Yu(C,x,"utf-8"),R.push({path:P.path,size:x.length,type:"file"})}let b=gr(e,t,r,"treeFetch");return fr(a,b),{localPath:c,repoRoot:a,files:R,fileCount:R.length,totalSize:g,cached:!1,expiresAt:b.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function qu(e,t,n,r,o,i=!1){let s=zt(),a=ms(s,e,t,r),c=Rs(Po(a,n));if(!c.startsWith(a+bs)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=mr(a);if(!i&&u.hit&&yr(c))return{localPath:c,repoRoot:a,path:n,size:ky(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await So({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in l)||!l.data){let f="error"in l?l.error:void 0;throw new Error(f||`Failed to fetch ${e}/${t}/${n}`)}dr(s),hr(a);let d=Ju(c);yr(d)||ys(d,{recursive:!0,mode:448}),Yu(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,p=gr(e,t,m,"treeFetch");return fr(a,p),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}async function Ay(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 Oy(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var Ly=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function Oy(e,t){try{let o=new URL(e);if(!Ly.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(),_y);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 Iy(e,t){let n=[],r=0;function o(i){let s;try{s=Cy(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Po(i,a);try{let u=Xu(c);if(u.isDirectory())o(c);else if(u.isFile()){let l=c.substring(t.length+1);r+=u.size,n.push({path:l,size:u.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function ky(e){try{return Xu(e).size}catch{return 0}}function Ce(){try{return ae().output.pagination.defaultCharLength}catch{return pt.pagination.defaultCharLength}}var el=1e5;function tl(e){let t=Math.min(Math.max(Ce(),1),el),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,el)}import{ContentSanitizer as il}from"@octocodeai/octocode-engine/contentSanitizer";function Rr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Wt(e){return Rr(e).length}function vy(e,t,n){return O.byteSliceContent(e,t,n)}function Eo(e,t){return O.byteToCharOffset(e,t)}function nl(e,t){return O.charToByteOffset(e,t)}function rl(e){return O.charToByteOffset(e,e.length)}function EO(e,t,n){let r=vy(e,t,t+n);return{charOffset:Eo(e,t),charLength:r.length,text:r}}function Ss(e,t,n,r){return O.sliceContent(e,t,n,r)}function mt(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=rl(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,u,l,d,m,p,f,g;if(o==="bytes"){let h=Math.min(t,s),R=Math.min(h+n,s);d=Eo(e,h),m=Eo(e,R),m<i&&nl(e,m)<R&&(m+=1);let b=Ss(e,d,m-d);c=b.text,d=b.charOffset,m=b.charOffset+b.charLength,u=b.byteOffset,l=b.byteOffset+b.byteLength,p=l<s;let P=r.actualOffset??h;f=Math.floor(P/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let h=Ss(e,t,n);c=h.text,d=h.charOffset,m=h.charOffset+h.charLength,u=h.byteOffset,l=h.byteOffset+h.byteLength,p=m<i;let R=r.actualOffset??d;f=Math.floor(R/a)+1,g=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:u,byteLength:l-u,totalBytes:s,nextByteOffset:p?l:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:g}}function _O(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function br(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}}}function wO(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
|
|
12
|
+
`){let u=e.lastIndexOf(`
|
|
13
|
+
`,o-1);o=u===-1?0:u+1}let i=o,s=0;for(;i<r;){let u=e.indexOf(`
|
|
14
|
+
`,i);if(u===-1){i=r;break}if(i=u+1,s++,i-o>=n)break}let a=e.substring(o,i),c=i<r;return{sliced:a,actualOffset:o,actualLength:a.length,hasMore:c,lineCount:s,totalChars:r,nextOffset:c?i:void 0}}var Fy=8e3,My="__octocode_generic__.unknown";function Ny(e){return e&&e.trim().length>0?e:My}function ol(e,t){return O.getSemanticBoundaryOffsets(e,Ny(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function Dy(e,t){let n=e.indexOf(`
|
|
15
|
+
`,t);return n===-1?void 0:n+1}function Sr(e){let t=e.trimEnd().split(`
|
|
16
|
+
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function Cr(e,t,n){let r=Dy(e,Math.max(0,t));if(r!==void 0)return ol(e,n).find(o=>o>=r&&o>t)}function OO(e,t,n,r,o){if(!Sr(e))return;let i=Cr(t,n,o);if(i===void 0)return;let s=i-n,a=`Page cut mid-block at char ${n}. Next top-level definition at char ${i}. Re-request with charLength=${r+s} to extend this page to the next boundary, or use charOffset=${n} to continue page-by-page.`;return{nextBlockChar:i,hint:a}}function To(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=ol(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(l=>l>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=Fy?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function xo(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Invalid regex pattern: ${l}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
17
|
+
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=O.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(u=>({start:u.start,end:u.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(u=>u)}}function Hy(){let e=Ce();return Math.min(e,8e3)}function _o(e,t){return{sourceChars:e,sourceBytes:t}}function sl(e,t,n){let r=e.content??"",o=n??Hy();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=To(r,t,o,i),c=mt(r,t,s),u;if(c.hasMore&&a==="char-limit"&&Sr(c.paginatedContent)){let l=c.charOffset+c.charLength;u=Cr(r,l,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,chunkMode:a,...u!==void 0&&{nextBlockChar:u}}}}async function al(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function cl(e,t,n,r,o,i,s,a,c=5,u,l,d,m="standard"){let p=e.length,f=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",h=g?"standard":"none",R;if(m==="symbols"){let $=O.extractSignatures(e,o);if($===null&&(R=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),$!==null){let D=il.sanitizeContent($,o),Re=O.applyContentViewMinification(D.content,o),ue=[O.SIGNATURES_ONLY_HINT];return u&&ue.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),D.hasSecrets&&ue.push(`Secrets detected and redacted: ${D.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Re,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Wt(e),..._o(p,f),isPartial:!1,signaturesExtracted:!0,hints:ue}}}let b=new Set,P=e,x=P.split(`
|
|
18
|
+
`),C=Wt(P),_=e,I,j,w=!1,A;if(i)_=e;else if(u){let $=d===!0,D;try{D=xo(x,u,c,l??!1,$)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:C,..._o(p,f),matchNotFound:!0,searchedFor:u,hints:[`Invalid regex "${u}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(D.matchCount===0){let V=l?[`Regex "${u}" matched no lines. Verify the pattern, check flags (case-${$?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${u}" not found in file${$?" (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:C,..._o(p,f),matchNotFound:!0,searchedFor:u,hints:V}}_=D.lines.join(`
|
|
19
|
+
`);let Re=D.matchRanges[0],ue=D.matchRanges[D.matchRanges.length-1];s=Re.start,a=ue.end,I=Re.start,j=ue.end,w=!0,D.matchRanges.length>1&&(A=D.matchRanges);let at=D.matchingLines.slice(0,5).join(", "),en=D.matchingLines.length>5?` and ${D.matchingLines.length-5} more`:"";b.add(D.matchCount>1?`Found ${D.matchCount} occurrences of "${u}" on lines ${at}${en} \u2014 all shown as ${D.matchRanges.length} slice${D.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${u}" on line ${D.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let $=s||1,D=a||C;if($<1||$>C)_=e;else if(D<$)_=e;else{let Re=Math.max(1,$),ue=Math.min(C,D),at=x.slice(Re-1,ue);I=Re,j=ue,w=!0,_=at.join(`
|
|
20
|
+
`),D>C&&b.add(`Requested endLine ${D} adjusted to ${C} (file end)`)}}let Q=il.sanitizeContent(_,o);if(_=g?O.applyContentViewMinification(Q.content,o):Q.content,Q.hasSecrets&&b.add(`Secrets detected and redacted: ${Q.secretsDetected.join(", ")}`),Q.warnings.length>0&&Q.warnings.forEach($=>b.add($)),C>2e3&&m!=="symbols"&&!u&&!s&&!a&&!i){let $=Math.max(1,C-200);b.add(`Large file (${C} lines) \u2014 minify:"symbols" for an export index, or startLine=${$} for the tail.`)}let se=Array.from(b);return{owner:t,repo:n,path:o,content:_,...h!=="standard"&&{contentView:h},branch:r,totalLines:C,..._o(p,f),...w&&{startLine:I,endLine:j,isPartial:w},...A&&{matchRanges:A},...se.length>0&&{matchLocations:se},...(se.length>0||R)&&{warnings:[...R?[R]:[],...se]}}}async function ul(e,t,n){let r=_e("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await we(r,async()=>await So(e,t),{shouldCache:p=>"data"in p&&!p.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await cl(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,u=e.charOffset??0,l=e.charLength,d=a?c:sl(c,u,l),m=(e.charOffset??0)>0;if(!e.noTimestamp&&!m)try{let p=await ie(t),f=await we(_e("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>al(p,e.owner,e.repo,e.path,e.branch),{shouldCache:g=>g!==null,forceRefresh:e.forceRefresh===!0});f&&(d.lastModified=f.lastModified,d.lastModifiedBy=f.lastModifiedBy)}catch{}return{data:d,status:200,rawResponseChars:o.rawResponseChars}}import{ContentSanitizer as pl}from"@octocodeai/octocode-engine/contentSanitizer";var Gy=2,Uy=20;function Pr(e,t=Uy){let n=e?Rr(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function ll(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return O.filterPatch(e,r)}function dl(e){return e?O.filterPatch(e,{trimContext:!0,contextLines:Gy}):""}function Cs(e){let t=pl.sanitizeContent(e.title??""),n=e.body?pl.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 By=Ce(),zy=Math.round(Ce()/4),fl=3;function ml(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 Er(e,t={}){let n=t.charOffset??0,r=t.charLength??By,o=t.charLength??zy,i=typeof e.body=="string"?O.minifyMarkdownCore(e.body):e.body,s=ml(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,g)=>{let h=f.commentType==="review_inline"?0:1,R=g.commentType==="review_inline"?0:1;return h-R}),c=a.filter(f=>f.commentType==="review_inline").length,u=a.length-c,l=t.includeFullCommentDetails?a:a.slice(0,fl),d=l.map(f=>{let g=ml(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>l.length||d.some(f=>"body_pagination"in f)),p=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...m?[`PR comments are paginated/summarized to ${fl} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(f=>({id:0,name:f,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:u}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((f,g)=>f+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((f,g)=>f+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(f=>({filename:f.filename,status:f.status,additions:f.additions,deletions:f.deletions,patch:f.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function Tr(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 wo(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?ll(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?dl(a.patch):a.patch}))}import{ContentSanitizer as Ps}from"@octocodeai/octocode-engine/contentSanitizer";function Ao(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function gl(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function hl(e){let t=gl(e);return t?t.discussion!==!1:!1}function yl(e){let t=gl(e);return t?t.reviewInline!==!1:!1}function Rl(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function bl(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Sl(e){return!!e.content?.comments?.includeBots}var Qy=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function Cl(e){let t=e.toLowerCase();return t.endsWith("[bot]")||Qy.has(t.replace(/\[bot\]$/,""))}function Es(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
|
|
21
21
|
|
|
22
|
-
`).trim()}async function ma(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=G(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!pa(p.user?.login??"")),d=i.length-l.length,u=l.map(p=>{let f=z.minifyMarkdownCore(bo(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Ro.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return d>0&&m.push(`${d} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(u,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:U([],0)}}}async function fa(e,t,n,r){try{let{items:o,rawResponseChars:i}=await So(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return U(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Ro.sanitizeContent(z.minifyMarkdownCore(bo(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return U([],0)}}async function ha(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=G(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!pa(p.user?.login??"")),d=i.length-l.length,u=l.map(p=>{let f=z.minifyMarkdownCore(bo(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Ro.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return d>0&&m.push(`${d} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(u,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:U([],0)}}}async function ga(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=yo(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:d}=hn(t);if(l&&d){let u=await n.rest.pulls.get({owner:l,repo:d,pull_number:e.number});if(u.data&&(s+=G(u.data),o.head=u.data.head?.ref,o.head_sha=u.data.head?.sha,o.base=u.data.base?.ref,o.base_sha=u.data.base?.sha,o.draft=u.data.draft??!1,u.data.merged_at&&(o.merged_at=u.data.merged_at),o.additions=u.data.additions??0,o.deletions=u.data.deletions??0,Zn(t)||(o.file_changes={total_count:u.data.changed_files??0,files:[]}),Zn(t))){let m=await ya(l,d,e.number);m&&(s+=ee(m)??0,m.files=Jn(m.files,t),o.file_changes=m)}}}catch(l){D(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=aa(t),c=ca(t);if(a||c){let{owner:l,repo:d}=hn(t);if(l&&d){let u=da(t),m=()=>Promise.resolve({comments:U([],0)}),[{comments:p,note:f},{comments:h,note:y}]=await Promise.all([a?ma(n,l,d,e.number,u):m(),c?ha(n,l,d,e.number,u):m()]);o.comments=[...p,...h],s+=(ee(p)??0)+(ee(h)??0);let b=[f,y].filter(g=>typeof g=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(ua(t))try{let{owner:l,repo:d}=hn(t);if(l&&d){let u=await fa(n,l,d,e.number);s+=ee(u)??0,o.reviews=u}}catch(l){D(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(la(t))try{let{owner:l,repo:d}=hn(t);if(l&&d){let u=await Ra(l,d,e.number,t);u&&(s+=ee(u)??0,o.commits=u)}}catch(l){D(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return U(o,s)}async function So(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 ya(e,t,n,r){let o=await re(r),{items:i,rawResponseChars:s}=await So(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U({total_count:i.length,files:i},s)}async function qm(e,t,n,r){let o=await re(r),{items:i,rawResponseChars:s}=await So(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U(i,s)}async function ef(e,t,n,r){try{let i=await(await re(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return U(i.data.files||[],i.data)}catch{return null}}async function Ra(e,t,n,r,o){let i=await qm(e,t,n,o);if(!i)return null;let s=ee(i)??0,a=[...i].sort((l,d)=>{let u=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(d.commit.author?.date?new Date(d.commit.author.date).getTime():0)-u}),c=await Promise.all(a.map(async l=>{let d=await ef(e,t,l.sha,o),u=[];return d&&(s+=ee(d)??0,u=Jn(d,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:u}}));return U(c,s)}async function qn(e,t,n,r){let{prData:o,sanitizationWarnings:i}=yo(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,Zn(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Zn(t))try{let u=await ya(a,c,e.number,r);u&&(s+=ee(u)??0,u.files=Jn(u.files,t),o.file_changes=u)}catch(u){D(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let l=aa(t),d=ca(t);if(l||d){let u=da(t),m=()=>Promise.resolve({comments:U([],0)}),[{comments:p,note:f},{comments:h,note:y}]=await Promise.all([l?ma(n,a,c,e.number,u):m(),d?ha(n,a,c,e.number,u):m()]);o.comments=[...p,...h],s+=(ee(p)??0)+(ee(h)??0);let b=[f,y].filter(g=>typeof g=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(ua(t))try{let u=await fa(n,a,c,e.number);s+=ee(u)??0,o.reviews=u}catch(u){D(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(la(t))try{let u=await Ra(a,c,e.number,t,r);u&&(s+=ee(u)??0,o.commits=u)}catch(u){D(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return U(o,s)}function tf(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function lw(e,t,n){let r=Ee("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode},n);return await Te(r,async()=>await Co(e,t),{shouldCache:i=>!i.error})}async function Co(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return await D(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PR_REQUIRED_PARAMS.code),{pull_requests:[],total_count:0,error:ne.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return await D(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PR_SINGLE_VALUES.code),{pull_requests:[],total_count:0,error:ne.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await re(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await qn(a,e,i,t);return{pull_requests:[fn(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:G(s.data)+(ee(c)??0)}}catch(i){let s=Z(i);return await D(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PULL_REQUEST_FETCH_FAILED.code),tf(s,ne.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 ba(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Sa(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Ca(e,t,n){let r=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,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await Te(r,async()=>await nf(e,t,n),{shouldCache:i=>!i.error})}async function nf(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Co(e,t);let r=await re(t);if(!Cs(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await rf(r,e);let i=Ss(e);if(!i)return await D(S.GITHUB_SEARCH_PULL_REQUESTS,ne.NO_VALID_PARAMETERS.code),{pull_requests:[],total_count:0,error:ne.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let s=e.sort&&e.sort!=="best-match"?e.sort:void 0,a=Math.min(e.limit||30,100),c=e.page||1,l=i,d=await r.rest.search.issuesAndPullRequests({q:i,sort:s,order:e.order||"desc",per_page:a,page:c}),u=d.data.items?.filter(P=>!!P.pull_request)||[],m=await Promise.all(u.map(async P=>await ga(P,e,r))),p=m.reduce((P,x)=>P+(ee(x)??0),0),f=m.map(P=>fn(P,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:e.charOffset,charLength:e.charLength})),h=d.data.total_count,y=Math.min(h,1e3),b=Math.min(Math.ceil(y/a),10),g=Math.min(c,Math.max(1,b)),C=g<b,T=Math.min(y,b*a);return{pull_requests:f,total_count:d.data.total_count,effectiveQuery:l,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:g,totalPages:b,perPage:a,totalMatches:y,reportedTotalMatches:h,reachableTotalMatches:T,totalMatchesKind:"reported",totalMatchesCapped:h>y,hasMore:C},rawResponseChars:G(d.data)+p}}catch(r){if(Ct(r))return Sa(e);let o=Z(r);return await D(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PULL_REQUEST_SEARCH_FAILED.code),ba(o,ne.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function rf(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await qn(m,t,e))),c=a.reduce((m,p)=>m+(ee(p)??0),0),l=a.map(m=>fn(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),d=s.data.length===o,u=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:d?i+1:i,perPage:o,totalMatches:u+(d?1:0),reachableTotalMatches:u,totalMatchesKind:d?"lowerBound":"exact",hasMore:d},rawResponseChars:G(s.data)+c}}catch(n){if(Ct(n))return Sa(t);let r=Z(n);return await D(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PULL_REQUEST_LIST_FAILED.code),ba(r,ne.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}function of(e){return e?e.includes('rel="next"'):!1}function Pa(e,t){if(e)return!t||e.length<=t?e:e.slice(0,t)}async function Ea(e,t){try{let n=await re(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=of(i),a=o.data.map(d=>{let u=d.commit.author,m=d.commit.committer,p=m?.date??u?.date??"",f=d.commit.message,h=f.split(`
|
|
23
|
-
`)[0]??f;return{sha:d.sha,date:p,message:f,messageHeadline:h,url:d.html_url,author:{name:u?.name??"unknown",email:u?.email??"",...d.author?.login?{login:d.author.login}:{}},...m?{committer:{name:m.name??"unknown",email:m.email??"",...d.committer?.login?{login:d.committer.login}:{}}}:{}}}),c={page:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await Promise.all(a.map(async(d,u)=>{try{let m=o.data[u]?.sha??d.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let f=e.path,h=p.data.files?.find(y=>y.filename===f||y.previous_filename===f);if(h)return{...d,additions:h.additions,deletions:h.deletions,status:h.status,...h.patch!==void 0?{patch:Pa(h.patch,e.charLength)}:{},...h.previous_filename?{previousFilename:h.previous_filename}:{}}}else{let f=e.path,h=(p.data.files??[]).filter(y=>!f||y.filename.startsWith(f)).map(y=>({filename:y.filename,status:y.status,additions:y.additions,deletions:y.deletions,...y.patch!==void 0?{patch:Pa(y.patch,e.charLength)}:{},...y.previous_filename?{previousFilename:y.previous_filename}:{}}));return{...d,files:h}}}catch{}return d}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return Z(n)}}var Ta=30;function wa(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 xa(e,t,n){let r=Ee("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await Te(r,async()=>await af(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function sf(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch{try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){return Z(p)}}let a=i.map(p=>{let h=p.full_name.split("/"),y=h[0]||"",b=h[1]||"";return{owner:y,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description.length>150?p.description.substring(0,150)+"...":p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...wa(p)}}),c=a.length,l=c===n,d=(r-1)*n+c,u=s??d+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:u,reachableTotalMatches:d,totalMatchesKind:m,hasMore:l}},status:200,rawResponseChars:G(i)}}async function af(e,t){try{let n=await re(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await sf({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=bs(e);if(!i.trim())return await D(S.GITHUB_SEARCH_REPOSITORIES,ne.QUERY_EMPTY.code),{error:ne.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Ta,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let d=await n.rest.search.repos(c),u=d.data.items.map(g=>{let T=g.full_name.split("/"),P=T[0]||"",x=T[1]||"";return{owner:P,repo:x,defaultBranch:g.default_branch,stars:g.stargazers_count||0,description:g.description?g.description.length>150?g.description.substring(0,150)+"...":g.description:"No description",url:g.html_url,createdAt:g.created_at,updatedAt:g.updated_at,pushedAt:g.pushed_at,visibility:g.visibility,...g.topics&&g.topics.length>0&&{topics:g.topics},...g.forks_count&&g.forks_count>0&&{forksCount:g.forks_count},...g.open_issues_count&&g.open_issues_count>0&&{openIssuesCount:g.open_issues_count},...g.language&&{language:g.language},...wa(g)}}),m=d.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),h=Math.min(a,Math.max(1,f)),y=h<f,b=Math.min(p,f*s);return{data:{repositories:u,pagination:{currentPage:h,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:y}},status:200,headers:$n(d.headers),rawResponseChars:G(d.data)}}catch(n){if(Ct(n)){let r=Math.min(e.limit||Ta,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}import{RequestError as uf}from"octokit";var Et={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function cf(e,t){return t?e>5e4?[`Response ~${e.toLocaleString()} tokens \u2014 exceeds typical context. Reduce charLength or refine the query.`]:e>3e4?[`Response ~${e.toLocaleString()} tokens \u2014 approaching context limit. Consider reducing charLength.`]:[]:[]}function lf(e){if(e.hasMore&&e.nextCharOffset!==void 0){let t=e.charOffset+1,n=e.charOffset+e.charLength;return[`Page ${e.currentPage}/${e.totalPages} (chars ${t}-${n} of ${e.totalChars}). Next: charOffset=${e.nextCharOffset}`]}return[]}function _a(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...cf(e.estimatedTokens,n)),o.push(...lf(e)),o}function er(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function Aa(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:E,...w}=e;return w}let r=t.itemsPerPage??Et.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),d=Object.create(null),u=e.path==="/"?"":e.path,m=E=>{let w=E;u&&E.startsWith(u)&&(w=E.slice(u.length),w.startsWith("/")&&(w=w.slice(1)));let O=w.lastIndexOf("/");return O===-1?".":w.slice(0,O)},p=E=>{let w=E.lastIndexOf("/");return w===-1?E:E.slice(w+1)};for(let E of l){let w=m(E.path);d[w]||(d[w]={files:[],folders:[]});let O=p(E.path);E.type==="file"?d[w].files.push(O):d[w].folders.push(O)}for(let E of Object.keys(d)){let w=d[E];w&&(w.files.sort(),w.folders.sort())}let f=Object.create(null),h=Object.keys(d).sort((E,w)=>E==="."?-1:w==="."?1:E.localeCompare(w));for(let E of h){let w=d[E];w&&(f[E]=w)}let y=l.filter(E=>E.type==="file").length,b=l.filter(E=>E.type==="dir").length,g=n.filter(E=>E.type==="file").length,C=n.filter(E=>E.type==="dir").length,T=o<s,P={currentPage:o,totalPages:s,hasMore:T,entriesPerPage:r,totalEntries:i},x=er(P,{owner:e.owner,repo:e.repo,branch:e.branch,path:u,depth:t.maxDepth??1,pageFiles:y,pageFolders:b,allFiles:g,allFolders:C}),I,Q=e._cachedFileSizeMap;if(Q){let E=new Set(l.filter($=>$.type==="file").map($=>$.path)),w=e.path==="/"?"":e.path,O=Object.create(null);for(let[$,M]of Object.entries(Q))for(let[N,se]of Object.entries(M)){let ce=$==="."?w?`${w}/${N}`:N:w?`${w}/${$}/${N}`:`${$}/${N}`;E.has(ce)&&(O[$]||(O[$]=Object.create(null)),O[$][N]=se)}Object.keys(O).length>0&&(I=O)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:g,totalFolders:C,truncated:T,filtered:!0,originalCount:i},structure:f,...I!==void 0&&{fileSizeMap:I},...Q!==void 0&&{_cachedFileSizeMap:Q},pagination:P,hints:x,rawResponseChars:e.rawResponseChars}}async function Po(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return U([],0);a.add(o);try{let c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r}),l=G(c.data),u=(Array.isArray(c.data)?c.data:[c.data]).map(p=>({name:p.name,path:p.path,type:p.type,size:"size"in p?p.size:void 0,download_url:"download_url"in p?p.download_url:void 0,url:p.url,html_url:p.html_url,git_url:p.git_url,sha:p.sha})),m=[...u];if(i<s){let p=u.filter(h=>h.type==="dir"),f=3;for(let h=0;h<p.length;h+=f){let b=p.slice(h,h+f).map(async C=>{try{let T=await Po(e,t,n,r,C.path,i+1,s,a);return l+=ee(T)??0,T}catch{return[]}});(await Promise.all(b)).forEach(C=>{m.push(...C)})}}return U(m,l)}catch{return U([],0)}}var tr=S.GITHUB_VIEW_REPO_STRUCTURE;async function df(e,t,n,r,o,i){let s;try{s=o??await $e(t,n,i)}catch(a){let c=Z(a);return await D(tr,We.NOT_FOUND.code),{error:We.NOT_FOUND.message(t,n,c.error),status:c.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s}}catch(a){if(!(a instanceof uf&&a.status===404)){let l=Z(a);return await D(tr,We.ACCESS_FAILED.code),{error:We.ACCESS_FAILED.message(t,n,l.error),status:l.status,rateLimitRemaining:l.rateLimitRemaining,rateLimitReset:l.rateLimitReset,retryAfter:l.retryAfter}}let c=Z(a);return await D(tr,We.PATH_NOT_FOUND.code),{error:We.PATH_NOT_FOUND.message(r,t,n,s),status:c.status}}}function pf(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 mf(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 La(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function Oa(e,t,n){let r=Ee("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await Te(r,async()=>await ff({...e,itemsPerPage:e.itemsPerPage??Et.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Aa(o,e):o}async function ff(e,t){try{let n=await re(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await df(n,r,o,c,i,t);if("error"in l)return l;let{data:d,workingBranch:u,repoDefaultBranch:m}=l,p=G(d),f=Array.isArray(d)?d:[d],h=pf(f);if(a>1){let V=await Po(n,r,o,u,c,1,a);p+=ee(V)??0,h=[...h,...V].filter((Y,fe,_e)=>_e.findIndex(Ve=>Ve.path===Y.path)===fe)}let y=h.filter(V=>V.type==="dir"?!an(V.name):!Ut(V.path));y.sort((V,k)=>{if(V.type!==k.type)return V.type==="dir"?-1:1;let Y=V.path.split("/").length,fe=k.path.split("/").length;return Y!==fe?Y-fe:V.path.localeCompare(k.path)});let b=e.itemsPerPage??Et.ENTRIES_PER_PAGE,g=e.page??1,C=y.length,T=Math.max(1,Math.ceil(C/b)),P=(g-1)*b,x=Math.min(P+b,C),I=y.slice(P,x),Q=mf(I,c),E=e.includeSizes===!0?La(y,c):void 0,w=E!==void 0?La(I,c):void 0,O=I.filter(V=>V.type==="file").length,$=I.filter(V=>V.type==="dir").length,M=y.filter(V=>V.type==="file").length,N=y.filter(V=>V.type==="dir").length,se=g<T,ce={currentPage:g,totalPages:T,hasMore:se,entriesPerPage:b,totalEntries:C},le=er(ce,{owner:r,repo:o,branch:u,path:c,depth:a,pageFiles:O,pageFolders:$,allFiles:M,allFolders:N});return{owner:r,repo:o,branch:u,...m!==void 0&&{defaultBranch:m},path:c||"/",apiSource:!0,summary:{totalFiles:M,totalFolders:N,truncated:se,filtered:!0,originalCount:y.length},structure:Q,...w!==void 0&&{fileSizeMap:w},...E!==void 0&&{_cachedFileSizeMap:E},pagination:ce,hints:le,rawResponseChars:p,_cachedItems:y.map(V=>({path:V.path,type:V.type}))}}catch(n){let r=Z(n);return await D(tr,We.STRUCTURE_EXPLORATION_FAILED.code),{error:We.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var Ia={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};function Tt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function hf(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function gf(e){return!!(e&&typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"full_name"in e&&typeof e.full_name=="string"&&"private"in e&&typeof e.private=="boolean")}function pe(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 yf(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 nt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:yf(e)}}function nr(e){return Rf(e)?nt({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 Rf(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||bf(n)}function bf(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function ka(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 Sf(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ka(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope}}function Cf(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ka(e.pagination)},nonExistentScope:e.nonExistentScope}}async function va(e,t,n=pe){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await As(s,t);return Tt(a)?nt(a):a.data?{data:Sf(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 Fa(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await xa(n,t);return"error"in r?nr(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:Cf(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??G(r.data)}}function Ef(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:Tf(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function Tf(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 Ma(e,t,n=pe){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await ea(i,t);if(Tt(s))return nt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:Ef(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??G(s.data),...a?.length?{hints:a}:{}}}function xf(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function _f(e,t,n=pe){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...xf(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Na(e,t,n=pe){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Ca(s,t);return a.error?nt({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:_f(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??G(a)}}function Lf(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 Ha(e,t,n=pe){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Oa(i,t);return"error"in s?nr(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:Lf(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??G(s)}}var rr=class{type="github";capabilities=Ia.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await va(t,this.authInfo,pe)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Ma(t,this.authInfo,pe)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Fa(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Na(t,this.authInfo,pe)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Ha(t,this.authInfo,pe)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=pe(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return $e(n,r,this.authInfo)}handleError(t){let n=Z(t);return nt(n)}};import{createHash as If}from"crypto";var kf=3600*1e3,Eo=20,Qe=new Map;function Da(e){return Date.now()-e.createdAt<kf}function vf(){for(let[e,t]of Qe.entries())Da(t)||Qe.delete(e);if(Qe.size>Eo){let e=[...Qe.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Qe.size-Eo;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Qe.delete(r[0])}}}function Ff(e){return e?If("sha256").update(e).digest("hex").slice(0,16):"default"}function Mf(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 Nf(e,t){let n=Mf(t?.baseUrl||"default"),r=Ff(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function To(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=Nf(e,t),r=Qe.get(n);if(r&&Da(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Qe.delete(n),Qe.size>=Eo&&vf();let o=new rr({...t,type:e}),i=Date.now();return Qe.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function Mx(){Qe.clear()}async function Ga(){try{return To("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}
|
|
24
|
-
`),[{provider:"github",ok:!1,error:t}]}}import{maskSensitiveData as
|
|
25
|
-
`}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:
|
|
26
|
-
`}return{type:"text",text
|
|
22
|
+
`).trim()}async function Pl(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Cl(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=O.minifyMarkdownCore(Es(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Ps.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return l>0&&m.push(`${l} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:U([],0)}}}async function El(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Ts(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return U(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Ps.sanitizeContent(O.minifyMarkdownCore(Es(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return U([],0)}}async function Tl(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Cl(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=O.minifyMarkdownCore(Es(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Ps.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return l>0&&m.push(`${l} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:U([],0)}}}async function xl(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Cs(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:u,repo:l}=Tr(t);if(u&&l){let d=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(d.data&&(s+=N(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Ao(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Ao(t))){let m=await _l(u,l,e.number);m&&(s+=ne(m)??0,m.files=wo(m.files,t),o.file_changes=m)}}}catch(u){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let a=hl(t),c=yl(t);if(a||c){let{owner:u,repo:l}=Tr(t);if(u&&l){let d=Sl(t),m=()=>Promise.resolve({comments:U([],0)}),[{comments:p,note:f},{comments:g,note:h}]=await Promise.all([a?Pl(n,u,l,e.number,d):m(),c?Tl(n,u,l,e.number,d):m()]);o.comments=[...p,...g],s+=(ne(p)??0)+(ne(g)??0);let R=[f,h].filter(b=>typeof b=="string");R.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...R])}}if(bl(t))try{let{owner:u,repo:l}=Tr(t);if(u&&l){let d=await El(n,u,l,e.number);s+=ne(d)??0,o.reviews=d}}catch(u){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(Rl(t))try{let{owner:u,repo:l}=Tr(t);if(u&&l){let d=await wl(u,l,e.number,t);d&&(s+=ne(d)??0,o.commits=d)}}catch(u){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return U(o,s)}async function Ts(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=N(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function _l(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Ts(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U({total_count:i.length,files:i},s)}async function jy(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Ts(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U(i,s)}async function $y(e,t,n,r){try{let i=await(await ie(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return U(i.data.files||[],i.data)}catch{return null}}async function wl(e,t,n,r,o){let i=await jy(e,t,n,o);if(!i)return null;let s=ne(i)??0,a=[...i].sort((u,l)=>{let d=u.commit.author?.date?new Date(u.commit.author.date).getTime():0;return(l.commit.author?.date?new Date(l.commit.author.date).getTime():0)-d}),c=await Promise.all(a.map(async u=>{let l=await $y(e,t,u.sha,o),d=[];return l&&(s+=ne(l)??0,d=wo(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:d}}));return U(c,s)}async function Lo(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Cs(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,Ao(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ao(t))try{let d=await _l(a,c,e.number,r);d&&(s+=ne(d)??0,d.files=wo(d.files,t),o.file_changes=d)}catch(d){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(d)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let u=hl(t),l=yl(t);if(u||l){let d=Sl(t),m=()=>Promise.resolve({comments:U([],0)}),[{comments:p,note:f},{comments:g,note:h}]=await Promise.all([u?Pl(n,a,c,e.number,d):m(),l?Tl(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(ne(p)??0)+(ne(g)??0);let R=[f,h].filter(b=>typeof b=="string");R.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...R])}if(bl(t))try{let d=await El(n,a,c,e.number);s+=ne(d)??0,o.reviews=d}catch(d){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(d)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(Rl(t))try{let d=await wl(a,c,e.number,t,r);d&&(s+=ne(d)??0,o.commits=d)}catch(d){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(d)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return U(o,s)}function Vy(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function SI(e,t,n){let r=_e("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode},n);return await we(r,async()=>await xs(e,t),{shouldCache:i=>!i.error})}async function xs(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PR_REQUIRED_PARAMS.code),{pull_requests:[],total_count:0,error:oe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PR_SINGLE_VALUES.code),{pull_requests:[],total_count:0,error:oe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ie(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{pull_requests:[Er(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:N(s.data)+(ne(c)??0)}}catch(i){let s=Z(i);return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PULL_REQUEST_FETCH_FAILED.code),Vy(s,oe.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 Al(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Ll(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Ol(e,t,n){let r=_e("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await we(r,async()=>await Wy(e,t,n),{shouldCache:i=>!i.error})}async function Wy(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await xs(e,t);let r=await ie(t);if(!Ou(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Ky(r,e);let i=Lu(e);if(!i)return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.NO_VALID_PARAMETERS.code),{pull_requests:[],total_count:0,error:oe.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let s=e.sort&&e.sort!=="best-match"?e.sort:void 0,a=Math.min(e.limit||30,100),c=e.page||1,u=i,l=await r.rest.search.issuesAndPullRequests({q:i,sort:s,order:e.order||"desc",per_page:a,page:c}),d=l.data.items?.filter(C=>!!C.pull_request)||[],m=await Promise.all(d.map(async C=>await xl(C,e,r))),p=m.reduce((C,_)=>C+(ne(_)??0),0),f=m.map(C=>Er(C,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:e.charOffset,charLength:e.charLength})),g=l.data.total_count,h=Math.min(g,1e3),R=Math.min(Math.ceil(h/a),10),b=Math.min(c,Math.max(1,R)),P=b<R,x=Math.min(h,R*a);return{pull_requests:f,total_count:l.data.total_count,effectiveQuery:u,...l.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:b,totalPages:R,perPage:a,totalMatches:h,reportedTotalMatches:g,reachableTotalMatches:x,totalMatchesKind:"reported",totalMatchesCapped:g>h,hasMore:P,...P?{nextPage:b+1}:{}},rawResponseChars:N(l.data)+p}}catch(r){if($t(r))return Ll(e);let o=Z(r);return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PULL_REQUEST_SEARCH_FAILED.code),Al(o,oe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function Ky(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await Lo(m,t,e))),c=a.reduce((m,p)=>m+(ne(p)??0),0),u=a.map(m=>Er(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),l=s.data.length===o,d=(i-1)*o+u.length;return{pull_requests:u,total_count:u.length,pagination:{currentPage:i,totalPages:l?i+1:i,perPage:o,totalMatches:d+(l?1:0),reachableTotalMatches:d,totalMatchesKind:l?"lowerBound":"exact",hasMore:l,...l?{nextPage:i+1}:{}},rawResponseChars:N(s.data)+c}}catch(n){if($t(n))return Ll(t);let r=Z(n);return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PULL_REQUEST_LIST_FAILED.code),Al(r,oe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}function Yy(e){return e?e.includes('rel="next"'):!1}function Il(e,t){if(e)return!t||e.length<=t?e:e.slice(0,t)}async function kl(e,t){try{let n=await ie(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=Yy(i),a=o.data.map(l=>{let d=l.commit.author,m=l.commit.committer,p=m?.date??d?.date??"",f=l.commit.message,g=f.split(`
|
|
23
|
+
`)[0]??f;return{sha:l.sha,date:p,message:f,messageHeadline:g,url:l.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...l.author?.login?{login:l.author.login}:{}},...m?{committer:{name:m.name??"unknown",email:m.email??"",...l.committer?.login?{login:l.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let u=await Promise.all(a.map(async(l,d)=>{try{let m=o.data[d]?.sha??l.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let f=e.path,g=p.data.files?.find(h=>h.filename===f||h.previous_filename===f);if(g){let h=g.patch!==void 0?Il(g.patch,e.charLength):void 0;return{...l,additions:g.additions,deletions:g.deletions,status:g.status,...h!==void 0?{patch:h,diff:Pr(h)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let f=e.path,g=(p.data.files??[]).filter(h=>!f||h.filename.startsWith(f)).map(h=>{let R=h.patch!==void 0?Il(h.patch,e.charLength):void 0;return{filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,...R!==void 0?{patch:R,diff:Pr(R)}:{},...h.previous_filename?{previousFilename:h.previous_filename}:{}}});return{...l,files:g}}}catch{}return l}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:u,pagination:c},status:200}}catch(n){return Z(n)}}var vl=30;function Fl(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 Ml(e,t,n){let r=_e("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await we(r,async()=>await Jy(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Xy(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch{try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){return Z(p)}}let a=i.map(p=>{let g=p.full_name.split("/"),h=g[0]||"",R=g[1]||"";return{owner:h,repo:R,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description.length>150?p.description.substring(0,150)+"...":p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...Fl(p)}}),c=a.length,u=c===n,l=(r-1)*n+c,d=s??l+(u?1:0),m=s!==void 0||!u?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:u?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:l,totalMatchesKind:m,hasMore:u,...u?{nextPage:r+1}:{}}},status:200,rawResponseChars:N(i)}}async function Jy(e,t){try{let n=await ie(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await Xy({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=Au(e);if(!i.trim())return await M(S.GITHUB_SEARCH_REPOSITORIES,oe.QUERY_EMPTY.code),{error:oe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||vl,100),a=e.page||1,c={q:i,per_page:s,page:a},u=["stars","forks","help-wanted-issues","updated"];e.sort&&u.includes(e.sort)&&(c.sort=e.sort);let l=await n.rest.search.repos(c),d=l.data.items.map(b=>{let x=b.full_name.split("/"),C=x[0]||"",_=x[1]||"";return{owner:C,repo:_,defaultBranch:b.default_branch,stars:b.stargazers_count||0,description:b.description?b.description.length>150?b.description.substring(0,150)+"...":b.description:"No description",url:b.html_url,createdAt:b.created_at,updatedAt:b.updated_at,pushedAt:b.pushed_at,visibility:b.visibility,...b.topics&&b.topics.length>0&&{topics:b.topics},...b.forks_count&&b.forks_count>0&&{forksCount:b.forks_count},...b.open_issues_count&&b.open_issues_count>0&&{openIssuesCount:b.open_issues_count},...b.language&&{language:b.language},...Fl(b)}}),m=l.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,f)),h=g<f,R=Math.min(p,f*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:R,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:h,...h?{nextPage:g+1}:{}}},status:200,headers:bo(l.headers),rawResponseChars:N(l.data)}}catch(n){if($t(n)){let r=Math.min(e.limit||vl,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}import{RequestError as nR}from"octokit";var Kt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function Zy(e,t){return t?e>5e4?[`Response ~${e.toLocaleString()} tokens \u2014 exceeds typical context. Reduce charLength or refine the query.`]:e>3e4?[`Response ~${e.toLocaleString()} tokens \u2014 approaching context limit. Consider reducing charLength.`]:[]:[]}function qy(e){if(e.hasMore&&e.nextCharOffset!==void 0){let t=e.charOffset+1,n=e.charOffset+e.charLength;return[`Page ${e.currentPage}/${e.totalPages} (chars ${t}-${n} of ${e.totalChars}). Next: charOffset=${e.nextCharOffset}`]}return[]}function ZI(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...Zy(e.estimatedTokens,n)),o.push(...qy(e)),o}function Oo(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function Nl(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:w,...A}=e;return A}let r=t.itemsPerPage??Kt.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),u=n.slice(a,c),l=Object.create(null),d=e.path==="/"?"":e.path,m=w=>{let A=w;d&&w.startsWith(d)&&(A=w.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let Q=A.lastIndexOf("/");return Q===-1?".":A.slice(0,Q)},p=w=>{let A=w.lastIndexOf("/");return A===-1?w:w.slice(A+1)};for(let w of u){let A=m(w.path);l[A]||(l[A]={files:[],folders:[]});let Q=p(w.path);w.type==="file"?l[A].files.push(Q):l[A].folders.push(Q)}for(let w of Object.keys(l)){let A=l[w];A&&(A.files.sort(),A.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((w,A)=>w==="."?-1:A==="."?1:w.localeCompare(A));for(let w of g){let A=l[w];A&&(f[w]=A)}let h=u.filter(w=>w.type==="file").length,R=u.filter(w=>w.type==="dir").length,b=n.filter(w=>w.type==="file").length,P=n.filter(w=>w.type==="dir").length,x=o<s,C={currentPage:o,totalPages:s,hasMore:x,...x?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=Oo(C,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:h,pageFolders:R,allFiles:b,allFolders:P}),I,j=e._cachedFileSizeMap;if(j){let w=new Set(u.filter(se=>se.type==="file").map(se=>se.path)),A=e.path==="/"?"":e.path,Q=Object.create(null);for(let[se,$]of Object.entries(j))for(let[D,Re]of Object.entries($)){let ue=se==="."?A?`${A}/${D}`:D:A?`${A}/${se}/${D}`:`${se}/${D}`;w.has(ue)&&(Q[se]||(Q[se]=Object.create(null)),Q[se][D]=Re)}Object.keys(Q).length>0&&(I=Q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:b,totalFolders:P,truncated:x,filtered:!0,originalCount:i},structure:f,...I!==void 0&&{fileSizeMap:I},...j!==void 0&&{_cachedFileSizeMap:j},pagination:C,hints:_,rawResponseChars:e.rawResponseChars}}import{RequestError as eR}from"octokit";var Hl=Symbol.for("octocode.recursiveFetchFailures"),tR=new Set([401,403,429]);function Dl(e){return e instanceof eR&&tR.has(e.status)}function _s(e,t){try{Object.defineProperty(e,Hl,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function ws(e){if(typeof e!="object"||e===null)return 0;let t=e[Hl];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function As(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return _s(U([],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(Dl(f))throw f;return _s(U([],0),1)}let u=N(c.data),d=(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})),m=[...d],p=0;if(i<s){let f=d.filter(h=>h.type==="dir"),g=3;for(let h=0;h<f.length;h+=g){let R=f.slice(h,h+g),b=await Promise.allSettled(R.map(P=>As(e,t,n,r,P.path,i+1,s,a)));for(let P of b)if(P.status==="fulfilled"){let x=P.value;u+=ne(x)??0,p+=ws(x),m.push(...x)}else{if(Dl(P.reason))throw P.reason;p+=1}}}return _s(U(m,u),p)}var Io=S.GITHUB_VIEW_REPO_STRUCTURE;async function rR(e,t,n,r,o,i){let s;try{s=o??await Ge(t,n,i)}catch(a){let c=Z(a);return await M(Io,et.NOT_FOUND.code),{error:et.NOT_FOUND.message(t,n,c.error),status:c.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s}}catch(a){if(!(a instanceof nR&&a.status===404)){let u=Z(a);return await M(Io,et.ACCESS_FAILED.code),{error:et.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let c=Z(a);return await M(Io,et.PATH_NOT_FOUND.code),{error:et.PATH_NOT_FOUND.message(r,t,n,s),status:c.status}}}function oR(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function iR(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 u=c.lastIndexOf("/");return u===-1?".":c.slice(0,u)},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 u=o(a.path);a.type==="file"?n[c].files.push(u):n[c].folders.push(u)}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 Gl(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function Ul(e,t,n){let r=_e("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await we(r,async()=>await sR({...e,itemsPerPage:e.itemsPerPage??Kt.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Nl(o,e):o}async function sR(e,t){try{let n=await ie(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),u=await rR(n,r,o,c,i,t);if("error"in u)return u;let{data:l,workingBranch:d,repoDefaultBranch:m}=u,p=N(l),f=Array.isArray(l)?l:[l],g=oR(f),h=0;if(a>1){let V=await As(n,r,o,d,c,1,a);h=ws(V),p+=ne(V)??0,g=[...g,...V].filter((Mn,Dr,Dm)=>Dm.findIndex(Hm=>Hm.path===Mn.path)===Dr)}let R=g.filter(V=>V.type==="dir"?!cr(V.name):!xn(V.path));R.sort((V,qe)=>{if(V.type!==qe.type)return V.type==="dir"?-1:1;let Mn=V.path.split("/").length,Dr=qe.path.split("/").length;return Mn!==Dr?Mn-Dr:V.path.localeCompare(qe.path)});let b=e.itemsPerPage??Kt.ENTRIES_PER_PAGE,P=e.page??1,x=R.length,C=Math.max(1,Math.ceil(x/b)),_=(P-1)*b,I=Math.min(_+b,x),j=R.slice(_,I),w=iR(j,c),A=e.includeSizes===!0?Gl(R,c):void 0,Q=A!==void 0?Gl(j,c):void 0,se=j.filter(V=>V.type==="file").length,$=j.filter(V=>V.type==="dir").length,D=R.filter(V=>V.type==="file").length,Re=R.filter(V=>V.type==="dir").length,ue=P<C,at={currentPage:P,totalPages:C,hasMore:ue,...ue?{nextPage:P+1}:{},entriesPerPage:b,totalEntries:x},en=Oo(at,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:se,pageFolders:$,allFiles:D,allFolders:Re});return h>0&&en.unshift(`Partial tree: ${h} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...m!==void 0&&{defaultBranch:m},path:c||"/",apiSource:!0,summary:{totalFiles:D,totalFolders:Re,truncated:ue,filtered:!0,originalCount:R.length},structure:w,...Q!==void 0&&{fileSizeMap:Q},...A!==void 0&&{_cachedFileSizeMap:A},pagination:at,hints:en,rawResponseChars:p,_cachedItems:R.map(V=>({path:V.path,type:V.type}))}}catch(n){let r=Z(n);return await M(Io,et.STRUCTURE_EXPLORATION_FAILED.code),{error:et.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var Bl={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};function Yt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function aR(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function cR(e){return!!(e&&typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"full_name"in e&&typeof e.full_name=="string"&&"private"in e&&typeof e.private=="boolean")}function de(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function uR(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 gt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:uR(e)}}function ko(e){return lR(e)?gt({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 lR(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||dR(n)}function dR(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function zl(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 pR(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,...zl(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function fR(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,...zl(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Ql(e,t,n=de){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await Nu(s,t);return Yt(a)?gt(a):a.data?{data:pR(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function jl(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await Ml(n,t);return"error"in r?ko(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:fR(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??N(r.data)}}function gR(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:hR(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function hR(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 $l(e,t,n=de){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await ul(i,t);if(Yt(s))return gt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:gR(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s.data),...a?.length?{hints:a}:{}}}function RR(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function bR(e,t,n=de){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...RR(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Vl(e,t,n=de){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Ol(s,t);return a.error?gt({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:bR(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a)}}function CR(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 Wl(e,t,n=de){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ul(i,t);return"error"in s?ko(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:CR(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s)}}var vo=class{type="github";capabilities=Bl.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Ql(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await $l(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await jl(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Vl(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Wl(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=de(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ge(n,r,this.authInfo)}handleError(t){let n=Z(t);return gt(n)}};import{createHash as ER}from"crypto";var TR=3600*1e3,Ls=20,Je=new Map;function Kl(e){return Date.now()-e.createdAt<TR}function xR(){for(let[e,t]of Je.entries())Kl(t)||Je.delete(e);if(Je.size>Ls){let e=[...Je.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Je.size-Ls;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Je.delete(r[0])}}}function _R(e){return e?ER("sha256").update(e).digest("hex").slice(0,16):"default"}function wR(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 AR(e,t){let n=wR(t?.baseUrl||"default"),r=_R(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Os(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=AR(e,t),r=Je.get(n);if(r&&Kl(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Je.delete(n),Je.size>=Ls&&xR();let o=new vo({...t,type:e}),i=Date.now();return Je.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function Yk(){Je.clear()}async function Yl(){try{return Os("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}
|
|
24
|
+
`),[{provider:"github",ok:!1,error:t}]}}import{maskSensitiveData as Is}from"@octocodeai/octocode-engine/mask";import{ContentSanitizer as ks}from"@octocodeai/octocode-engine/contentSanitizer";var LR={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};function Xl(){try{return ae().output.format}catch{return"yaml"}}function nv(e){if(e==null||typeof e!="object")return{content:[{type:"text",text:`error: "Invalid result options"
|
|
25
|
+
`}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:xr({data:t,instructions:n})}],isError:!!r}}var Fo={system(e,t=1){return{type:"text",text:e,annotations:{audience:["assistant"],priority:t,role:"system"}}},assistant(e,t=.8){return{type:"text",text:e,annotations:{audience:["assistant","user"],priority:t,role:"assistant"}}},user(e,t=.6){return{type:"text",text:e,annotations:{audience:["user"],priority:t,role:"user"}}},data(e,t){let n=t??Xl(),r;try{r=n==="yaml"?O.jsonToYamlString(wn(e)):JSON.stringify(wn(e),null,2)}catch{r=`error: "Data serialization failed"
|
|
26
|
+
`}return{type:"text",text:IR(r),annotations:{audience:["assistant"],priority:.3,role:"assistant"}}}},Mo={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};function No(e){let t=[],{system:n,assistant:r,user:o,data:i,isError:s}=e;if(n){let a=[];if(n.instructions&&a.push(n.instructions),n.pagination){let{currentPage:c,totalPages:u,hasMore:l}=n.pagination;a.push(`Page ${c}/${u}${l?" (more available)":""}`)}n.warnings?.length&&a.push(`\u26A0\uFE0F Warnings:
|
|
27
27
|
${n.warnings.map(c=>`- ${c}`).join(`
|
|
28
28
|
`)}`),n.hints?.length&&a.push(`Hints:
|
|
29
29
|
${n.hints.map(c=>`- ${c}`).join(`
|
|
30
|
-
`)}`),a.length>0&&t.push(
|
|
30
|
+
`)}`),a.length>0&&t.push(Fo.system(a.join(`
|
|
31
31
|
|
|
32
|
-
`)))}if(t.push(
|
|
32
|
+
`)))}if(t.push(Fo.assistant(r.summary)),r.details){let a=r.format==="json"||r.format==="yaml"?r.format:void 0;t.push(Fo.data(r.details,a))}if(o){let a=o.emoji?`${o.emoji} ${o.message}`:o.message;t.push(Fo.user(a))}return{content:t,structuredContent:OR(i),isError:!!s}}var rv={success(e,t,n){return No({system:n?{hints:n}:void 0,assistant:{summary:e},user:{message:"Operation completed",emoji:Mo.success},data:t})},empty(e,t){return No({system:{hints:t||["Try broader search terms","Check spelling"]},assistant:{summary:e},user:{message:"No results found",emoji:Mo.empty},data:{status:"empty",results:[]}})},error(e,t){return No({system:{instructions:"Tool execution failed. Error details provided for self-correction."},assistant:{summary:`Error: ${e}`},user:{message:"An error occurred",emoji:Mo.error},data:{status:"error",error:e,details:t},isError:!0})},paginated(e,t,n,r){return No({system:{pagination:{currentPage:n.page,totalPages:n.total,hasMore:n.hasMore},hints:r},assistant:{summary:e},user:{message:`Page ${n.page} of ${n.total}`,emoji:n.hasMore?"\u{1F4C4}":Mo.success},data:t})}};function OR(e){if(e==null)return;let t=wn(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?ot(t):ot({data:t})}function IR(e){if(e==null||typeof e!="string")return"";let t=ks.sanitizeContent(e);return Is(t.content)}function ot(e){if(e==null)return e;if(typeof e=="string"){let t=ks.sanitizeContent(e);return Is(t.content)}if(Array.isArray(e))return e.map(t=>ot(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ot(r);return t}return e}function ov(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(`
|
|
33
33
|
|
|
34
|
-
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function gn(e,t){let n=Qt(e)??{},r=$a(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;r==="json"?i=JSON.stringify(ar(n,t||o),null,2):i=z.jsonToYamlString(n,{keysPriority:t||o});let s=xo.sanitizeContent(i);return wo(s.content)}function ar(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>ar(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=ar(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=ar(n[o],t));return r}var Uf=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]);function Bf(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=>Uf.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Qt(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=>Qt(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(Bf(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Qt(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{z as cr}from"zod";function F(e,t){return cr.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,cr.number().int().min(e).max(t))}var q=F(1,1e3).optional().default(1),jt=F(0,100).optional(),Vt=F(1,1e9).optional(),zf={responseCharOffset:F(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:F(1,5e4).optional().describe("Full-response char window.")};function X(e,t={}){let{maxQueries:n=5}=t;return cr.object({queries:cr.array(e).min(1).max(n).describe("Parallel queries."),...zf}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}import{z as he}from"zod";var Qf=he.object({currentPage:he.number(),totalPages:he.number(),hasMore:he.boolean(),charOffset:he.number(),charLength:he.number(),totalChars:he.number(),nextCharOffset:he.number().optional()}).optional(),xe={hints:he.array(he.string()).optional(),base:he.string().optional(),shared:he.record(he.string(),he.union([he.string(),he.number(),he.boolean()])).optional(),responsePagination:Qf};function Jx(e){return e.extend(xe)}var _o={empty:(e={})=>{let t=e;if(t.mode==="structural")return["No structural matches. The pattern must be a complete code fragment for the target language; use $X for a single node, $$$ARGS for a list.","For relational rules (inside/has/not), add `stopBy: end` so the sub-rule walks all ancestors/descendants \u2014 without it the rule silently matches nothing.","Verify the file extension is one the engine parses (ts/tsx/js/py/go/rs/java/c/cpp/cs/sh), and widen the path."];let n=typeof t.path=="string"?t.path:void 0,r=typeof t.langType=="string"?t.langType:typeof t.type=="string"?t.type:void 0,o=Array.isArray(t.include)?t.include:[],i=Array.isArray(t.excludeDir)?t.excludeDir:[],s=typeof t.keywords=="string"?t.keywords:void 0,a=r||o.length>0||i.length>0,c=typeof t.searchEngine=="string"?t.searchEngine:void 0;if(!s&&!n&&!a)return[];let l=a?["Remove include/exclude/langType first, then retry a shorter or literal term."]:["Try a shorter partial term, fixedString=true for literals, or search a parent directory."];return c==="grep"?["grep fallback active \u2014 perlRegex patterns (lookaheads, backreferences) unsupported; use fixedString:true or simplify the pattern.",...l]:l},error:(e={})=>e.errorType==="size_limit"?[`Too many results${e.matchCount?` (${e.matchCount} matches)`:""} \u2014 narrow, add a filter, or use fixedString=true.`]:e.errorType==="not_found"?["Path not found \u2014 verify with localViewStructure."]:[]};var Ao={empty:(e={})=>{let t=e;return(typeof t.path=="string"?t.path:void 0)?["Confirm path with `localFindFiles`."]:[]},error:(e={})=>{if(e.errorType==="size_limit"){let t=e,n=typeof t.fileSize=="number"?` (~${Math.round(t.fileSize/1024)}KB)`:"",r=typeof t.totalLines=="number"?t.totalLines:void 0,o=r?Math.max(1,r-200):void 0,i=[`File${n} too large \u2014 use matchString or startLine+endLine for a slice.`,'Or minify="symbols" for a skeleton index, then startLine/endLine.'];return o&&r&&i.push(`Tail: startLine=${o}, endLine=${r}.`),i}if(e.errorType==="directory"){let t=e;return[`${typeof t.path=="string"?`'${t.path}'`:"Path"} is a directory \u2014 use \`localViewStructure\` to explore it.`]}return e.errorType==="not_found"?["Use `localFindFiles` to locate the correct path."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]}};var Lo={empty:(e={})=>{let t=e,n=Array.isArray(t.extensions)?t.extensions.filter(i=>typeof i=="string"):[],r=typeof t.pattern=="string"?t.pattern:void 0,o=[...r?[`pattern="${r}"`]:[],...n.length>0?[`extensions=${n.join(",")}`]:[]];return o.length===0?[]:[`No entries matched ${o.join(" + ")} \u2014 remove filters or increase depth/recursive.`]},error:(e={})=>e.errorType==="not_found"?["Path must be absolute \u2014 use localFindFiles to discover the correct path."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]};var Oo={empty:(e={})=>{let t=e,n=Array.isArray(t.names)&&t.names.length>0?t.names:void 0,r=typeof t.modifiedWithin=="string"?t.modifiedWithin:void 0,o=typeof t.sizeGreater=="string"?t.sizeGreater:void 0,i=typeof t.sizeLess=="string"?t.sizeLess:void 0,s=[];return n&&s.push(`names=${JSON.stringify(n)}`),r&&s.push(`modifiedWithin="${r}"`),o&&s.push(`sizeGreater="${o}"`),i&&s.push(`sizeLess="${i}"`),s.length===0?[]:[`No metadata match for ${s.join(", ")} \u2014 remove one filter or broaden names.`,"For content text, switch to `localSearchCode`."]},error:(e={})=>e.errorType==="not_found"?["Verify path with `localViewStructure` at the parent directory."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]};var Io={empty:(e={})=>{let t=e,n=Array.isArray(t.keywords)?t.keywords:void 0,r=typeof t.owner=="string"?t.owner:void 0,o=typeof t.repo=="string"?t.repo:void 0,i=typeof t.extension=="string"||typeof t.filename=="string"||typeof t.path=="string";if(t.nonExistentScope===!0)return[`"${r&&o?`${r}/${o}`:r||"target"}" doesn't exist or isn't accessible \u2014 check spelling.`];if(e.hasOwnerRepo&&r&&o)return[i?"Remove path/filename/extension first, then retry keywords.":`No results in ${r}/${o} \u2014 large or popular repos often require narrowing: add extension, filename, or path to reduce scope. Repo may also be unindexed (new/private/recently renamed). Fall back to ghGetFileContent with a known path, or ghViewRepoStructure to discover paths.`,"GitHub code search indexes the default branch only."];let s=[];return n&&n.length===1&&typeof n[0]=="string"&&/^@[\w-]+\/[\w.-]+$|^[a-z][\w]*[-.][\w.-]+$/.test(n[0])&&s.push(`"${n[0]}" looks like a package name \u2014 try \`npmSearch\`.`),s.length===0&&n&&n.length>0&&s.push('Scope to owner/repo, split into one-keyword queries, or try a shorter exact term. For large repos (react, webpack, electron), narrow with extension="ts" or path="src".'),s},error:(e={})=>{let t=[];return e.isRateLimited&&t.push(`Rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:""}`),e.status===401&&t.push("GITHUB_TOKEN missing/expired."),e.status===403&&!e.isRateLimited&&t.push("Token lacks `repo` scope."),t}};var ko={empty:(e={})=>{let t=e;return(typeof t.path=="string"?t.path:void 0)?["Verify it's a file, not a directory \u2014 use `ghViewRepoStructure`."]:[]},error:(e={})=>{if(e.errorType==="size_limit"){let t=e,n=typeof t.fileSize=="number"?`${t.fileSize}KB `:"",r=typeof t.totalLines=="number"?t.totalLines:void 0,o=r?Math.max(1,r-200):void 0,i=[`Large file ${n}\u2014 use startLine+endLine or matchString for a slice.`,'Or minify="symbols" for a skeleton index, then startLine/endLine.'];return o&&r&&i.push(`Tail: startLine=${o}, endLine=${r}.`),i}if(e.errorType==="not_found"){let t=e;return["Verify path with `ghViewRepoStructure`.",...(typeof t.branch=="string"?t.branch:void 0)?["Omit `branch` to use the default branch."]:[]]}return e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks `repo` scope."]:[]}};var vo={empty:(e={})=>{let t=e;return t.wasFilteredToEmpty===!0?["All entries were filtered by the ignored-paths list (node_modules, .git, dist, etc.). Path is valid \u2014 navigate to a specific subdirectory."]:(typeof t.path=="string"&&t.path?t.path:void 0)?["Try the parent path, or omit `path` to list from root."]:[]},error:(e={})=>{if(e.isRateLimited)return[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`];if(e.status===401)return["GITHUB_TOKEN is missing or expired."];if(e.status===403)return["Token lacks `repo` scope."];if(e.status===404){let t=e,n=typeof t.owner=="string"?t.owner:void 0,r=typeof t.repo=="string"?t.repo:void 0;return[`${n&&r?`'${n}/${r}'`:"the repository"} not found \u2014 check spelling or use \`ghSearchRepos\`.`]}return[]}};var Fo={empty:(e={})=>{let t=e;if((typeof t.type=="string"?t.type:"prs")==="commits"){let p=typeof t.path=="string"?t.path:void 0;return p?p.endsWith("/")?[`No commits found under "${p}". Check the directory prefix or widen since/until.`]:[`No commits found for "${p}". Check path spelling or widen since/until.`,"File may have been renamed \u2014 re-query with its previous name."]:["No commits found. Try widening since/until or removing the author filter."]}let r=typeof t.state=="string"?t.state:void 0,o=typeof t.owner=="string"?t.owner:void 0,i=typeof t.repo=="string"?t.repo:void 0,s=typeof t.author=="string"?t.author:void 0,a=typeof t.query=="string"?t.query:void 0,c=typeof t.prNumber=="number"?t.prNumber:void 0,d=(Array.isArray(t.prMatch)?t.prMatch:void 0)?.includes("title")??!1,u=o&&i?`${o}/${i}`:void 0;if(c!==void 0&&u)return[`PR #${c} not found in ${u}. Verify the PR number, or search by title using keywordsToSearch with match:["title"].`];let m=[];return r&&m.push(`state=${r}`),s&&m.push(`author=${s}`),a&&m.push(`query="${a}"`),m.length===0?[]:[r==="merged"?"No merged PRs matched \u2014 widen the date range or remove author/label filters.":"Remove filters one at a time to find what is too narrow.",...a&&!d?['For title-only matching use match:["title"] with sort:"best-match".']:a?[]:["Add a keyword (keywordsToSearch) to narrow by title or body text."]]},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks repo scope \u2014 check GITHUB_TOKEN permissions."]:[]};var Mo={empty:(e={})=>{let t=e,n=typeof t.query=="string"?t.query:void 0,r=Array.isArray(t.keywords)?t.keywords:void 0,o=typeof t.language=="string"?t.language:void 0,i=typeof t.owner=="string"?t.owner:void 0,s=typeof t.topic=="string"?t.topic:void 0,a=o||i||s,c=n??(r&&r.length>0?String(r[0]):void 0);if(!c&&!a)return[];let l=[a?"Remove owner/language/topic first, then retry fewer keywords.":'Try fewer/simpler keywords, or use match:["name"] for exact-name lookup.'];return c&&/^@[\w-]+\/[\w.-]+$|^[a-z][\w]*[-.][\w.-]+$/.test(c)&&l.push(`"${c}" looks like a package \u2014 use \`npmSearch\` instead.`),l},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks `public_repo` scope."]:[]};var No={empty:(e={})=>{let t=e;return(typeof t.sparsePath=="string"?t.sparsePath:typeof t.path=="string"?t.path:void 0)?["Omit `sparsePath` to check out the full repo.","Confirm path with `ghViewRepoStructure` before cloning sparse."]:[]},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`,"Use `ghViewRepoStructure` to inspect the tree without cloning."]:e.errorType==="permission"?["Token lacks read access \u2014 verify GITHUB_TOKEN has `repo` scope."]:e.errorType==="not_found"?["Check spelling or omit `branch` to use the default branch."]:e.errorType==="timeout"?["Clone timed out \u2014 use `sparsePath` for a subdirectory only."]:[]};function jf(e){let t=[];if(e.includes("-")&&(t.push(e.replace(/-/g,"_")),t.push(e.replace(/-/g,""))),e.includes("_")&&t.push(e.replace(/_/g,"-")),e.startsWith("@")){let n=e.split("/").pop();n&&t.push(n)}return e.endsWith("js")||t.push(e+"js"),[...new Set(t)].filter(n=>n!==e).slice(0,3)}var Ho={empty:(e={})=>{let t=e,n=typeof t.name=="string"?t.name:void 0;if(!n)return[];let r=jf(n);return["Check spelling and remove any version suffix.","Not on npm? Use `ghSearchRepos` instead.",...r.length?[`Try: ${r.join(", ")}`]:[]]},error:(e={})=>e.isRateLimited?[`npm registry rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.originalError?["npm registry unreachable \u2014 use `ghSearchRepos` instead."]:[]};var Do={empty:(e={})=>{let t=typeof e.symbolName=="string"?e.symbolName:"",n=e,r=typeof n.type=="string"?n.type:void 0;return!t&&!r?[]:r==="documentSymbols"?["Verify uri with localFindFiles/localSearchCode, then retry."]:r==="references"?["references is bounded to the current package (open TS server files) \u2014 cross-package calls will not appear.",'Use type="callers" for cross-package incoming calls.']:["Re-anchor with localSearchCode to get uri+symbolName+lineHint; use documentSymbols if the symbol is ambiguous."]},error:(e={})=>e.errorType==="lsp_unavailable"?["Language server unavailable \u2014 use localSearchCode for references and localGetFileContent for source slices."]:e.errorType==="symbol_not_found"?["Run localSearchCode for the exact symbol line, then retry with updated uri+lineHint."]:[]};function mt(e,t){return t?[...{documentSymbols:["Use returned line values as lineHint for definition, references, or callers."],hover:['type="definition" to jump to source, type="callers" for cross-package usage.'],definition:['localGetFileContent for context, type="callers" for cross-package impact, type="references" for same-package usages.'],typeDefinition:['localGetFileContent for the type, type="implementation" for concrete implementations.'],implementation:['localGetFileContent for implementation, type="callers" for call sites.'],references:["groupByFile=true for compact summary, localGetFileContent for context.","Scope: bounded by files open in the TS server (current package). Use callers/callHierarchy for cross-package blast radius."],callers:["Increase depth for a wider tree, localGetFileContent for context."],callees:['Increase depth, type="definition" on returned calls for source.'],callHierarchy:["Increase depth, localGetFileContent on call sites for context."]}[e]??[]]:[...{definition:["Re-anchor with localSearchCode and retry."],hover:['Try type="definition" instead.'],typeDefinition:['Try type="hover" for the inferred type.'],references:["references is bounded to the current package (open TS server files) \u2014 cross-package calls will not appear.",'Use type="callers" for cross-package incoming calls.'],callers:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" for same-package usages instead.',"Use localSearchCode for dynamic references."],callees:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" or localSearchCode instead.',"Use localSearchCode for dynamic calls."],callHierarchy:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" for same-package usages instead.',"Use localSearchCode for dynamic references."],documentSymbols:['Use localSearchCode with "export|function|class|const" as a fallback.'],implementation:["symbolName must be a method/property of an interface or abstract class \u2014 not the class name.",'Use type="documentSymbols" to list members, then retry with a member name.']}[e]??[]]}var Go={[K.LOCAL_RIPGREP]:_o,[K.LOCAL_FETCH_CONTENT]:Ao,[K.LOCAL_VIEW_STRUCTURE]:Lo,[K.LOCAL_FIND_FILES]:Oo,[K.GITHUB_SEARCH_CODE]:Io,[K.GITHUB_FETCH_CONTENT]:ko,[K.GITHUB_VIEW_REPO_STRUCTURE]:vo,[K.GITHUB_SEARCH_PULL_REQUESTS]:Fo,[K.GITHUB_SEARCH_REPOSITORIES]:Mo,[K.GITHUB_CLONE_REPO]:No,[K.PACKAGE_SEARCH]:Ho,[Re]:Do};function $o(e){return e in Go}function Uo(e,t,n){let r=Go[e]?.[t];return r?r(n||{}).filter(i=>typeof i=="string"):[]}function oe(e,t,n){if(!$o(e))return[];let r=Uo(e,t,n);return[...new Set(r)]}function Ua(e){let t=[];if(e.scopesSuggestion&&t.push(e.scopesSuggestion),e.rateLimitRemaining!==void 0&&e.rateLimitReset!==void 0){let n=e.rateLimitReset;if(!isNaN(n)){let r=new Date(n);t.push(`Rate limit: ${e.rateLimitRemaining} remaining, resets at ${r.toISOString()}`)}}return e.retryAfter!==void 0&&t.push(`Retry after ${e.retryAfter} seconds`),t}function Vf(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function A(e,t,n={}){let{toolName:r,hintContext:o,extra:i,customHints:s,hintSourceError:a}=n,c={status:"error"},l=[];if(a&&l.push(...Ua(a)),Vf(e))c.error=e,a||l.push(...Ua(e));else if(jr(e)){if(c.error=e.message,c.errorCode=e.errorCode,r){let u=oe(r,"error",{originalError:e.message,errorType:Wf(e),...o});l.push(...u)}}else if(typeof e=="string")c.error=e;else if(e instanceof Error){let u=qi(e);if(c.error=u.message,c.errorCode=u.errorCode,r){let m=oe(r,"error",{originalError:u.message,...o});l.push(...m)}}else c.error="Unknown error occurred";s&&s.length>0&&l.push(...s),i?.hints&&Array.isArray(i.hints)&&l.push(...i.hints);let d=l.filter(u=>typeof u=="string"&&u.trim().length>0);if(d.length>0&&(c.hints=d),i){let{hints:u,...m}=i;Object.assign(c,m)}return n.rawResponse===void 0?c:U(c,n.rawResponse)}function Wf(e){switch(e.errorCode){case"fileTooLarge":case"outputTooLarge":return"size_limit";case"fileAccessFailed":case"fileReadFailed":return Kf(e)?"directory":"not_found";case"pathValidationFailed":return"permission";default:return}}function Kf(e){if(e.context?.errorCode==="EISDIR")return!0;let t=e.cause;return typeof t=="object"&&t!==null&&t.code==="EISDIR"}async function H_(e,t,n){if(e)try{await e(t,n)}catch{D(t,Mn.EXECUTION_FAILED.code).catch(()=>{})}}function Se(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t},a=i==="empty"?oe(r,"empty",o?.hintContext):[],c=o?.prefixHints||[],l=o?.extraHints||[],d=[...new Set([...c,...a,...l])].filter(u=>typeof u=="string"&&u.trim().length>0);return d.length>0&&(s.hints=d),o?.rawResponse===void 0?s:U(s,o.rawResponse)}function lr(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter},r=Array.isArray(e.hints)?e.hints:[];return A(n,t,{hintSourceError:n,customHints:r,rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ge(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return D(r||n||"unknown_tool",Mn.EXECUTION_FAILED.code).catch(()=>{}),A(i,t)}async function Le({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ge(o,t,r,e)}}import{existsSync as Jf}from"fs";import{join as Zf}from"path";import{getOctocodeDir as qf}from"octocode-shared";import{spawn as Bo}from"child_process";var Q_=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],ur=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],yn=[...ur,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Ba=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],Yf=10*1024*1024,zo=5e3;function Qo(e={},t=ur){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function wt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=ur,maxOutputSize:a=Yf}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},d=()=>l.stdoutChunks.join(""),u=()=>l.stderrChunks.join(""),m={cwd:o,env:Qo(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=Bo(e,t,m)}catch(g){c({stdout:"",stderr:"",exitCode:null,success:!1,error:g instanceof Error?g:new Error(`Failed to spawn command '${e}'`)});return}let f,h=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},zo),c({stdout:d(),stderr:u(),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)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}y(),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",g=>{if(l.killed)return;let C=g.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stdoutChunks.push(C)}),p.stderr?.on("data",g=>{if(l.killed)return;let C=g.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stderrChunks.push(C)}),p.on("close",g=>{l.killed||(y(),c({stdout:d(),stderr:u(),exitCode:g,success:g===0}))}),p.on("error",g=>{l.killed||(l.killed=!0,y(),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:g}))})})}function dr(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=ur}=r,a;try{a=Bo(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Qo({},s)})}catch{o(!1);return}let c,l=()=>{clearTimeout(d),c!==void 0&&(clearTimeout(c),c=void 0)},d=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},zo),o(!1)}},n);a.on("close",u=>{l(),i||o(u===0)}),a.on("error",()=>{l(),i||o(!1)})})}var Xf=1*1024*1024;function j_(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=yn,maxOutputSize:l=Xf}=r,d;try{d=Bo(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Qo({},c)})}catch{o(null);return}let u,m=()=>{clearTimeout(p),u!==void 0&&(clearTimeout(u),u=void 0)};d.stdout?.on("data",f=>{if(i)return;let h=f.toString();if(a+=Buffer.byteLength(h),a>l){if(!i){i=!0;try{d.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(h)}),d.stderr?.on("data",()=>{});let p=setTimeout(()=>{if(!i){i=!0;try{d.kill("SIGTERM")}catch{}u=setTimeout(()=>{try{d.kill("SIGKILL")}catch{}},zo),o(null)}},n);d.on("close",f=>{if(m(),!i)if(f===0){let h=s.join("").trim();o(h||null)}else o(null)}),d.on("error",()=>{m(),i||o(null)})})}function pr(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 za=120*1e3,eh=30*1e3,Qa=[...yn,"GIT_TERMINAL_PROMPT"];async function ja(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await oh();let a=e.branch??await $e(r,o,t),c=qf(),l=Un(c,r,o,a,i),d=zn(l);if(!s&&d.hit&&d.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};zt(c),fo(l),jn(l);let u=rh(t,n);if(i){if(await nh(r,o,a,l,i,u),!Jf(Zf(l,i)))throw fo(l),new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the directory path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await th(r,o,a,l,u);let m=Qn(r,o,a,"clone",i);return Bn(l,m),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}async function th(e,t,n,r,o){let i=Wa(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Va(e,t),r),await jo(i,za,`full clone of ${e}/${t}`,o)}async function nh(e,t,n,r,o,i){let s=Wa(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Va(e,t),r),await jo(s,za,`sparse clone of ${e}/${t}`,i),await jo(["-C",r,"sparse-checkout","set","--",o],eh,`sparse-checkout set ${o}`,void 0)}function Va(e,t){return`https://github.com/${e}/${t}.git`}function Wa(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function rh(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function oh(){try{if(!(await wt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Qa,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 ih(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 jo(e,t,n,r){let o=await wt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Qa,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=ih(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}import{getDirectorySizeBytes as xh}from"octocode-shared";import{incrementToolCharSavings as ph}from"octocode-shared";function je(e){return t=>{}}function Ka(e,t){return n=>t}async function Ya(e,t={}){if(!Array.isArray(e))throw D("promiseUtils",at.PROMISES_NOT_ARRAY.code).catch(je("promise utility session logging")),new Error(at.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw D("promiseUtils",at.TIMEOUT_NOT_POSITIVE.code).catch(je("promise utility session logging")),new Error(at.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw D("promiseUtils",at.CONCURRENCY_NOT_POSITIVE.code).catch(je("promise utility session logging")),new Error(at.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>(D("promiseUtils",lt.NOT_A_FUNCTION.code).catch(je("promise utility session logging")),Promise.reject(new Error(lt.NOT_A_FUNCTION.message(l)))));if(r<i.length)return sh(i,r,n,o);let s=i.map((c,l)=>Xa(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 Xa(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{D("promiseUtils",lt.TIMEOUT.code).catch(()=>{}),l(new Error(lt.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 sh(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){D("promiseUtils",lt.FUNCTION_UNDEFINED.code).catch(je("promise utility session logging")),o[c]={success:!1,error:new Error(lt.FUNCTION_UNDEFINED.message),index:c};continue}try{let d=await Xa(l,c,n,r);o[c]=d}catch(d){o[c]={success:!1,error:d instanceof Error?d:new Error(String(d)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}function ah(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 Wo=["path","uri"];function Vo(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Vo(o,t,n+1);return}let r=e;for(let o of Wo){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let o of Object.values(r))o&&typeof o=="object"&&Vo(o,t,n+1)}function Ja(e){let t=[];for(let i of e)Vo(i?.data,t,0);if(t.length===0)return;let n=ah(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return ch(e,r),n}function ch(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){let a=i[s];typeof a=="string"?!Wo.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function lh(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 uh(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var dh=new Set([...Wo,"owner","repo","name","id"]);function Za(e){let t=lh(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(dh.has(i))continue;let s=n[i];uh(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var mh=3,qa=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,fh=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,hh=5e3;function gh(e,t,n){if(e<=1)return qa;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(fh/o),s=Math.max(hh,Math.min(i,qa));return n?Math.max(s,n):s}async function J(e,t,n,r){let o=n.concurrency??mh,{results:i,errors:s}=await Sh(e,t,o,n.minQueryTimeoutMs);return yh(n,i,s,e,r)}function yh(e,t,n,r,o){let i=["results","hints","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let C=g.result.status;c[g.queryIndex]={id:oc(g.originalQuery,g.queryIndex),...C!==void 0?{status:C}:{},data:Ph(g.result)}}),n.forEach(g=>{let C=r[g.queryIndex];C&&(c[g.queryIndex]={id:oc(C,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),C=ec(g.text,o),T=tc(g.structuredContent,C.pagination);return rc(e.toolName,t,n,C.text.length),{content:[{type:"text",text:C.text}],structuredContent:T,isError:g.isError??(l.length>0&&l.every(x=>x.status==="error"))}}let d=e.peerHints?nc(l):[],u={results:l};if(Array.isArray(u.results)){let g=Ja(u.results);g&&(u.base=g);let C=Za(u.results);C&&(u.shared=C)}let m=e.peerHints?nc(Array.isArray(u.results)?u.results:[]):[],p=e.peerHints?Array.from(new Set([...d,...m])):d;p.length>0&&(u.hints=p);let f=gn(u,a),h=ec(f,o),y=tc(Ye(u),h.pagination);return rc(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:y,isError:l.length>0&&l.every(g=>g.status==="error")}}function Ko(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(`
|
|
35
|
-
`,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
|
|
36
|
-
`:`# Response page ${
|
|
37
|
-
`}${
|
|
38
|
-
`).length-1}))),r&&p&&u.url&&(y.url=u.url,p=!1),m.matches.push(y),f=!0}f||m.matches.push({path:s.path,pathOnly:!0,...r&&u.url?{url:u.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...hc(e.pagination),hasMore:e.pagination.hasMore}),i}function yc(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Rc(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function $h(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function bc(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map($h),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:mc(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Uh(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function Bh(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function zh(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:Bh(e)}}function Sc(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=Uh(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=zh(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(d=>({...d,...d.bodyPagination&&{bodyPagination:d.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...hc(e.pagination),hasMore:e.pagination.hasMore}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function Cc(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Pc(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function Ec(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Et.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Tc(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([u],[m])=>u==="."?-1:m==="."?1:u.localeCompare(m)).map(([u,m])=>({dir:u,files:m.files,folders:m.folders})),c=e.fileSizeMap,l={};if(c){for(let[u,m]of Object.entries(c))if(n[u]){let p=new Set(n[u].files);for(let[f,h]of Object.entries(m))p.has(f)&&(l[f]=h)}}let d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}function Qh(e,t,n,r){let o=Math.max(t,1),i=Math.max(n,0),s=Math.max(r,0),a=Math.max(1,Math.ceil(s/o)),c=s===0?0:Math.min(Math.max(e,0),Math.max(s-1,0));return{currentPage:s===0?1:Math.min(a,Math.floor(c/o)+1),totalPages:a,hasMore:e+i<s,charOffset:e,charLength:i,totalChars:s}}function YA({groups:e,getItems:t,setItems:n,getItemText:r,setItemText:o,charOffset:i,charLength:s,maxItems:a}){let c=r&&o?{get:r,set:o}:null,l=[],d=0;e.forEach((P,x)=>{d+=G(n(P,[]));for(let I of t(P)){let Q=c?.get(I);if(c&&Q!==void 0){let E=G(c.set(I,"")),w=Q.length,O=d,$=O+E,M=$+w;l.push({groupIndex:x,item:I,textStart:$,textLen:w,start:O,end:M}),d=M}else{let E=G(I),w=d;l.push({groupIndex:x,item:I,textStart:w,textLen:0,start:w,end:w+E}),d=w+E}}});let u=d,m=Math.max(s,1),p=Math.min(Math.max(i,0),u),f=Math.min(p+m,u),h=P=>{if(P.textLen===0||!c)return P.item;let x=Math.min(Math.max(p-P.textStart,0),P.textLen),I=Math.min(Math.max(f-P.textStart,0),P.textLen);if(x===0&&I===P.textLen)return P.item;let Q=c.get(P.item)??"";return c.set(P.item,Q.slice(x,I))},y=new Map,b=p,g=0,C=typeof a=="number"&&a>0?a:void 0;for(let P of l){if(P.end<=p)continue;if(P.start>=f)break;let x=y.get(P.groupIndex)??[];if(x.push(h(P)),y.set(P.groupIndex,x),b=Math.max(b,Math.min(P.end,f)),g+=1,C!==void 0&&g>=C){b=Math.max(b,P.end);break}}if(y.size===0&&p<u){let P=l.find(x=>x.end>p);P&&(y.set(P.groupIndex,[h(P)]),b=Math.max(b,Math.min(P.end,f)))}let T=[];return e.forEach((P,x)=>{let I=y.get(x);I&&T.push(n(P,I))}),{groups:T,pagination:Qh(p,m,Math.max(0,b-p),u)}}function xt(e){let t=new Set,n=[];for(let r of e)typeof r=="string"&&r.trim().length>0&&!t.has(r)&&(t.add(r),n.push(r));return n}function jh(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function gr(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=jh(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r,s=Array.isArray(n.data.hints)?n.data.hints.filter(a=>typeof a=="string"&&a.trim().length>0):void 0;t.push({id:n.id,error:i,...s&&s.length>0?{hints:s}:{}})}return t}function yr(e,t,n){let r=gn(e,[...t]);return{structuredContent:Ye(e),text:r,isError:n}}function xc(e){return typeof e=="object"&&e!==null}function rt(e){return typeof e=="string"&&e.length>0?e:void 0}function Xe(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Vh(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function Wh(e){return xt(e.flatMap(t=>{let n=t.data.hints;return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}))}var Kh=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function Yh(e){if(!xc(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 Kh){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Xh(e,t){return`${e}/${t}`}function Jh(e,t,n){let r=Xh(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function Zh(e,t){return{path:rt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",...Xe(e.fileSize)!==void 0?{fileSize:Xe(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:Xe(e.totalLines),sourceChars:Xe(e.sourceChars),sourceBytes:Xe(e.sourceBytes),resolvedBranch:rt(e.resolvedBranch),pagination:Yh(e.pagination),...e.isPartial===!0?{isPartial:!0}:{},startLine:Xe(e.startLine),endLine:Xe(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:rt(e.lastModified),lastModifiedBy:rt(e.lastModifiedBy),warnings:Vh(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:rt(e.searchedFor)}}function wc(e,t){let n=t.pagination,r=n?.charOffset??0,o=n?.charLength??0,i=r+o,s=n?.currentPage&&n.totalPages?`Page ${n.currentPage}/${n.totalPages}`:"Content page",a=typeof n?.totalChars=="number"&&o>0?` (chars ${r+1}-${i} of ${n.totalChars})`:"";return`${s}${a}. Next: charOffset=${i} for ${e}:${t.path}`}function qh(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(xc).map(o=>({path:rt(o.path)??"",size:Xe(o.size)??0,type:rt(o.type)??"file"}));return{path:String(t.path??""),localPath:rt(e.localPath)??"",fileCount:Xe(e.fileCount)??r.length,totalSize:Xe(e.totalSize)??0,...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:rt(e.resolvedBranch)}}function eg(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=Jh(n,s,a),l=r.data;if(i.type==="directory"){let u=c.directories??[];u.push(qh(l,i)),c.directories=u;return}let d=c.files??[];d.push(Zh(l,i)),c.files=d}),Array.from(n.values())}function tg(e){let t=[];for(let n of e){for(let r of n.files??[]){if(r.pagination?.hasMore&&typeof r.pagination.charOffset=="number"){let o=r.pagination.charLength??0,i=r.pagination.charOffset+o,s=r.pagination.nextBlockChar;if(typeof s=="number"){let a=s-i;t.push(`${wc(n.id,r)}. Page cut mid-block at char ${i}. Next top-level definition starts at char ${s}. Re-request with charLength=${o+a} to extend this page to the next boundary, or use charOffset=${i} to continue page-by-page.`)}else t.push(wc(n.id,r))}r.isPartial&&!r.matchRanges?.length&&typeof r.endLine=="number"&&typeof r.totalLines=="number"&&r.endLine<r.totalLines&&t.push(`File content is partial (lines ${r.startLine??1}\u2013${r.endLine} of ${r.totalLines}). Use startLine=${r.endLine+1} to read the next section of ${n.id}:${r.path}.`)}for(let r of n.directories??[])r.cached&&t.push(`Directory ${n.id}:${r.path} served from cache.`)}return xt(t)}function ng(e,t){let n=e.toLowerCase();if(t===404||n.includes("not found")||n.includes("404"))return["Verify owner/repo/path/branch.","Use ghViewRepoStructure to confirm the path."];if(t===403||n.includes("forbidden")||n.includes("403"))return["Check token permissions or repository visibility."];if(t===429||n.includes("rate limit"))return["Retry after reset or authenticate with a higher-limit token."]}function rg(e,t){return gr(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error,hints:ng(r.error)}})}function _c(){return({queries:e,results:t,config:n})=>{let r=eg(t,e),o=rg(t,e),i=xt([...n.peerHints?Wh(t):[],...tg(r)]),s={results:r};return i.length>0&&(s.hints=i),o&&o.length>0&&(s.errors=o),yr(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","hints","errors"],r.length===0&&!!(o&&o.length>0))}}async function Ac(e){let{queries:t,authInfo:n}=e,r=Be(n);return J(t,async(o,i)=>{try{let s=hr.safeParse(o);if(!s.success){let l=s.error.issues.map(d=>d.message).join("; ");return A(l,o)}let a=s.data,c=r();return a.type==="directory"?og(a,n,c):ig(a,c)}catch(s){return ge(s,o)}},{toolName:S.GITHUB_FETCH_CONTENT,peerHints:!0,finalize:_c()},e)}async function og(e,t,n){if(!Hn())return ge(new Error("Directory fetch requires ENABLE_LOCAL=true and ENABLE_CLONE=true. Directory mode saves files to disk using the same cache as ghCloneRepo."),e,"Clone not enabled",S.GITHUB_FETCH_CONTENT);if(!fr(n,"fetchDirectoryToDisk"))return ge(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",S.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return A("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await $e(e.owner,e.repo,t),o=await Ds(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i={localPath:o.localPath,fileCount:o.fileCount,totalSize:o.totalSize,files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{}};return Se(e,i,!0,S.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??G(o)})}async function ig(e,t){let n=await ft(e,()=>t.provider.getFileContent(Cc(e)));if(n.ok===!1)return n.result;let r=n.response.hints,o={...Pc(n.response.data,e),...r?.length?{hints:r}:{}},i=!!(n.response.data.matchNotFound===!0||n.response.data.content&&n.response.data.content.length>0);return Se(e,o,i,S.GITHUB_FETCH_CONTENT,{rawResponse:n.response.rawResponseChars,hintContext:{path:e.path,branch:e.branch,isPartial:n.response.data.isPartial,endLine:n.response.data.endLine}})}function sg(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{}}}function ag(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function cg(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function lg(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{id:`${n.owner}/${n.repo}:${r.path}`,owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function ug(e,t,n){return t.length===0?[]:[{id:e.length===1&&typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",data:{files:lg(t),...n?{pagination:n}:{}}}]}function dg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pg(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${dg(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function mg(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?cg(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:pg(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:fg(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 fg(e,t){return{...e,matches:t}}function hg(e){return xt(e.flatMap(t=>{let n=t.data.hints;return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}))}function gg(e){return e.some(t=>t.matches.some(n=>n.pathOnly))}function Lc(){return({queries:e,results:t,config:n})=>{let r=[],o,i=0,s=[];t.forEach((b,g)=>{if(b.status==="error")return;let C=sg(b);if(C.results.reduce((x,I)=>x+I.matches.length,0)===0){let x=b.data.hints,I=Array.isArray(x)?x.filter(Q=>typeof Q=="string"&&Q.trim().length>0):[];s.push({id:b.id,hints:I,...C.nonExistentScope?{nonExistentScope:!0}:{}})}let P=C.results;r.push({id:b.id,groups:P}),C.pagination&&(o=C.pagination,i+=1)});let a=Array.from(new Set(e.flatMap(b=>{let g=b.keywords;return Array.isArray(g)?g.filter(C=>typeof C=="string"):[]}))),c=mg(ag(r),a),l=o&&i===1?Wt(o,"matches"):[],d=gr(t),u=gg(c)?['Some match="file" results are path-only because GitHub did not return text matches; use ghGetFileContent with matchString or startLine/endLine to inspect content.']:[],m=xt([...n.peerHints?hg(t):[],...l,...u]),p=o&&i===1?o:void 0,f=e.some(b=>b.concise===!0),h=ug(e,c,p);if(f)for(let b of h)b.data.files=b.data.files.map(g=>`${g.owner}/${g.repo}:${g.path}`);let y={results:h};if(m.length>0&&(y.hints=m),s.length>0){let b=new Set(m);y.emptyQueries=s.map(({id:g,hints:C,nonExistentScope:T})=>{let P=C.filter(x=>!b.has(x));return{id:g,...P.length>0?{hints:P}:{},...T?{nonExistentScope:T}:{}}})}return d.length>0&&(y.errors=d),yr(y,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","hints","emptyQueries","errors"],c.length===0&&d.length>0)}}function yg(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function Rg(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search.",hints:['Use owner="<org-or-user>" with repo="<repository>" \u2014 GitHub code search cannot scope to a bare repository name.','If you only know the repo name, first use ghSearchRepos with keywords=["<repo>"] to find its owner.']}}async function Oc(e){let{queries:t}=e,n=Be(e.authInfo);return J(t,async(r,o)=>{try{let i=Rg(r);if(i)return A(i.error,r,{customHints:i.hints});if(!yg(r))return A("At least one search term or scope filter is required.",r);let s=n(),a=await ft(r,()=>s.provider.searchCode(fc(r)));if(a.ok===!1)return a.result;let c=gc(a.response.data,r),l={hasOwnerRepo:!!(r.owner&&r.repo),owner:r.owner,repo:r.repo,nonExistentScope:c.nonExistentScope,match:r.match,extension:r.extension,filename:r.filename,path:r.path,keywords:r.keywords,totalMatches:c.pagination?.totalMatches,hasMore:c.pagination?.hasMore,currentPage:c.pagination?.currentPage??1,totalPages:c.pagination?.totalPages??1,matchedPaths:c.results.flatMap(p=>p.matches.map(f=>f.path))},d=new Set(c.results.flatMap(p=>p.matches.map(f=>`${p.owner}/${p.repo}:${f.path}`))).size,u=[];if(c.results.length>0){let p=Array.isArray(r.keywords)&&typeof r.keywords[0]=="string"?r.keywords[0]:"<keyword>";u.push(`Found matches in ${d} file${d===1?"":"s"} \u2014 matchIndices[].lineOffset is the 0-based line within the snippet; use ghGetFileContent(path, matchString="${p}") to land on the matched region (returns lineHint for lspGetSemantics).`)}if(c.pagination){let{totalPages:p,perPage:f,totalMatches:h,reportedTotalMatches:y,reachableTotalMatches:b}=c.pagination,g=y??h,C=b??Math.min(h,p*f);g>C&&u.push(`GitHub caps code-search at ${C} results \u2014 ${g-C} of ${g} reported matches are unreachable; narrow with path/extension/filename to see the rest.`)}if(typeof r.path=="string"&&!r.filename&&/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/.test(r.path)){let p=r.path.match(/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/),f=p?p[1]:r.path;u.push(`path="${r.path}" looks like a file path \u2014 auto-extracted filename="${f}" for the query. Use explicit filename="${f}" + path="<dir>" for clarity.`)}return Se(r,c,c.results.length>0,S.GITHUB_SEARCH_CODE,{hintContext:l,rawResponse:a.response.rawResponseChars,extraHints:u})}catch(i){return ge(i,r)}},{toolName:S.GITHUB_SEARCH_CODE,peerHints:!0,finalize:Lc()},e)}import{z as v}from"zod";import{GitHubCodeSearchQuerySchema as Ic}from"@octocodeai/octocode-core/schemas";var kc={limit:F(1,100).optional(),page:q.default(1)},vc=te(Ic,kc),Fc=X(ae(Ic,kc)),AL=v.object({base:v.string().optional(),shared:v.record(v.string(),v.union([v.string(),v.number(),v.boolean()])).optional(),responsePagination:xe.responsePagination,results:v.array(v.object({id:v.string(),data:v.object({files:v.array(v.object({id:v.string(),owner:v.string(),repo:v.string(),path:v.string(),queryId:v.string().optional(),matches:v.array(v.object({value:v.string().optional(),pathOnly:v.boolean().optional(),matchIndices:v.array(v.object({start:v.number(),end:v.number()})).optional(),url:v.string().optional()}))})),pagination:v.object({currentPage:v.number(),totalPages:v.number(),perPage:v.number(),totalMatches:v.number(),reportedTotalMatches:v.number().optional(),reachableTotalMatches:v.number().optional(),totalMatchesKind:v.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:v.boolean().optional(),hasMore:v.boolean(),uniqueFileCount:v.number().optional()}).optional()})})),hints:v.array(v.string()).optional(),emptyQueries:v.array(v.object({id:v.string(),hints:v.array(v.string()).optional(),nonExistentScope:v.literal(!0).optional()})).optional(),errors:v.array(v.object({id:v.string(),error:v.string(),hints:v.array(v.string()).optional()})).optional()});function bg(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function Sg(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function Cg(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Mc(e){let{content:t,reviewMode:n}=e,r=bg(t,n),o=Sg(t,n),i=Cg(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}function Nc(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function qo(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function br(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function ei(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function Cr(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 Dc(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Gc(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function Pg(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Sr(e,t,n){return Pg({...Gc(e,t),...n})}function Hc(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Sr(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function Jo(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Sr(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Eg(e,t,n){return{target:Gc(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function Rr(e){return String(e.path??e.filename??"")}function Tg(e,t){return{path:Rr(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function wg(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 xg(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=wg(r,n.comments),i=qo(t),s=i?o.filter(l=>br(l.body,i)):o,{items:a,pagination:c}=ei(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let d=Cr(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...d?{body:d.content,bodyPagination:d.pagination}:{bodyPreview:Dc(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function _g(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=qo(t);return{reviews:(o?r.filter(s=>br(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Cr(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 Ag(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=ei(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function Lg(e){return e.split(`
|
|
34
|
+
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function xr(e,t){let n=wn(e)??{},r=Xl(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;r==="json"?i=JSON.stringify(Do(n,t||o),null,2):i=O.jsonToYamlString(n,{keysPriority:t||o});let s=ks.sanitizeContent(i);return Is(s.content)}function Do(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Do(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Do(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Do(n[o],t));return r}var kR=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]);function vR(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=>kR.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function wn(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=>wn(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(vR(a))continue;let c=(s==="files"||s==="repositories")&&!n,u=wn(a,{inFilesObject:n||c,depth:c?0:r+1});u!==void 0&&(o[s]=u,i=!0)}return i?o:void 0}return e}import{z as Ho}from"zod";function v(e,t){return Ho.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Ho.number().int().min(e).max(t))}var q=v(1,1e3).optional().default(1),An=v(0,100).optional(),Ln=v(1,1e9).optional(),FR={responseCharOffset:v(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:v(1,5e4).optional().describe("Full-response char window.")};function X(e,t={}){let{maxQueries:n=5}=t;return Ho.object({queries:Ho.array(e).min(1).max(n).describe("Parallel queries."),...FR}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}import{z as he}from"zod";var MR=he.object({currentPage:he.number(),totalPages:he.number(),hasMore:he.boolean(),charOffset:he.number(),charLength:he.number(),totalChars:he.number(),nextCharOffset:he.number().optional()}).optional(),Ae={hints:he.array(he.string()).optional(),base:he.string().optional(),shared:he.record(he.string(),he.union([he.string(),he.number(),he.boolean()])).optional(),responsePagination:MR};function dv(e){return e.extend(Ae)}function NR(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function L(e,t,n={}){let{extra:r}=n,o={status:"error"};if(NR(e))o.error=e;else if(yi(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=qa(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:U(o,n.rawResponse)}function Le(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:L(i,t,{toolName:n.toolName})}}async function Sv(e,t,n){if(e)try{await e(t,n)}catch{M(t,Br.EXECUTION_FAILED.code).catch(()=>{})}}function Pe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:U(s,o.rawResponse)}function Go(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 L(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Ee(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return M(r||n||"unknown_tool",Br.EXECUTION_FAILED.code).catch(()=>{}),L(i,t)}async function ke({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Ee(o,t,r,e)}}import{existsSync as GR}from"fs";import{join as UR}from"path";import{spawn as vs}from"child_process";var wv=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Uo=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],_r=[...Uo,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Jl=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],DR=10*1024*1024,Fs=5e3;function Ms(e={},t=Uo){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function Xt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Uo,maxOutputSize:a=DR}=n;return new Promise(c=>{let u={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},l=()=>u.stdoutChunks.join(""),d=()=>u.stderrChunks.join(""),m={cwd:o,env:Ms(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=vs(e,t,m)}catch(b){c({stdout:"",stderr:"",exitCode:null,success:!1,error:b instanceof Error?b:new Error(`Failed to spawn command '${e}'`)});return}let f,g=setTimeout(()=>{if(!u.killed){u.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Fs),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),h=()=>{clearTimeout(g),f!==void 0&&(clearTimeout(f),f=void 0)},R=()=>{if(u.totalOutputSize>a){if(!u.killed){u.killed=!0;try{p.kill("SIGKILL")}catch{}h(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",b=>{if(u.killed)return;let P=b.toString();u.totalOutputSize+=Buffer.byteLength(P),!R()&&u.stdoutChunks.push(P)}),p.stderr?.on("data",b=>{if(u.killed)return;let P=b.toString();u.totalOutputSize+=Buffer.byteLength(P),!R()&&u.stderrChunks.push(P)}),p.on("close",b=>{u.killed||(h(),c({stdout:l(),stderr:d(),exitCode:b,success:b===0}))}),p.on("error",b=>{u.killed||(u.killed=!0,h(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:b}))})})}function Zl(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Uo}=r,a;try{a=vs(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Ms({},s)})}catch{o(!1);return}let c,u=()=>{clearTimeout(l),c!==void 0&&(clearTimeout(c),c=void 0)},l=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Fs),o(!1)}},n);a.on("close",d=>{u(),i||o(d===0)}),a.on("error",()=>{u(),i||o(!1)})})}var HR=1*1024*1024;function Av(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=_r,maxOutputSize:u=HR}=r,l;try{l=vs(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Ms({},c)})}catch{o(null);return}let d,m=()=>{clearTimeout(p),d!==void 0&&(clearTimeout(d),d=void 0)};l.stdout?.on("data",f=>{if(i)return;let g=f.toString();if(a+=Buffer.byteLength(g),a>u){if(!i){i=!0;try{l.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(g)}),l.stderr?.on("data",()=>{});let p=setTimeout(()=>{if(!i){i=!0;try{l.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}},Fs),o(null)}},n);l.on("close",f=>{if(m(),!i)if(f===0){let g=s.join("").trim();o(g||null)}else o(null)}),l.on("error",()=>{m(),i||o(null)})})}function Bo(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 ql=120*1e3,BR=30*1e3,ed=[..._r,"GIT_TERMINAL_PROMPT"];async function td(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await $R();let a=e.branch??await Ge(r,o,t),c=zt(),u=$u(c,r,o,a,i),l=mr(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Co(c),hs(u),hr(u);let d=jR(t,n);if(i){if(await QR(r,o,a,u,i,d),!GR(UR(u,i)))throw hs(u),new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await zR(r,o,a,u,d);let m=gr(r,o,a,"clone",i);return fr(u,m),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}async function zR(e,t,n,r,o){let i=rd(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",nd(e,t),r),await Ns(i,ql,`full clone of ${e}/${t}`,o)}async function QR(e,t,n,r,o,i){let s=rd(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",nd(e,t),r),await Ns(s,ql,`sparse clone of ${e}/${t}`,i),await Ns(["-C",r,"sparse-checkout","set","--skip-checks","--",o],BR,`sparse-checkout set ${o}`,void 0)}function nd(e,t){return`https://github.com/${e}/${t}.git`}function rd(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function jR(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function $R(){try{if(!(await Xt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:ed,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 VR(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 Ns(e,t,n,r){let o=await Xt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:ed,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=VR(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}async function od(e,t={}){if(!Array.isArray(e))throw M("promiseUtils",bt.PROMISES_NOT_ARRAY.code).catch(xe("promise utility session logging")),new Error(bt.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw M("promiseUtils",bt.TIMEOUT_NOT_POSITIVE.code).catch(xe("promise utility session logging")),new Error(bt.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw M("promiseUtils",bt.CONCURRENCY_NOT_POSITIVE.code).catch(xe("promise utility session logging")),new Error(bt.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,u)=>typeof c=="function"?c:()=>(M("promiseUtils",Ct.NOT_A_FUNCTION.code).catch(xe("promise utility session logging")),Promise.reject(new Error(Ct.NOT_A_FUNCTION.message(u)))));if(r<i.length)return WR(i,r,n,o);let s=i.map((c,u)=>id(c,u,n,o));return(await Promise.allSettled(s)).map((c,u)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:u})}async function id(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,u)=>{o=setTimeout(()=>{M("promiseUtils",Ct.TIMEOUT.code).catch(()=>{}),u(new Error(Ct.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 WR(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,u=e[c];if(!u){M("promiseUtils",Ct.FUNCTION_UNDEFINED.code).catch(xe("promise utility session logging")),o[c]={success:!1,error:new Error(Ct.FUNCTION_UNDEFINED.message),index:c};continue}try{let l=await id(u,c,n,r);o[c]=l}catch(l){o[c]={success:!1,error:l instanceof Error?l:new Error(String(l)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}function KR(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 Hs=["path","uri"];function Ds(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Ds(o,t,n+1);return}let r=e;for(let o of Hs){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let o of Object.values(r))o&&typeof o=="object"&&Ds(o,t,n+1)}function sd(e){let t=[];for(let i of e)Ds(i?.data,t,0);if(t.length===0)return;let n=KR(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return YR(e,r),n}function YR(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){let a=i[s];typeof a=="string"?!Hs.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function XR(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 JR(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var ZR=new Set([...Hs,"owner","repo","name","id"]);function ad(e){let t=XR(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(ZR.has(i))continue;let s=n[i];JR(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var qR=3,cd=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,eb=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,tb=5e3;function nb(e,t,n){if(e<=1)return cd;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(eb/o),s=Math.max(tb,Math.min(i,cd));return n?Math.max(s,n):s}async function J(e,t,n,r){let o=n.concurrency??qR,{results:i,errors:s}=await sb(e,t,o,n.minQueryTimeoutMs);return rb(n,i,s,e,r)}function rb(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let h=g.result.status;c[g.queryIndex]={id:pd(g.originalQuery,g.queryIndex),...h!==void 0?{status:h}:{},data:ab(g.result)}}),n.forEach(g=>{let h=r[g.queryIndex];h&&(c[g.queryIndex]={id:pd(h,g.queryIndex),status:"error",data:{error:g.error}})});let u=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:u,config:e}),h=ud(g.text,o),R=ld(g.structuredContent,h.pagination);return dd(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:R,isError:g.isError??(u.length>0&&u.every(P=>P.status==="error"))}}let l={results:u};if(Array.isArray(l.results)){let g=sd(l.results);g&&(l.base=g);let h=ad(l.results);h&&(l.shared=h)}let d=xr(l,a),m=ud(d,o),p=ld(ot(l),m.pagination);return dd(e.toolName,t,n,m.text.length),{content:[{type:"text",text:m.text}],structuredContent:p,isError:u.length>0&&u.every(g=>g.status==="error")}}function Gs(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(`
|
|
35
|
+
`,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 ob(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Gs(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function ib(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Gs(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 ud(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=Gs(e,s,i),c=a<o,u=ob(e,s,i),l=ib(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${u}/${l}. Next: responseCharOffset=${a}
|
|
36
|
+
`:`# Response page ${u}/${l}.
|
|
37
|
+
`}${d}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function ld(e,t){return t?{...e,responsePagination:t}:e}function dd(e,t,n,r){let o=t.reduce((i,s)=>i+(ne(s.result)??N(s.result)),0)+n.reduce((i,s)=>i+N(s),0);try{io(e,o,r)}catch{}}async function sb(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,u)=>()=>t(c,u).then(l=>({result:l,queryIndex:u,originalQuery:c})));return(await od(s,{timeout:nb(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,u)=>{i.push({queryIndex:u,error:c.message})}})).forEach(c=>{c.success&&c.data&&o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}),{results:o,errors:i}}function ab(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function pd(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function zo(e){return e.data!==void 0&&!e.error}function cb(e){return e.error!==void 0}import{maskSensitiveData as fd}from"@octocodeai/octocode-engine/mask";var Us=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function ub(){return Yi().provider??ir()}function lb(e){let t=Yi(),n=t.provider??ir(),{baseUrl:r,token:o}=t;try{let i=Os(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=fd(s);throw new Us(n,`Failed to initialize ${n} provider: ${a}`)}}function $e(e){let t;return()=>t??=lb(e)}function Qo(e,t){return e.capabilities[t]}async function kt(e,t){let n=await t();return zo(n)?{ok:!0,response:n}:{ok:!1,result:Go(n,e)}}async function md(e,t){let n=t??ub(),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:fd(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)zo(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}async function gd(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>ke({toolName:S.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Qo(s,"cloneRepo"))return Ee(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",S.GITHUB_CLONE_REPO);let a;try{a=await td(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return L(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=or(a.localPath),u={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},l={localSearch:{tool:"localSearchCode",query:{path:a.localPath,keywords:"TODO",mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:u,next:l};return Pe(o,d,!0,S.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:S.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}import{CloneRepoQuerySchema as fb}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as mb}from"@octocodeai/octocode-core/schemas/outputs";import{z as hd}from"zod";function db(e,t){return e?.description&&!t.description?t.describe(e.description):t}function yd(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=db(e.shape[r],o);return n}function pb(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Rd(e,t){if(!t?.length)return e;let n=new Set(t);return hd.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function re(e,t={},n={}){let r=Rd(e,n.omit),o=pb(r,yd(r,t));return n.strict?o.strict():o}function ce(e,t={},n={}){let r=Rd(e,n.omit),o=hd.object({...r.shape,...yd(r,t)});return n.strict?o.strict():o}var Bs=re(fb),bd=X(Bs),h0=mb.extend(Ae);import{z as E}from"zod";import{FileContentQuerySchema as Sd}from"@octocodeai/octocode-core/schemas";var gb=E.enum(["none","standard","symbols"]).optional().default("standard"),hb=E.object({currentPage:E.number(),totalPages:E.number(),hasMore:E.boolean(),nextPage:E.number().optional(),nextMatchPage:E.number().optional(),charOffset:E.number().optional(),charLength:E.number().optional(),totalChars:E.number().optional(),nextCharOffset:E.number().optional(),filesPerPage:E.number().optional(),totalFiles:E.number().optional(),entriesPerPage:E.number().optional(),totalEntries:E.number().optional(),matchesPerPage:E.number().optional(),totalMatches:E.number().optional()}),yb=E.object({path:E.string(),content:E.string(),localPath:E.string().optional(),repoRoot:E.string().optional(),contentView:E.enum(["none","standard","symbols"]).optional(),isSkeleton:E.boolean().optional(),totalLines:E.number().optional(),sourceChars:E.number().optional(),sourceBytes:E.number().optional(),resolvedBranch:E.string().optional(),pagination:hb.optional(),isPartial:E.boolean().optional(),startLine:E.number().optional(),endLine:E.number().optional(),matchRanges:E.array(E.object({start:E.number(),end:E.number()})).optional(),lastModified:E.string().optional(),lastModifiedBy:E.string().optional(),warnings:E.array(E.string()).optional(),matchNotFound:E.boolean().optional(),searchedFor:E.string().optional(),cached:E.boolean().optional()}),Rb=E.object({path:E.string(),localPath:E.string(),repoRoot:E.string().optional(),fileCount:E.number(),totalSize:E.number(),files:E.array(E.object({path:E.string(),size:E.number(),type:E.string()})).optional(),cached:E.boolean().optional(),resolvedBranch:E.string().optional()}),Cd={startLine:Ln,endLine:Ln,contextLines:An,charOffset:v(0,1e8).optional(),charLength:v(1,5e4).optional(),minify:gb},bb=ce(Sd,Cd),jo=re(Sd,Cd),Pd=X(bb),T0=E.object({base:E.string().optional(),shared:E.record(E.string(),E.union([E.string(),E.number(),E.boolean()])).optional(),responsePagination:Ae.responsePagination,results:E.array(E.object({id:E.string(),owner:E.string(),repo:E.string(),files:E.array(yb).optional(),directories:E.array(Rb).optional()})),errors:E.array(E.object({id:E.string(),owner:E.string().optional(),repo:E.string().optional(),path:E.string().optional(),error:E.string()})).optional()});function Sb(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 Ed(e,t){return e&&t?`${e}/${t}`:void 0}function A0(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,u=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${u} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function Td(e){return{keywords:e.keywords??[],projectId:Ed(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function xd(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 Cb(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function _d(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:u}=Cb(a),l=`${c}/${u}`,d=s,m=o.get(l);if(m||(m={id:l,owner:c,repo:u,matches:[]},o.set(l,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let p=!0,f=!1;for(let g of s.matches){if(!g.context)continue;let h={path:s.path,value:Sb(g.context)};g.positions?.length>0&&(h.matchIndices=g.positions.map(([R,b])=>({start:R,end:b,lineOffset:(g.context??"").substring(0,R).split(`
|
|
38
|
+
`).length-1}))),r&&p&&d.url&&(h.url=d.url,p=!1),m.matches.push(h),f=!0}f||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...xd(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function wd(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Ad(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function Pb(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Ld(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Pb),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Ed(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Eb(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function Tb(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function xb(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:Tb(e)}}function Od(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=Eb(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,u=xb(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(l=>({...l,...l.bodyPagination&&{bodyPagination:l.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...u&&{reviewSummary:u},...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}:{},...xd(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function Id(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function kd(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function vd(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Kt.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Fd(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[m])=>d==="."?-1:m==="."?1:d.localeCompare(m)).map(([d,m])=>({dir:d,files:m.files,folders:m.folders})),c=e.fileSizeMap,u={};if(c){for(let[d,m]of Object.entries(c))if(n[d]){let p=new Set(n[d].files);for(let[f,g]of Object.entries(m))p.has(f)&&(u[f]=g)}}let l={structure:a,...Object.keys(u).length>0&&{fileSizes:u},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(l.resolvedBranch=i),s&&(l.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)&&(l.pagination=e.pagination),l}function _b(e,t,n,r){let o=Math.max(t,1),i=Math.max(n,0),s=Math.max(r,0),a=Math.max(1,Math.ceil(s/o)),c=s===0?0:Math.min(Math.max(e,0),Math.max(s-1,0));return{currentPage:s===0?1:Math.min(a,Math.floor(c/o)+1),totalPages:a,hasMore:e+i<s,charOffset:e,charLength:i,totalChars:s}}function k0({groups:e,getItems:t,setItems:n,getItemText:r,setItemText:o,charOffset:i,charLength:s,maxItems:a}){let c=r&&o?{get:r,set:o}:null,u=[],l=0;e.forEach((C,_)=>{l+=N(n(C,[]));for(let I of t(C)){let j=c?.get(I);if(c&&j!==void 0){let w=N(c.set(I,"")),A=j.length,Q=l,se=Q+w,$=se+A;u.push({groupIndex:_,item:I,textStart:se,textLen:A,start:Q,end:$}),l=$}else{let w=N(I),A=l;u.push({groupIndex:_,item:I,textStart:A,textLen:0,start:A,end:A+w}),l=A+w}}});let d=l,m=Math.max(s,1),p=Math.min(Math.max(i,0),d),f=Math.min(p+m,d),g=C=>{if(C.textLen===0||!c)return C.item;let _=Math.min(Math.max(p-C.textStart,0),C.textLen),I=Math.min(Math.max(f-C.textStart,0),C.textLen);if(_===0&&I===C.textLen)return C.item;let j=c.get(C.item)??"";return c.set(C.item,j.slice(_,I))},h=new Map,R=p,b=0,P=typeof a=="number"&&a>0?a:void 0;for(let C of u){if(C.end<=p)continue;if(C.start>=f)break;let _=h.get(C.groupIndex)??[];if(_.push(g(C)),h.set(C.groupIndex,_),R=Math.max(R,Math.min(C.end,f)),b+=1,P!==void 0&&b>=P){R=Math.max(R,C.end);break}}if(h.size===0&&p<d){let C=u.find(_=>_.end>p);C&&(h.set(C.groupIndex,[g(C)]),R=Math.max(R,Math.min(C.end,f)))}let x=[];return e.forEach((C,_)=>{let I=h.get(_);I&&x.push(n(C,I))}),{groups:x,pagination:_b(p,m,Math.max(0,R-p),d)}}function wb(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function $o(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=wb(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function Vo(e,t,n){let r=xr(e,[...t]);return{structuredContent:ot(e),text:r,isError:n}}function Md(e){return typeof e=="object"&&e!==null}function Ve(e){return typeof e=="string"&&e.length>0?e:void 0}function it(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ab(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}var Lb=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function Ob(e){if(!Md(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 Lb){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Ib(e,t){return`${e}/${t}`}function kb(e,t,n){let r=Ib(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function vb(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function Fb(e,t){let n=Ob(e.pagination),r=vb(n,t);return{path:Ve(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:Ve(e.localPath),repoRoot:Ve(e.repoRoot),...it(e.fileSize)!==void 0?{fileSize:it(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:it(e.totalLines),sourceChars:it(e.sourceChars),sourceBytes:it(e.sourceBytes),resolvedBranch:Ve(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:it(e.startLine),endLine:it(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:Ve(e.lastModified),lastModifiedBy:Ve(e.lastModifiedBy),warnings:Ab(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Ve(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function Mb(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Md).map(o=>({path:Ve(o.path)??"",size:it(o.size)??0,type:Ve(o.type)??"file"}));return{path:String(t.path??""),localPath:Ve(e.localPath)??"",repoRoot:Ve(e.repoRoot),fileCount:it(e.fileCount)??r.length,totalSize:it(e.totalSize)??0,...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Ve(e.resolvedBranch)}}function Nb(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=kb(n,s,a),u=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(Mb(u,i)),c.directories=d;return}let l=c.files??[];l.push(Fb(u,i)),c.files=l}),Array.from(n.values())}function Db(e,t){return $o(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error}})}function Nd(){return({queries:e,results:t})=>{let n=Nb(t,e),r=Db(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),Vo(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}async function Dd(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{let s=Le(jo,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?Hb(a,n,c):Gb(a,n,c)}catch(s){return Ee(s,o,void 0,S.GITHUB_FETCH_CONTENT)}},{toolName:S.GITHUB_FETCH_CONTENT,finalize:Nd()},e)}async function Hb(e,t,n){let r=ae();if(!(r.local.enabled&&r.local.enableClone))return L("Directory fetch requires local clone support. Set ENABLE_LOCAL=true and ENABLE_CLONE=true.",e);if(!Qo(n,"fetchDirectoryToDisk"))return Ee(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",S.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return L("Directory fetch requires both owner and repo.",e,{rawResponse:0});let o=e.branch??await Ge(e.owner,e.repo,t),i=await Zu(e.owner,e.repo,String(e.path),o,t,!!e.forceRefresh),s={localPath:i.localPath,repoRoot:i.repoRoot,fileCount:i.fileCount,totalSize:i.totalSize,files:i.files,...i.cached?{cached:!0}:{},...e.branch!==i.branch?{resolvedBranch:i.branch}:{}};return Pe(e,s,!0,S.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??N(i)})}async function Gb(e,t,n){let r=await kt(e,()=>n.provider.getFileContent(Id(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await Ub(e,t):void 0,i={...kd(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Pe(e,i,s,S.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function Ub(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ge(e.owner,e.repo,t);return qu(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function Bb(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function zb(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function Qb(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function jb(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function $b(e,t,n){return t.length===0?[]:[{id:e.length===1&&typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",data:{files:jb(t),...n?{pagination:n}:{}}}]}function Vb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wb(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${Vb(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function Kb(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?Qb(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:Wb(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:Yb(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 Yb(e,t){return{...e,matches:t}}function Hd(){return({queries:e,results:t})=>{let n=[],r,o=0,i=[],s=!1;t.forEach((f,g)=>{if(f.status==="error")return;let h=Bb(f);h.incompleteResults&&(s=!0),h.results.reduce((P,x)=>P+x.matches.length,0)===0&&i.push({id:f.id,...h.nonExistentScope?{nonExistentScope:!0}:{},...h.incompleteResults?{incompleteResults:!0}:{}});let b=h.results;n.push({id:f.id,groups:b}),h.pagination&&(r=h.pagination,o+=1)});let a=Array.from(new Set(e.flatMap(f=>{let g=f.keywords;return Array.isArray(g)?g.filter(h=>typeof h=="string"):[]}))),c=Kb(zb(n),a),u=$o(t),l=r&&o===1?r:void 0,d=e.some(f=>f.concise===!0),m=$b(e,c,l);if(d)for(let f of m)f.data.files=f.data.files.map(g=>`${g.owner}/${g.repo}:${g.path}`);let p={results:m};return i.length>0&&(p.emptyQueries=i.map(({id:f,nonExistentScope:g,incompleteResults:h})=>({id:f,...g?{nonExistentScope:g}:{},...h?{incompleteResults:h}:{}}))),u.length>0&&(p.errors=u),s&&(p.warnings=[...Array.isArray(p.warnings)?p.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),Vo(p,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],c.length===0&&u.length>0)}}function Xb(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function Jb(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 Gd(e){let{queries:t}=e,n=$e(e.authInfo);return J(t,async(r,o)=>{try{let i=Jb(r);if(i)return L(i.error,r);if(!Xb(r))return L("At least one search term or scope filter is required.",r);let s=n(),a=await kt(r,()=>s.provider.searchCode(Td(r)));if(a.ok===!1)return a.result;let c=_d(a.response.data,r);return Pe(r,c,c.results.length>0,S.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Ee(i,r,void 0,S.GITHUB_SEARCH_CODE)}},{toolName:S.GITHUB_SEARCH_CODE,finalize:Hd()},e)}import{z as k}from"zod";import{GitHubCodeSearchQuerySchema as Ud}from"@octocodeai/octocode-core/schemas";var Bd={limit:v(1,100).optional(),page:q.default(1)},zd=re(Ud,Bd),Qd=X(ce(Ud,Bd)),lF=k.object({base:k.string().optional(),shared:k.record(k.string(),k.union([k.string(),k.number(),k.boolean()])).optional(),responsePagination:Ae.responsePagination,results:k.array(k.object({id:k.string(),data:k.object({files:k.array(k.object({owner:k.string(),repo:k.string(),path:k.string(),queryId:k.string().optional(),matches:k.array(k.object({value:k.string().optional(),pathOnly:k.boolean().optional(),matchIndices:k.array(k.object({start:k.number(),end:k.number(),lineOffset:k.number()})).optional(),url:k.string().optional()}))})),pagination:k.object({currentPage:k.number(),totalPages:k.number(),perPage:k.number(),totalMatches:k.number(),reportedTotalMatches:k.number().optional(),reachableTotalMatches:k.number().optional(),totalMatchesKind:k.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:k.boolean().optional(),hasMore:k.boolean(),nextPage:k.number().optional(),uniqueFileCount:k.number().optional()}).optional()})})),emptyQueries:k.array(k.object({id:k.string(),nonExistentScope:k.literal(!0).optional(),incompleteResults:k.literal(!0).optional()})).optional(),warnings:k.array(k.string()).optional(),errors:k.array(k.object({id:k.string(),error:k.string()})).optional()});function Zb(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function qb(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function eS(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function jd(e){let{content:t,reviewMode:n}=e,r=Zb(t,n),o=qb(t,n),i=eS(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}function pF(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function js(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Ko(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function $s(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function Xo(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 Vd(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Wd(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function tS(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Yo(e,t,n){return tS({...Wd(e,t),...n})}function $d(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Yo(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function zs(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Yo(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function nS(e,t,n){return{target:Wd(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function Wo(e){return String(e.path??e.filename??"")}function rS(e,t){return{path:Wo(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function oS(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 iS(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=oS(r,n.comments),i=js(t),s=i?o.filter(u=>Ko(u.body,i)):o,{items:a,pagination:c}=$s(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(u=>{let l=Xo(typeof u.body=="string"?u.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:u.id,author:u.author,commentType:u.commentType??"discussion",path:u.path,line:u.line,...u.in_reply_to_id!=null?{in_reply_to_id:u.in_reply_to_id}:{},...l?{body:l.content,bodyPagination:l.pagination}:{bodyPreview:Vd(typeof u.body=="string"?u.body:"")},createdAt:u.createdAt,updatedAt:u.updatedAt}}),commentPagination:c}}function sS(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=js(t);return{reviews:(o?r.filter(s=>Ko(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Xo(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 aS(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=$s(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function cS(e){return e.split(`
|
|
39
39
|
`).filter(t=>{if(!t.startsWith("+"))return!0;let n=t.slice(1).trim();return n!==""&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")}).map(t=>t.startsWith("+")?"+"+t.slice(1).replace(/\s*\/\/.*$/,"").trimEnd():t).join(`
|
|
40
|
-
`)}function
|
|
40
|
+
`)}function uS(e){return e.replace(/\n{3,}/g,`
|
|
41
41
|
|
|
42
|
-
`)}function Ig(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(Rr(p))):o,a=qo(t),c=a?s.filter(p=>br(Rr(p),a)||br(p.patch,a)):s,{items:l,pagination:d}=ei(c,t.filePage??t.page??1,t.itemsPerPage??20),u=n.patches.mode!=="none",m=l.map(p=>{let f=Tg(p,!1);if(!u||typeof p.patch!="string")return f;let h=r&&!a?Lg(p.patch):p.patch,y=Cr(h,t.charOffset??0,t.charLength??12e3);return{...f,patch:y?.content??"",...y?{patchPagination:y.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:d}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(Rr).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function ht(e){return typeof e=="object"&&e!==null}function Zo(e){if(ht(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function ti(e){if(ht(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function kg(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function vg(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!ht(n))continue;let r=ti(n.patchPagination);if(r?.hasMore)return r}}function Fg(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!ht(n))continue;let r=ti(n.bodyPagination);if(r?.hasMore)return r}}function Mg(e,t,n,r){let o={},i=ti(e.bodyPagination),s=Zo(e.filePagination),a=Zo(e.commentPagination),c=Zo(e.commitPagination),l=vg(e),d=Fg(e),u=kg(n);i&&(o.body={...i,nextQuery:Hc(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:Jo(t,r,u,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:Jo(t,r,{comments:n.comments},"commentPage",a)}),d?.hasMore&&d.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...d,nextQuery:Sr(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:d.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:Jo(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Hc(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return ht(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Sr(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function Ng(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function $c(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?Og(s):s,c=n.body?Cr(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,d=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,f={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:Dc(typeof e.body=="string"?e.body:void 0)}:{},...d?{next:Eg(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...Ig(e,t,n,r),...xg(e,t,n),..._g(e,t,n),...Ag(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},h=Mg(f,t,n,i);return Ng(f),h&&(f.contentPagination=h),f}function Uc(e,t){let n=e[0];if(!n)return[];let r=["PR response includes a `next` map \u2014 re-call with next.target + one content key (e.g. next.getBody, next.getAllPatches, next.getComments) to fetch a surface."],o=ht(n.contentPagination)?n.contentPagination:{},i={body:{label:"body charOffset",field:"charOffset"},changedFiles:{label:"changedFiles filePage",field:"filePage"},comments:{label:"comments commentPage",field:"commentPage"},commentBody:{label:"comment body commentBodyOffset",field:"commentBodyOffset"},commits:{label:"commits commitPage",field:"commitPage"},patches:{label:"patches charOffset",field:"charOffset"},filePaths:{label:"file paths filePage",field:"filePage"}};for(let[s,{label:a,field:c}]of Object.entries(i)){let l=o[s];if(!ht(l)||l.hasMore!==!0)continue;let u=(ht(l.nextQuery)?l.nextQuery:{})[c];typeof u=="number"&&r.push(`More PR ${a}=${u}.`)}return t.patches.mode==="none"&&r.push('Patches not included \u2014 request content.patches={mode:"all"} or {mode:"selected",files:[...]}.'),t.comments||r.push("Comments not included \u2014 request content.comments={discussion:true,reviewInline:true}."),r}import{z as _t}from"zod";import{GitHubPullRequestSearchQuerySchema as Bc}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Hg}from"@octocodeai/octocode-core/schemas/outputs";var zc={perPage:F(1,100).optional().default(30),prNumber:F(1,1e9).optional(),limit:F(1,100).optional().default(30),page:q.default(1),filePage:q.optional(),commentPage:q.optional(),commitPage:q.optional(),itemsPerPage:F(1,100).optional().default(20),charOffset:F(0,1e8).optional(),commentBodyOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional()},Dg=ae(Bc,zc),Pr=te(Bc,zc),Qc=X(Dg),$L=Hg.extend({results:_t.array(_t.object({id:_t.string().optional(),status:_t.string().optional(),data:_t.object({pull_requests:_t.array(_t.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...xe});async function jc(e){let{queries:t,authInfo:n}=e,r=Be(n);return J(t,async(o,i)=>{try{let s=Pr.safeParse(o);if(!s.success){let k=s.error.issues.map(Y=>Y.message).join("; ");return A(`Validation error: ${k}`,o)}if(s.data.type==="commits"){let k=s.data;if(!k.owner||!k.repo)return A("owner and repo are required for commits mode.",o);let Y=k.path,fe=Y&&!Y.endsWith("/")?"file":"repo";if(fe==="file"&&!Y)return A("path is required when querying a specific file in commits mode.",o);let _e=await Ea({type:fe,owner:k.owner,repo:k.repo,path:Y,branch:k.branch,since:k.since,until:k.until,author:k.author,page:Number(k.page)||1,perPage:Number(k.perPage)||30,includeDiff:!!k.includeDiff,charLength:typeof k.charLength=="number"?k.charLength:void 0},n);if(Tt(_e)){let _n=_e.status===429||_e.error?.toString().toLowerCase().includes("rate limit")||!1;return A(_e,o,{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,hintContext:{type:"commits",path:Y,isRateLimited:_n,status:_e.status,retryAfter:_e.retryAfter},hintSourceError:_e})}let{commits:Ve,pagination:Zt}=_e.data,Bi=Ve.length>0,Ur=[];Zt.hasMore&&Zt.nextPage&&Ur.push(`${Ve.length} commit${Ve.length===1?"":"s"} returned \u2014 re-call with page:${Zt.nextPage} for more.`);let zi=/#(\d+)/;if(Bi){let _n=Ve.find(An=>{let qt=An.messageHeadline;return typeof qt=="string"&&zi.test(qt)});if(_n){let An=_n.messageHeadline,qt=zi.exec(An);qt&&Ur.push(`Merge commits embed PR refs \u2014 e.g. "${An}" \u2192 use ghHistoryResearch(owner:"${k.owner}", repo:"${k.repo}", prNumber:${qt[1]}) to read that PR's body, diffs, comments, and reviews.`)}}return Se(o,_e.data,Bi,S.GITHUB_SEARCH_PULL_REQUESTS,{hintContext:{type:"commits",path:Y,matchCount:Ve.length,hasMorePages:Zt.hasMore},extraHints:Ur,rawResponse:_e.rawResponseChars})}let a=r(),c={...s.data},l=Mc(c),d=[],u=c.prNumber!==void 0;!u&&Nc(l)&&d.push('Broad PR search returns metadata only. Re-call with prNumber and content selectors (body, changedFiles, patches, comments, commits) or reviewMode="full" to fetch PR content.'),u||(c.content=void 0,c.reviewMode=void 0);let m=!u&&((c.keywordsToSearch?.length??0)>0||!!c.query);if(m&&!c.created&&(c.state==="merged"||c.merged===!0)&&!c.sort&&!c.order?d.push(`To find the PR that first introduced a feature: sort:"created" order:"asc". Use match:["title"] for title-only and query:'"exact phrase"' for phrase matching.`):m&&!c.created&&!c.sort&&!c.order&&d.push('Archaeology tip: add state:"merged" sort:"created" order:"asc" to find the oldest matching merged PR. Use match:["title"] for title-only matching.'),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return A("At least one valid search parameter, filter, or PR number is required.",o);let h=await ft(c,()=>a.provider.searchPullRequests(bc(c)));if(h.ok===!1)return h.result;let y=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:b,resultData:g,pagination:C}=Sc(h.response.data,{includeFileChanges:y}),T=c.prNumber!==void 0?void 0:C;c.prNumber!==void 0&&delete g.pagination;let P=!u&&(!!o.content||!!o.reviewMode),x={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},I=c.minify==="standard",Q=u,E=b.map(k=>$c(k,c,P?x:l,I,Q));g.pull_requests=E,!u&&c.concise===!0&&(g.pull_requests=E.map(k=>{let Y=k;return`#${Y.number} ${Y.title}`}));let w=E.length>0,O=T?Wt({currentPage:T.currentPage,totalPages:T.totalPages,hasMore:T.hasMore,totalMatches:T.totalMatches,entriesPerPage:T.perPage},"PRs"):[],$=w?[`Found ${E.length} PR${E.length===1?"":"s"}.`,...Q?Uc(E,l):[]]:[],M=[],N=b.filter(k=>(typeof k.changedFilesCount=="number"?k.changedFilesCount:Array.isArray(k.fileChanges)?k.fileChanges.length:0)>30);if(N.length>0){let k=N.map(fe=>`#${fe.number}`).join(", "),Y=Math.max(...N.map(fe=>typeof fe.changedFilesCount=="number"?fe.changedFilesCount:Array.isArray(fe.fileChanges)?fe.fileChanges.length:0));M.push(`Large PR(s) ${k} have ${Y}+ file changes.`)}let se=l.body||l.changedFiles||l.patches.mode!=="none"||!!l.comments||l.reviews||!!l.commits;!y&&!(u&&se)&&b.filter(Y=>typeof Y.changedFilesCount=="number"&&Y.changedFilesCount>0).length>0&&M.push('Metadata mode: changedFiles details omitted (changedFilesCount available). Re-call with prNumber + content.changedFiles=true for file paths, content.patches={mode:"selected",files:["src/foo.ts"]} for targeted diffs, or reviewMode="full" for all content in one call.');let le=u&&typeof c.matchString=="string"&&c.matchString.trim()?[`matchString filter active \u2014 pagination totals count only items matching "${c.matchString.trim()}"; drop matchString for the full set.`]:[],V=Gg({data:g,pullRequests:b,extraHints:[...$,...O,...d,...M,...le]},c);return Se(c,V.data,w,S.GITHUB_SEARCH_PULL_REQUESTS,{hintContext:{matchCount:E.length,state:c.state,owner:c.owner,repo:c.repo,author:c.author,keywords:c.keywordsToSearch,prNumber:c.prNumber,prMatch:c.match},extraHints:V.extraHints,rawResponse:h.response.rawResponseChars})}catch(s){return ge(s,o)}},{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"],peerHints:!0},e)}function Gg(e,t){return{data:e.data,extraHints:e.extraHints}}function Vc(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 $g(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function rO(e){let t=e,r=[`${t.owner?`${t.owner}/`:""}${t.repo}`];if(typeof t.stars=="number"&&r.push(`${t.stars} stars`),typeof t.forksCount=="number"&&t.forksCount>0&&r.push(`${t.forksCount} forks`),typeof t.openIssuesCount=="number"&&t.openIssuesCount>0&&r.push(`${t.openIssuesCount} issues`),t.language&&r.push(t.language),t.license&&r.push(t.license),t.pushedAt&&r.push(t.pushedAt.slice(0,10)),t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"&&r.push(`@${t.defaultBranch}`),t.visibility&&t.visibility!=="public"&&r.push(t.visibility),Array.isArray(t.topics)&&t.topics.length>0&&r.push(`#${t.topics.slice(0,4).join(",")}`),t.description&&t.description!=="No description"){let o=t.description.replace(/\s+/g," ").trim();r.push(o.length>100?`${o.slice(0,99)}...`:o)}return r.join(" | ")}function Ug(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map($g)},extraHints:n?["Minimal owner/repo list \u2014 re-run without concise (or ghViewRepoStructure) to dive into a chosen repo."]:[]}}function ri(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function oi(e){return!!(e.keywords&&e.keywords.length>0)}function Bg(e){return!!(oi(e)||ri(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function Wc(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function zg(e){let t=ri(e),n=oi(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:Wc(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:Wc(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function Qg(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=Vg(n,r,t.sort);if(o!==0)return o;let i=Kc(r,t)-Kc(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:ni(n).localeCompare(ni(r))})}function Vg(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 Vc(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function Kc(e,t){let n=Wg(t),r=ni(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(d=>d.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((d,u)=>o===u||r===u?d+80:o.includes(u)||r.includes(u)?d+40:s.includes(u)?d+35:i.includes(u)?d+10:d,0)+(c&&a===c?20:0)}function Wg(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function ni(e){return`${e.owner}/${e.repo}`}function Kg(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore}}function Yg(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function Xg(e){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages} for merged topic+keyword results (~${e.totalMatches??0} upper-bound total). Next: page=${e.currentPage+1}.`]:[]}function Yc(e){return e.flatMap(t=>{let n=t.label==="topics"?"Topic search":t.label==="keywords"?"Keyword search":"Search",r=t.response.error||"Provider error";return`${n} failed: ${r}`})}function Jg(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??G(n.response.data??n.response)),0)}var Zg=100;function qg(e,t,n=!1,r=0){if(t)return n&&r>Zg&&!e.owner&&!e.language&&!e.stars?['Large result set with no owner/language/stars filter \u2014 add owner="<org>" to scope to a specific org, language="<lang>" to restrict by language, or stars=">100" to surface established repos.']:void 0;let o=ri(e),i=oi(e),s=typeof e.stars=="string"?e.stars:void 0,a=typeof e.created=="string"?e.created:void 0,c=typeof e.updated=="string"?e.updated:void 0,l=[];o&&i?l.push("No match for topics AND keywords. Drop topics, then keywords."):o?l.push("No topic match. Drop one, try synonyms, or use keywords."):i&&l.push("No keyword match. Drop the rarest, try synonyms, or use topics.");let d=[];if(s&&d.push(`stars="${s}"`),a&&d.push(`created="${a}"`),c&&d.push(`updated="${c}"`),d.length>0&&l.push(`Filters (${d.join(", ")}) \u2014 try widening/removing.`),l.length!==0)return l}async function Xc(e){let{queries:t,authInfo:n}=e,r=Be(n);return J(t,async(o,i)=>{try{if(!Bg(o))return A("At least one repository search term or filter is required.",o);let s=r(),a=zg(o),{successes:c,failures:l}=await sc(a.map(k=>({meta:{label:k.label,query:k.query},operation:()=>s.provider.searchRepos(yc(k.query))}))),d=c.map(k=>({label:k.meta.label,query:k.meta.query,response:k.response})),u=l.map(k=>({label:k.meta.label,query:k.meta.query,response:k.response}));if(d.length===0){let k=u[0];return k?lr(k.response,o):ge(new Error("Repository search produced no provider results"),o)}let m=o.limit,p=jg(Qg(d.flatMap(k=>Rc(k.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,h=d.some(k=>k.response.data.nonExistentScope),y=f.length===0&&h?[`Owner "${o.owner??"?"}" doesn't exist or isn't searchable \u2014 verify spelling/access, not filters.`]:[],b=d.length===1?d[0]:void 0,g=d.length>1,C=g?Yg(d):b?.response.data.pagination,T=C?g?Xg(C):Wt(C,"repos"):[],P=C?Kg(C):void 0,x=o.page,I=C?.totalPages??0,Q=typeof x=="number"&&I>0&&x>I&&f.length===0,E=Q?[`page ${x} exceeds totalPages ${I} \u2014 last page is ${I}.`]:[],w=f.length>0,O=!!C?.hasMore,$=C?.totalMatches??C?.reachableTotalMatches??0,M=Q?void 0:qg(o,w,O,$),N=a.length>1&&d.length===1?[`Only ${b?.label??"one"} search succeeded; pagination reflects that subset.`,...Yc(u)]:Yc(u),se=Ug({repositories:f,pagination:P},o),ce=[];if(w){let k=f[0];k?.owner&&k?.repo&&ce.push(`Top result: ${k.owner}/${k.repo} \u2014 use ghViewRepoStructure to browse or ghSearchCode to search within it.`),f.length>=3&&ce.push("Use multiple ghViewRepoStructure queries in parallel to compare the layouts of top results.")}let V=[...E,...y,...se.extraHints,...N,...T,...M||[],...ce];return Se(o,se.data,w,S.GITHUB_SEARCH_REPOSITORIES,{extraHints:V,hintContext:Q?{}:{keywords:o.keywords,owner:o.owner,language:o.language,topic:o.topicsToSearch?.[0]},rawResponse:Jg([...d,...u])})}catch(s){return ge(s,o)}},{toolName:S.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"],peerHints:!0},e)}import{z as W}from"zod";import{GitHubReposSearchSingleQuerySchema as Jc}from"@octocodeai/octocode-core/schemas";var Zc={limit:F(1,100).optional(),page:q.default(1)},qc=te(Jc,Zc),el=X(ae(Jc,Zc)),ey=W.object({owner:W.string(),repo:W.string(),stars:W.number().optional(),forks:W.number().optional(),openIssuesCount:W.number().optional(),language:W.string().optional(),license:W.string().optional(),description:W.string().optional(),homepage:W.string().optional(),pushedAt:W.string().optional(),createdAt:W.string().optional(),defaultBranch:W.string().optional(),topics:W.array(W.string()).optional(),visibility:W.string().optional(),url:W.string().optional(),updatedAt:W.string().optional()}),ty=W.object({currentPage:W.number(),totalPages:W.number(),hasMore:W.boolean(),perPage:W.number().optional(),totalMatches:W.number().optional(),reportedTotalMatches:W.number().optional(),reachableTotalMatches:W.number().optional(),totalMatchesKind:W.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:W.boolean().optional()}).optional(),ny=W.object({repositories:W.array(W.union([W.string(),ey])).optional(),pagination:ty}).passthrough(),hO=W.object({results:W.array(W.object({id:W.string().optional(),status:W.string().optional(),data:ny.optional()}).passthrough()).optional()}).extend(xe);var ry=5;function oy(e){if(!e||typeof e!="object")return[];let t=[],n=[];for(let r of Object.values(e)){let o=r;if(Array.isArray(o.folders))for(let i of o.folders)typeof i=="string"&&t.push(`${i}/`);if(Array.isArray(o.files))for(let i of o.files)typeof i=="string"&&n.push(i)}return[...t,...n]}function iy(e,t){return oy(e).slice(0,t)}function sy(e){return!e.owner||!e.repo?void 0:`${e.truncated||e.hasMore?"Structure page is partial":"Structure complete"} - use ghSearchCode(owner="${e.owner}", repo="${e.repo}") to find patterns, or ghGetFileContent to read specific files.`}function ay(e,t,n){if(!n)return[];let r=iy(e,ry);if(r.length===0)return[];let o=t>r.length?` (+${t-r.length} more)`:"";return[`Next paths: ${r.join(", ")}${o}`]}function cy(e){let t=e.currentPage??1,n=e.totalPages??t+1,r=e.totalEntries,o=e.entriesPerPage,i=typeof r=="number"&&typeof o=="number"?` (showing ${Math.min(t*o,r)} of ${r})`:"";return`Page ${t}/${n}${i}. Next: page=${t+1}`}function ly(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...Array.isArray(e.hints)?{hints:e.hints}:{}}}function uy(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&an(o))continue;let i=r.files.filter(a=>!Ut(a)),s=r.folders.filter(a=>!an(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function tl(e){let{queries:t,authInfo:n}=e,r=Be(n);return J(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await ft(o,()=>s.provider.getRepoStructure(Ec(o,c)));if(l.ok===!1)return ly(l.result,o);let d=Object.keys(l.response.data.structure??{}).length>0,u=uy(l.response.data.structure),m=Object.keys(u).length>0,p=d&&!m,f=!!l.response.data.summary?.truncated,h=Tc(l.response.data,o,u,c),y="branchFallback"in h?h.branchFallback:void 0,b=l.response.data.hints||[],g=y?[`WARNING: Branch '${String(y.requestedBranch)}' not found. Showing '${String(y.actualBranch)}' (default branch). Re-query with the correct branch name if branch-specific results are required.`]:[],C=Object.values(u).reduce((w,O)=>w+O.files.length+O.folders.length,0),T=h.pagination,P=!!T?.hasMore,x=m&&!P?sy({owner:o.owner,repo:o.repo,truncated:f,hasMore:!1}):void 0,I=P?[cy(T??{})]:[...b,...x?[x]:[]],Q=[];if(P){let w=T?.currentPage??1,O=T?.totalPages;Q.push(`Tree paginated (page ${w}${O?` of ${O}`:""}); use page=${w+1} to fetch the remaining entries.`)}else f&&Q.push(`Tree truncated at maxDepth=${o.maxDepth??"default"}; re-query with a deeper maxDepth or a more specific path to see the rest.`);let E=dy({data:h,entryCount:C,wasTruncated:f,extraHints:I},o);return Se(o,E.data,m,S.GITHUB_VIEW_REPO_STRUCTURE,{hintContext:{entryCount:C,path:o.path,depth:o.maxDepth,branch:o.branch,wasFilteredToEmpty:p,flagFiles:Object.values(u).flatMap(w=>w.files.filter(O=>/(Mode|Config|Flag|Feature)\.[A-Za-z0-9]+$/.test(O)))},prefixHints:g,extraHints:[...Q,...E.extraHints],rawResponse:l.response.rawResponseChars})}catch(s){return ge(s,o,"Failed to explore repository structure")}},{toolName:S.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"],peerHints:!0},e)}function dy(e,t){let n=ay(e.data.structure,e.entryCount,e.wasTruncated);return{data:e.data,extraHints:[...n,...e.extraHints]}}import{GitHubViewRepoStructureQuerySchema as nl}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as py}from"@octocodeai/octocode-core/schemas/outputs";var rl={maxDepth:F(0,20).optional(),page:q.default(1),itemsPerPage:F(1,200).optional()},ol=te(nl,rl),il=X(ae(nl,rl)),IO=py.extend(xe);import{z as my}from"zod";import{LocalBinaryInspectQuerySchema as fy}from"@octocodeai/octocode-core/schemas";var hy={entryPageNumber:q.default(1),matchStringContextLines:F(0,50).default(3),charLength:F(1,5e4).optional(),page:q.default(1)},sl=my.object({...fy.shape,...hy}),Er=sl.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),al=X(sl,{maxQueries:5});import{promises as Oy}from"fs";import{securityRegistry as Iy}from"octocode-security/registry";import cl from"path";import{pathValidator as gy}from"octocode-security/pathValidator";import{getConfigSync as yy}from"octocode-shared";function Ry(e,t,n,r){let o=[],i=e!==r?` (resolved to: ${r})`:"";return o.push(`CWD: ${n}`),t?.includes("outside allowed")?o.push(`Fix: Use absolute path within workspace, e.g. path="${n}/..."${i}`):t?.includes("Permission denied")?o.push("Fix: Check file/directory permissions"):t?.includes("Symlink")||t?.includes("symlink")?o.push("Fix: Symlink target may be outside allowed directories"):(t?.includes("ENOENT")||t?.includes("not found"))&&o.push(`Fix: Path not found. Use absolute path, e.g. path="${n}/..."${i}`),o}function Ce(e,t){if(!e.path?.trim()){let s=Fe.pathValidationFailed("","path is required");return{isValid:!1,errorResult:A(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||yy().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=cl.isAbsolute(r)?r:cl.resolve(n,r),i=gy.validate(o);if(!i.isValid){let s=Fe.pathValidationFailed(e.path,i.error),a=Ry(e.path,i.error,n,o);return{isValid:!1,errorResult:A(s,e,{toolName:t,hintContext:{errorType:"permission",path:e.path,originalError:i.error},extra:{cwd:n,resolvedPath:o},customHints:a})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function BO(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:Fe.outputTooLarge(e,r).errorCode,hints:[`Found ${e} ${o}${e===1?"":"s"} - exceeds safe limit of ${r}`,"Use charLength to paginate through results",i?"Detailed results increase size - consider using charLength for pagination":"Consider using charLength to paginate large result sets"]}:{shouldBlock:!1}}import{validateCommand as by}from"octocode-security/commandValidator";async function Oe(e,t=[],n={}){let r=by(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=pr(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024}=n,l=await wt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(l.error)throw l.error;return{success:l.success,code:l.exitCode,stdout:l.stdout,stderr:l.stderr}}var ll=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],ul=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],dl=[".dmg",".rar",".cpgz"],Sy=[".aar",".yaa"];function At(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function Cy(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},d={command:"7z",args:i},u={command:"7zz",args:i},m={command:"aa",args:s};return At(Sy,e)?[m]:At(dl,e)?[d,u,l,c,a]:At(ul,e)?[l,d,u,c,a]:At(ll,e)?[a,c,l,d,u]:[c,a,l,d,u]}function Py(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return At(dl,e)?[s,a,o,r,n]:At(ul,e)?[o,s,a,r,n]:At(ll,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function pl(e){let t=[];for(let n of e){let r=await Oe(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function Ey(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
|
|
42
|
+
`)}function lS(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(Wo(p))):o,a=js(t),c=a?s.filter(p=>Ko(Wo(p),a)||Ko(p.patch,a)):s,{items:u,pagination:l}=$s(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=u.map(p=>{let f=rS(p,!1);if(!d||typeof p.patch!="string")return f;let g=r&&!a?cS(p.patch):p.patch,h=Xo(g,t.charOffset??0,t.charLength??12e3);return{...f,patch:h?.content??"",diff:Pr(h?.content),...h?{patchPagination:h.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:l}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(Wo).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function wr(e){return typeof e=="object"&&e!==null}function Qs(e){if(wr(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(wr(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function dS(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function pS(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!wr(n))continue;let r=Vs(n.patchPagination);if(r?.hasMore)return r}}function fS(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!wr(n))continue;let r=Vs(n.bodyPagination);if(r?.hasMore)return r}}function mS(e,t,n,r){let o={},i=Vs(e.bodyPagination),s=Qs(e.filePagination),a=Qs(e.commentPagination),c=Qs(e.commitPagination),u=pS(e),l=fS(e),d=dS(n);i&&(o.body={...i,nextQuery:$d(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:zs(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:zs(t,r,{comments:n.comments},"commentPage",a)}),l?.hasMore&&l.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...l,nextQuery:Yo(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:l.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:zs(t,r,{commits:n.commits},"commitPage",c)}),u&&n.patches.mode!=="none"&&(o.patches={...u,nextQuery:$d(t,r,{patches:n.patches},u,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return wr(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Yo(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function gS(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Kd(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?uS(s):s,c=n.body?Xo(a,t.charOffset??0,t.charLength??12e3):void 0,u=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,l=o!==void 0?o:u,m=t.prNumber!==void 0||t.verbose===!0,f={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:Vd(typeof e.body=="string"?e.body:void 0)}:{},...l?{next:nS(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...lS(e,t,n,r),...iS(e,t,n),...sS(e,t,n),...aS(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=mS(f,t,n,i);return gS(f),g&&(f.contentPagination=g),f}import{z as Jt}from"zod";import{GitHubPullRequestSearchQuerySchema as Yd}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as hS}from"@octocodeai/octocode-core/schemas/outputs";var Xd={perPage:v(1,100).optional().default(30),prNumber:v(1,1e9).optional(),limit:v(1,100).optional().default(30),page:q.default(1),filePage:q.optional(),commentPage:q.optional(),commitPage:q.optional(),itemsPerPage:v(1,100).optional().default(20),charOffset:v(0,1e8).optional(),commentBodyOffset:v(0,1e8).optional(),charLength:v(1,5e4).optional()},yS=ce(Yd,Xd),Jo=re(Yd,Xd),Jd=X(yS),TF=hS.extend({results:Jt.array(Jt.object({id:Jt.string().optional(),status:Jt.string().optional(),data:Jt.object({pull_requests:Jt.array(Jt.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Ae});async function Zd(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{let s=Le(Jo,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let _=s.data;if(!_.owner||!_.repo)return L("owner and repo are required for commits mode.",o);let I=_.path,j=I&&!I.endsWith("/")?"file":"repo";if(j==="file"&&!I)return L("path is required when querying a specific file in commits mode.",o);let w=await kl({type:j,owner:_.owner,repo:_.repo,path:I,branch:_.branch,since:_.since,until:_.until,author:_.author,page:Number(_.page)||1,perPage:Number(_.perPage)||30,includeDiff:!!_.includeDiff,charLength:typeof _.charLength=="number"?_.charLength:void 0},n);if(Yt(w))return L(w,o,{toolName:S.GITHUB_SEARCH_PULL_REQUESTS});let{commits:A}=w.data,Q=A.length>0;return Pe(o,w.data,Q,S.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:w.rawResponseChars})}let a=r(),c={...s.data},u=jd(c),l=c.prNumber!==void 0;if(l||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return L("At least one valid search parameter, filter, or PR number is required.",o);let m=await kt(c,()=>a.provider.searchPullRequests(Ld(c)));if(m.ok===!1)return m.result;let p=l?u.changedFiles||u.patches.mode!=="none":!1,{pullRequests:f,resultData:g}=Od(m.response.data,{includeFileChanges:p});c.prNumber!==void 0&&delete g.pagination;let h=!l&&(!!o.content||!!o.reviewMode),R={...u,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},b=c.minify==="standard",P=l,x=f.map(_=>Kd(_,c,h?R:u,b,P));g.pull_requests=x,!l&&c.concise===!0&&(g.pull_requests=x.map(_=>{let I=_;return`#${I.number} ${I.title}`}));let C=x.length>0;return Pe(c,g,C,S.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:m.response.rawResponseChars})}catch(s){return Ee(s,o,void 0,S.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}function qd(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 RS(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function BF(e){let t=e,r=[`${t.owner?`${t.owner}/`:""}${t.repo}`];if(typeof t.stars=="number"&&r.push(`${t.stars} stars`),typeof t.forksCount=="number"&&t.forksCount>0&&r.push(`${t.forksCount} forks`),typeof t.openIssuesCount=="number"&&t.openIssuesCount>0&&r.push(`${t.openIssuesCount} issues`),t.language&&r.push(t.language),t.license&&r.push(t.license),t.pushedAt&&r.push(t.pushedAt.slice(0,10)),t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"&&r.push(`@${t.defaultBranch}`),t.visibility&&t.visibility!=="public"&&r.push(t.visibility),Array.isArray(t.topics)&&t.topics.length>0&&r.push(`#${t.topics.slice(0,4).join(",")}`),t.description&&t.description!=="No description"){let o=t.description.replace(/\s+/g," ").trim();r.push(o.length>100?`${o.slice(0,99)}...`:o)}return r.join(" | ")}function bS(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(RS)}}}function np(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function rp(e){return!!(e.keywords&&e.keywords.length>0)}function SS(e){return!!(rp(e)||np(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function ep(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function CS(e){let t=np(e),n=rp(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:ep(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:ep(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function PS(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 ES(e,t){return[...e].sort((n,r)=>{let o=TS(n,r,t.sort);if(o!==0)return o;let i=tp(r,t)-tp(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Ws(n).localeCompare(Ws(r))})}function TS(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 qd(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function tp(e,t){let n=xS(t),r=Ws(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(l=>l.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((l,d)=>o===d||r===d?l+80:o.includes(d)||r.includes(d)?l+40:s.includes(d)?l+35:i.includes(d)?l+10:l,0)+(c&&a===c?20:0)}function xS(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Ws(e){return`${e.owner}/${e.repo}`}function _S(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function wS(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function AS(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??N(n.response.data??n.response)),0)}async function op(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{if(!SS(o))return L("At least one repository search term or filter is required.",o);let s=r(),a=CS(o),{successes:c,failures:u}=await md(a.map(C=>({meta:{label:C.label,query:C.query},operation:()=>s.provider.searchRepos(wd(C.query))}))),l=c.map(C=>({label:C.meta.label,query:C.meta.query,response:C.response})),d=u.map(C=>({label:C.meta.label,query:C.meta.query,response:C.response}));if(l.length===0){let C=d[0];return C?Go(C.response,o):Ee(new Error("Repository search produced no provider results"),o,void 0,S.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=ES(PS(l.flatMap(C=>Ad(C.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,g=l.length===1?l[0]:void 0,R=l.length>1?wS(l):g?.response.data.pagination,b=R?_S(R):void 0,P=f.length>0,x=bS({repositories:f,pagination:b},o);return Pe(o,x.data,P,S.GITHUB_SEARCH_REPOSITORIES,{rawResponse:AS([...l,...d])})}catch(s){return Ee(s,o,void 0,S.GITHUB_SEARCH_REPOSITORIES)}},{toolName:S.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}import{z as B}from"zod";import{GitHubReposSearchSingleQuerySchema as ip}from"@octocodeai/octocode-core/schemas";var sp={limit:v(1,100).optional(),page:q.default(1)},ap=re(ip,sp),cp=X(ce(ip,sp)),LS=B.object({owner:B.string(),repo:B.string(),stars:B.number().optional(),forks:B.number().optional(),openIssuesCount:B.number().optional(),language:B.string().optional(),license:B.string().optional(),description:B.string().optional(),homepage:B.string().optional(),pushedAt:B.string().optional(),createdAt:B.string().optional(),defaultBranch:B.string().optional(),topics:B.array(B.string()).optional(),visibility:B.string().optional(),url:B.string().optional(),updatedAt:B.string().optional()}),OS=B.object({currentPage:B.number(),totalPages:B.number(),hasMore:B.boolean(),perPage:B.number().optional(),totalMatches:B.number().optional(),reportedTotalMatches:B.number().optional(),reachableTotalMatches:B.number().optional(),totalMatchesKind:B.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:B.boolean().optional(),nextPage:B.number().optional()}).optional(),IS=B.object({repositories:B.array(B.union([B.string(),LS])).optional(),pagination:OS}).passthrough(),qF=B.object({results:B.array(B.object({id:B.string().optional(),status:B.string().optional(),data:IS.optional()}).passthrough()).optional()}).extend(Ae);function kS(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function vS(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&cr(o))continue;let i=r.files.filter(a=>!xn(a)),s=r.folders.filter(a=>!cr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function up(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),u=await kt(o,()=>s.provider.getRepoStructure(vd(o,c)));if(u.ok===!1)return kS(u.result,o);let l=vS(u.response.data.structure),d=Object.keys(l).length>0,m=Fd(u.response.data,o,l,c);return Pe(o,m,d,S.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return Ee(s,o,"Failed to explore repository structure",S.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:S.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}import{GitHubViewRepoStructureQuerySchema as lp}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as FS}from"@octocodeai/octocode-core/schemas/outputs";var dp={maxDepth:v(0,20).optional(),page:q.default(1),itemsPerPage:v(1,200).optional()},pp=re(lp,dp),fp=X(ce(lp,dp)),gM=FS.extend(Ae);import{z as mp}from"zod";import{LocalBinaryInspectQuerySchema as MS}from"@octocodeai/octocode-core/schemas";var NS={entryPageNumber:q.default(1),matchStringContextLines:v(0,50).default(3),charLength:v(1,5e4).optional(),page:q.default(1),detailed:mp.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},gp=mp.object({...MS.shape,...NS}),Zo=gp.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),hp=X(gp,{maxQueries:5});import{promises as In}from"fs";import{join as Zs,basename as qo,dirname as YS,resolve as xp,sep as XS}from"node:path";import{securityRegistry as JS}from"@octocodeai/octocode-engine/registry";import yp from"path";import{pathValidator as DS}from"@octocodeai/octocode-engine/pathValidator";function ve(e,t){if(!e.path?.trim()){let s=De.pathValidationFailed("","path is required");return{isValid:!1,errorResult:L(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||ae().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=yp.isAbsolute(r)?r:yp.resolve(n,r),i=DS.validate(o);if(!i.isValid){let s=De.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:L(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function _M(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:De.outputTooLarge(e,r).errorCode,hints:[`Found ${e} ${o}${e===1?"":"s"} - exceeds safe limit of ${r}`,"Use charLength to paginate through results",i?"Detailed results increase size - consider using charLength for pagination":"Consider using charLength to paginate large result sets"]}:{shouldBlock:!1}}import{validateCommand as HS}from"@octocodeai/octocode-engine/commandValidator";async function On(e,t=[],n={}){let r=HS(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Bo(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024,tolerateOutputLimit:u=!1}=n,l=await Xt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(l.outputLimitExceeded&&u)return{success:!0,code:l.exitCode,stdout:l.stdout,stderr:l.stderr,truncated:!0};if(l.error)throw l.error;return{success:l.success,code:l.exitCode,stdout:l.stdout,stderr:l.stderr}}var Ks=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Ys=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Xs=[".dmg",".rar",".cpgz"],Rp=[".aar",".yaa"];function Ze(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function GS(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},u={command:"bsdtar",args:o},l={command:"7z",args:i},d={command:"7zz",args:i},m={command:"aa",args:s};return Ze(Rp,e)?[m]:Ze(Xs,e)?[l,d,u,c,a]:Ze(Ys,e)?[u,l,d,c,a]:Ze(Ks,e)?[a,c,u,l,d]:[c,a,u,l,d]}function US(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return Ze(Xs,e)?[s,a,o,r,n]:Ze(Ys,e)?[o,s,a,r,n]:Ze(Ks,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Js(e){let t=[];for(let n of e){let r=await On(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function BS(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
|
|
43
43
|
`).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
|
|
44
|
-
`)}async function
|
|
45
|
-
`).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function
|
|
46
|
-
`)
|
|
47
|
-
`),
|
|
48
|
-
`)
|
|
49
|
-
`),
|
|
50
|
-
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function oR(e,t,n){let r=t.split(`
|
|
51
|
-
`)
|
|
52
|
-
`).length,O=z.applyContentViewMinification(E,i),$=[z.SIGNATURES_ONLY_HINT];return e.matchString&&$.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),y&&$.push(y),U({path:e.path,content:O,contentView:"symbols",isSkeleton:!0,totalLines:w,...Tl(f,h),hints:$},f)}}let P=p.split(`
|
|
53
|
-
`).length,x=oR(e,p,t),I=E=>{let w=[...T?[T]:[],...y?[y]:[]];if(w.length===0)return E;let O=E.warnings??[];return{...E,warnings:[...O,...w]}};if(x.earlyResult){let E=x.earlyResult.content,w=g&&typeof E=="string"?{...x.earlyResult,content:z.applyContentViewMinification(E,i)}:x.earlyResult;return U(El(I(ii(cR(w,C),e,P)),f,h),f)}let Q=aR(e,x,s,P,t,g,C);return U(El(I(ii(Q,e,P)),f,h),f)}catch(n){return A(n,e,{toolName:S.LOCAL_FETCH_CONTENT})}}function ii(e,t,n){return e}import{z as lR}from"zod";import{FetchContentQuerySchema as xl}from"@octocodeai/octocode-core/schemas";var uR=lR.enum(["none","standard","symbols"]).optional().default("standard"),_l={startLine:Vt,endLine:Vt,contextLines:jt.default(5),charOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional(),minify:uR},dR=ae(xl,_l),Tr=te(xl,_l),Al=X(dR,{maxQueries:5});async function Ll(e){let{queries:t}=e;return J(t||[],async n=>Le({toolName:S.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Tr.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return A(`Validation error: ${i}`,n)}return await wl(r.data)}}),{toolName:S.LOCAL_FETCH_CONTENT,peerHints:!0},e)}import{z as pR}from"zod";import{FindFilesQuerySchema as mR}from"@octocodeai/octocode-core/schemas";var Ol={maxDepth:F(0,100).optional(),minDepth:F(0,100).optional(),limit:F(1,1e4).optional(),page:q.default(1),itemsPerPage:F(1,50).optional()},Il=pR.object(Object.fromEntries(Object.entries(mR.shape).filter(([e])=>e!=="regexType")));function fR(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 hR=ae(Il,Ol),wr=te(Il,Ol).superRefine(fR),kl=X(hR,{maxQueries:5});function Kt(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 Rn(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var gR=["node_modules","dist",".git","coverage","build",".next",".nuxt",".svelte-kit",".turbo",".cache",".parcel-cache","out","target",".octocode",".cursor",".vscode",".idea",".claude",".context"];function yR(e,t){let n=t??gR,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}function RR(e){let{query:t,currentPage:n,totalPages:r,shownCount:o,totalFiles:i,wasFileCapped:s,maxFiles:a,discoveredFileCount:c,hasConfigFiles:l,extraHints:d=[]}=e,u=t,m=[];Array.isArray(u.names)&&u.names.length>0&&m.push(`names: ${u.names.join(", ")}`),u.entryType&&m.push(`entryType: ${u.entryType==="f"?"files":u.entryType==="d"?"directories":String(u.entryType)}`);let p=f=>typeof f=="string"&&!Ml.test(f)?" (skipped: invalid format)":"";return u.modifiedBefore&&m.push(`modified before: ${u.modifiedBefore}${p(u.modifiedBefore)}`),u.modifiedWithin&&m.push(`modified within: ${u.modifiedWithin}${p(u.modifiedWithin)}`),u.sizeGreater&&m.push(`size > ${u.sizeGreater}`),u.sizeLess&&m.push(`size < ${u.sizeLess}`),Array.isArray(u.excludeDir)&&u.excludeDir.length>0&&m.push(`excluding: ${u.excludeDir.join(", ")}`),[...d,...m.length>0?[`Active filters \u2014 ${m.join(" | ")}`]:[],...n<r?[`Page ${n}/${r} (${o} of ${i}). Next: page=${n+1}`]:[],...r>0&&n>r?[`Requested page ${n} is outside available range (1-${r}). Use page=${r} for the last page.`]:[],...s?[`Results capped at ${a} of ${c} discovered. All ${a} are reachable via page; to see the rest, narrow with names/entryType/time filters. Note: sorting applies only within the capped set \u2014 limit is a pre-sort discovery cap.`]:[],...i===0?oe(S.LOCAL_FIND_FILES,"empty",{fileCount:i,hasConfigFiles:l,path:t.path,names:t.names,modifiedWithin:t.modifiedWithin,sizeGreater:t.sizeGreater,sizeLess:t.sizeLess}):[u.entryType==="f"?`Found ${i} file${i===1?"":"s"}. Use localSearchCode to search or localGetFileContent to read.`:u.entryType==="d"?`Found ${i} director${i===1?"y":"ies"}. Use localViewStructure to browse or localSearchCode to search.`:`Found ${i} entr${i===1?"y":"ies"} \u2014 pass entryType="f" for files, entryType="d" for directories. Use localSearchCode or localGetFileContent.`]]}async function vl(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Ce(e,S.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:yR(i.path,i.excludeDir)},a=PR(s),c=e.limit??1e4,l=z.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),d=l.totalDiscovered,u=l.wasCapped,m=l.entries.map(M=>bR(M,r)),p=e.sortBy||"modified";SR(m,p,r);let f=[],h=CR(m,t,n),y=h.length,b=e.itemsPerPage||20,g=e.page||1,C=Math.max(1,Math.ceil(y/b)),T=(g-1)*b,P=Math.min(T+b,y),I=h.slice(T,P),Q=/\.(config|rc|env|json|ya?ml|toml|ini)$|^(\..*rc|config\.|\.env)/i,E=I.some(M=>Q.test(M.path.split("/").pop()||"")),w=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],O=[...a,...w],$={...y===0?{status:"empty"}:{},path:i.path,files:I,pagination:{currentPage:g,totalPages:C,filesPerPage:b,totalFiles:y,hasMore:g<C,...u?{totalFilesFound:d}:{}},...O.length>0&&{warnings:O},hints:RR({query:e,currentPage:g,totalPages:C,shownCount:I.length,totalFiles:y,wasFileCapped:u,maxFiles:c,discoveredFileCount:d,hasConfigFiles:E,extraHints:f})};return U(Fl($,e,{totalFiles:y}),l.entries.reduce((M,N)=>M+N.path.length,0))}catch(o){return A(o,e,{toolName:S.LOCAL_FIND_FILES})}}function bR(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 Fl(e,t,n){return e}function SR(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 CR(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=Kt(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var Ml=/^\d+[hdwm]$/;function PR(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!Ml.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}async function Nl(e){let{queries:t}=e;return J(t||[],async n=>Le({toolName:S.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=wr.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return A(`Validation error: ${i}`,n)}return await vl(r.data)}}),{toolName:S.LOCAL_FIND_FILES,peerHints:!0},e)}import{RipgrepQuerySchema as Hl}from"@octocodeai/octocode-core/schemas";var Dl={contextLines:jt,matchContentLength:F(1,1e5).optional().default(500),maxMatchesPerFile:F(1,1e5).optional(),maxFiles:F(1,1e5).optional(),matchPage:q.optional(),itemsPerPage:F(1,1e3).optional(),page:q.default(1)},ER=ae(Hl,Dl),gt=te(Hl,Dl,{strict:!0}),Gl=X(ER,{maxQueries:5});var bn=new Map,TR=parseInt(process.env.OCTOCODE_COMMAND_CHECK_TIMEOUT_MS||"5000",10)||5e3,$l={rg:{name:"ripgrep",versionFlag:"--version",tool:"localSearchCode"}};async function si(e,t=!1){if(!t&&bn.has(e))return bn.get(e);let n=$l[e];try{let r=On(),o=await dr(r,[n.versionFlag],TR),i={available:o,command:e,...o?{}:{error:`${n.name} (${e}) bundled binary is unavailable`}};return bn.set(e,i),i}catch(r){let o={available:!1,command:e,error:r instanceof Error?r.message:`Failed to check ${e} availability`};return bn.set(e,o),o}}async function xk(){let e=new Map,t=await Promise.all([si("rg")]);return e.set("rg",t[0]),e}function _k(e){let t=$l[e],n={rg:"Bundled ripgrep failed to load. Reinstall the MCP package to restore dist/runtime/rg."};return`${t.name} (${e}) is not available. ${n[e]}`}function Ak(){bn.clear()}import{validateRipgrepQuery as kR}from"@octocodeai/octocode-core/schemas/runtime";function Ul(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=z.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={matchCount:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}function wR(e){return e.trim().split(`
|
|
54
|
-
`).filter(Boolean).filter(n=>!Bl(n)).map(n=>({path:n,matchCount:1,matches:[]}))}function xR(e){return e.trim().split(`
|
|
55
|
-
`).filter(Boolean).filter(n=>!Bl(n)).map(n=>{let r=n.lastIndexOf(":");if(r===-1)return{path:n,matchCount:1,matches:[]};let o=n.slice(0,r),i=parseInt(n.slice(r+1),10);return{path:o,matchCount:isNaN(i)?1:i,matches:[]}})}function Bl(e){return/^\d+\s/.test(e)&&/\b(?:files|bytes|seconds|matches|searched|printed|spent)\b/.test(e)}function zl(e,t){let n=t.countLinesPerFile||t.countMatchesPerFile,r=t.filesOnly||t.filesWithoutMatch;if(n){let o=xR(e),i=o.reduce((s,a)=>s+(a.matchCount??0),0);return{files:o,stats:{matchCount:i}}}else return r?{files:wR(e),stats:{}}:Ul(e,t)}async function Yt(e,t,n,r,o){let i=e;i.sort((le,V)=>AR(le,V,t));let s=i,a=!1;t.maxFiles&&i.length>t.maxFiles&&(s=i.slice(0,t.maxFiles),a=!0);let c=s.length,l=!!(t.filesOnly||t.filesWithoutMatch),d=!!(t.countLinesPerFile||t.countMatchesPerFile),u=l||d,m=s.reduce((le,V)=>le+(V.matchCount??0),0),p=u?o?.matchCount??m:m,f=t,h=f.itemsPerPage||Me.DEFAULT_FILES_PER_PAGE,y=f.page||1,b=Math.ceil(c/h),g=(y-1)*h,C=Math.min(g+h,c),T=s.slice(g,C),P=f.maxMatchesPerFile||Me.DEFAULT_MATCHES_PER_PAGE,x=T.map(le=>{let V=le.matches?.length??0,k=Math.ceil(V/P),Y=Math.max(1,f.matchPage||1),fe=(Y-1)*P,_e=Math.min(fe+P,V),Ve=u?void 0:le.matches?.slice(fe,_e);return{path:le.path,...l?{}:{matchCount:d?le.matchCount||1:V},...Ve!==void 0&&{matches:Ve},pagination:!u&&V>P?{currentPage:Y,totalPages:k,matchesPerPage:P,totalMatches:V,hasMore:Y<k}:void 0}}),I=y<b?[`Page ${y}/${b} (${x.length} of ${c} files${l?"":`, ${p} matches`}). Next: page=${y+1}`]:b>0&&y>b?[`Page ${y} is outside range (1\u2013${b}). Use page=${b}.`]:[];a&&I.push(`Results limited to ${t.maxFiles} files (found ${i.length} matching)`);let Q=x.filter(le=>le.pagination?.hasMore);Q.length>0&&I.push(`Note: ${Q.length} file(s) have more matches \u2014 use matchPage=${(f.matchPage||1)+1} with maxMatchesPerFile to continue matches inside those files`);let E=_R(x,t,p),w=t,O=[],$=w.include;Array.isArray($)&&$.length>0&&O.push(`include: ${$.join(", ")}`);let M=w.exclude;Array.isArray(M)&&M.length>0&&O.push(`exclude: ${M.join(", ")}`);let N=w.excludeDir;Array.isArray(N)&&N.length>0&&O.push(`excludeDir: ${N.join(", ")}`);let se=w.langType;se&&O.push(`langType: ${se}`),w.caseSensitive&&O.push("case-sensitive"),w.wholeWord&&O.push("whole-word"),O.length>0&&E.unshift(`Active filters \u2014 ${O.join(" | ")}`);let ce={files:x,pagination:{currentPage:y,totalPages:b,filesPerPage:h,totalFiles:c,...l?{}:{totalMatches:p},hasMore:y<b,...a?{totalFilesFound:i.length}:{}},...r.length>0?{warnings:r}:{},hints:[...c>0&&!u?["Use localGetFileContent with the full path (prepend base to each returned path) and line numbers to read surrounding code.","Pass line numbers as lineHint to lspGetSemantics for definitions, references, or call flow."]:[],...c>0&&u?["Use localGetFileContent to read listed files, or rerun localSearchCode without filesOnly/count mode for matched snippets."]:[],...I,...E]};return Ql(ce,t,{totalMatches:p,totalFiles:c})}function Ql(e,t,n){return e}function _R(e,t,n){let r=[];if(n>100||e.length>20){let o=[];!t.langType&&!t.include&&o.push("add langType or include"),t.excludeDir?.length||o.push("add excludeDir"),(t.keywords?.length??0)<5&&o.push("lengthen pattern"),o.length>0&&r.push(`Large result set (${n} matches in ${e.length} files). Narrow: ${o.join(", ")}.`)}return r}function AR(e,t,n){let r=(t.matchCount??0)-(e.matchCount??0);return r!==0?r:e.path.localeCompare(t.path)}function xr(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};if(!e.fixedString){let o=LR(r);o&&t.push(`invalid regex: ${o}`)}return!e.fixedString&&OR(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&IR(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function LR(e){try{return new RegExp(e),null}catch(t){return t instanceof Error?t.message:"unknown regex parse error"}}function OR(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function IR(e){return/\(\?[=!<]/.test(e)}async function jl(e){let t=[],n=kR(e);if(!n.isValid)return A(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=gt.safeParse(e);if(!r.success){let y=r.error.issues.map(b=>b.message);return A(new Error(`Query validation failed: ${y.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return A(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}});let s=Ce(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=xr({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return A(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],d=new In,{command:u,args:m}=d.fromQuery(a).build(),p=await Oe(u,m);if(p.code===null){let y=Me.DEFAULT_EXEC_TIMEOUT_MS;return U({status:"error",error:`Search timed out after ${y/1e3} seconds.`,errorCode:B.COMMAND_TIMEOUT,searchEngine:"rg",hints:[`Search timed out after ${y/1e3} seconds.`,"Try a more specific path or add langType/include filters to narrow the search.","Use filesOnly=true for faster discovery.","Consider excluding large directories with excludeDir.",...l]},p.stdout.length+p.stderr.length)}if(p.code===1||p.success&&!p.stdout.trim())return U({status:"empty",searchEngine:"rg",warnings:[...t,...l],hints:oe(S.LOCAL_RIPGREP,"empty",{keywords:o.keywords,path:o.path,langType:o.langType,include:o.include,excludeDir:o.excludeDir,fixedString:o.fixedString,caseSensitive:o.caseSensitive,mode:o.mode})},p.stdout.length);if(!p.success){let b=p.code===2&&/No such file or directory/.test(p.stderr)?`Search path not found: ${o.path}. Verify it with localViewStructure or localFindFiles.`:`Ripgrep failed (exit code ${p.code}): ${p.stderr}`;return A(new Error(b),o,{toolName:S.LOCAL_RIPGREP,rawResponse:p.stdout.length+p.stderr.length})}let f=zl(p.stdout,o);!a.filesOnly&&p.stdout.length>Me.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p.stdout.length/1024)}KB).`);let h=await Yt(f.files,o,"rg",[...t,...l],f.stats);return U(h,p.stdout.length)}var vR="Using grep fallback because bundled ripgrep is unavailable; advanced ripgrep-only options may be ignored.";async function Wl(e,t){let n=[],r=gt.safeParse(e);if(!r.success){let h=r.error.issues.map(y=>y.message);return A(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n}})}let o=r.data;if(!o.path)return A(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n}});let s=Ce(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=xr({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return A(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...n,...c.warnings]}});let l=NR(n,c.warnings,t,o),{args:d,outputMode:u}=FR(a),m=await Oe("grep",d);if(m.code===null){let h=Me.DEFAULT_EXEC_TIMEOUT_MS;return U({status:"error",error:`Search timed out after ${h/1e3} seconds.`,errorCode:B.COMMAND_TIMEOUT,searchEngine:"grep",hints:[`Search timed out after ${h/1e3} seconds.`,"Try a more specific path or add include/exclude filters to narrow the search.","Use filesOnly=true for faster discovery.",...l]},m.stdout.length+m.stderr.length)}if(m.code===1||m.success&&!m.stdout.trim())return U({status:"empty",searchEngine:"grep",warnings:l,hints:[...oe(S.LOCAL_RIPGREP,"empty",{keywords:o.keywords,path:o.path,langType:o.langType,include:o.include,excludeDir:o.excludeDir,fixedString:o.fixedString,caseSensitive:o.caseSensitive,mode:o.mode,searchEngine:"grep"}),"Try with ripgrep for better results when bundled ripgrep is repaired."]},m.stdout.length);if(!m.success)return A(new Error(`grep fallback failed (exit code ${m.code}): ${m.stderr}`),o,{toolName:S.LOCAL_RIPGREP,rawResponse:m.stdout.length+m.stderr.length});let p=HR(m.stdout,u),f=await Yt(p.files,o,"grep",l,{matchCount:p.matchCount});return U({...f,searchEngine:"grep"},m.stdout.length)}function FR(e){let t=["-R","-H"];e.fixedString?t.push("-F"):e.perlRegex&&t.push("-E"),(e.caseInsensitive||MR(e))&&t.push("-i"),e.wholeWord&&t.push("-w"),e.invertMatch&&t.push("-v"),t.push("-I");let n=e.contextLines;n!==void 0&&n>0&&t.push("-C",String(n));let r=e.filesOnly?"files":e.countLinesPerFile||e.countMatchesPerFile?"count":"matches";r==="files"?t.push("-l"):r==="count"?t.push("-c"):t.push("-n");for(let o of e.include??[])t.push(`--include=${o}`);for(let o of e.exclude??[])t.push(`--exclude=${o}`);for(let o of e.excludeDir??[])t.push(`--exclude-dir=${o}`);return e.langType&&t.push(`--include=*.${e.langType}`),t.push("--",e.keywords??"",e.path),{args:t,outputMode:r}}function MR(e){return e.caseSensitive!==!0&&e.caseInsensitive!==!0&&(e.keywords??"")===(e.keywords??"").toLowerCase()}function NR(e,t,n,r){let o=[vR];n&&o.push(`Ripgrep unavailable: ${n}`),o.push(...e,...t);let i=[];return r.filesWithoutMatch&&i.push("filesWithoutMatch"),r.countMatchesPerFile&&i.push("countMatchesPerFile uses grep -c line counts"),r.hidden&&i.push("hidden"),r.noIgnore&&i.push("noIgnore"),r.multiline&&i.push("multiline"),r.multilineDotall&&i.push("multilineDotall"),(r.sort||r.sortReverse)&&i.push("sort"),i.length>0&&o.push(`grep fallback ignored/degraded options: ${i.join(", ")}.`),o}function HR(e,t){if(t==="files"){let i=Vl(e).map(s=>({path:s,matchCount:1,matches:[]}));return{files:i,matchCount:i.length}}if(t==="count"){let i=Vl(e).map(DR).filter(a=>a!==void 0),s=i.reduce((a,c)=>a+(c.matchCount??0),0);return{files:i,matchCount:s}}let n=new Map;for(let i of e.split(`
|
|
56
|
-
`)){if(!i.trim()||i==="--")continue;let s=GR(i);if(!s)continue;let a=n.get(s.path)??{path:s.path,matchCount:0,matches:[]},c=a.matches??=[];c.push({value:s.value,line:s.line,column:0}),a.matchCount=c.length,n.set(s.path,a)}let r=[...n.values()],o=r.reduce((i,s)=>i+(s.matchCount??0),0);return{files:r,matchCount:o}}function Vl(e){return[...new Set(e.trim().split(`
|
|
57
|
-
`).filter(Boolean))]}function DR(e){let t=Kl(e);if(!t)return;let n=Number.parseInt(t.numberText,10);if(!(!Number.isFinite(n)||n<=0))return{path:t.path,matchCount:n,matches:[]}}function GR(e){let t=Kl(e);if(!t)return;let n=Number.parseInt(t.numberText,10);if(Number.isFinite(n))return{path:t.path,line:n,value:t.rest}}function Kl(e){let t=e.indexOf(":");if(t===-1)return;let n=e.indexOf(":",t+1);if(n!==-1)return{path:e.slice(0,t),numberText:e.slice(t+1,n),rest:e.slice(n+1)}}import{readFile as $R,stat as Yl}from"node:fs/promises";var UR=["ts","tsx","js","jsx","mjs","cjs","py","go","rs","java","c","h","cpp","cc","cxx","hpp","hh","hxx","cs","sh","bash","zsh"],BR=["node_modules","dist",".git","build","coverage",".next","out","target"],zR=2e3,QR=1e6;function jR(e){if(!e)return;let n=e.replace(/\$+[A-Za-z0-9_]*/g," ").match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)??[],r;for(let o of n)(!r||o.length>r.length)&&(r=o);return r}async function VR(e,t){if((await Yl(e)).isFile())return[e];let o=(t.include?.length?t.include:void 0)??UR.map(a=>`*.${a}`),i=t.excludeDir?.length?t.excludeDir:BR;return z.queryFileSystem({path:e,recursive:!0,entryType:"f",names:o,excludeDir:i,limit:t.maxFiles??zR}).entries.map(a=>a.path)}async function Xl(e){let t=Ce(e,S.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath,r=e.pattern,o=e.rule,i=jR(r),s;try{s=await VR(n,e)}catch(h){return A(h,e,{toolName:S.LOCAL_RIPGREP})}let a=[],c=[],l=0,d=0,u=0,m;for(let h of s){if(m)break;let y;try{if((await Yl(h)).size>QR)continue;y=await $R(h,"utf8")}catch{continue}if(i&&!y.includes(i)){u++;continue}let b;try{b=z.structuralSearch(y,h,r,o)}catch(g){let C=g instanceof Error?g.message:String(g);if(C.includes("does not support"))continue;m=C;break}d++,b.length!==0&&(l+=b.length,a.push({path:h,matchCount:b.length,matches:b.map(g=>({line:g.startLine,value:g.text.split(`
|
|
58
|
-
`,1)[0],column:g.startCol}))}))}if(m)return A(new Error(`Invalid structural ${o?"rule":"pattern"}: ${m}`),e,{toolName:S.LOCAL_RIPGREP,customHints:[o?"Check the YAML rule shape. Relational sub-rules (inside/has) need `stopBy: end` to walk all ancestors/descendants, else they silently match nothing.":"Check the pattern syntax. Use $X for a single node, $$$ARGS for a list. The pattern must be a complete code fragment for the target language."]});i?u>0&&c.push(`Pre-filter on "${i}" skipped parsing ${u} file(s); parsed ${d}.`):c.push(`No literal anchor in the ${o?"rule":"pattern"} \u2014 parsed all ${d} candidate file(s) with no text pre-filter.`);let f=await Yt(a,e,"rg",c,{matchCount:l});if(l>0){let h=Array.isArray(f.hints)?[...f.hints]:[];return h.push("Structural matches return node ranges \u2014 pass matches[].line as the lspGetSemantics lineHint to navigate semantically."),{...f,hints:h}}return f}function WR(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Jl(e){let t=WR(e);if(t.mode==="structural")return await Xl(t);t.contextLines===void 0&&(t.contextLines=2);try{let n=await si("rg");return n.available?await jl(t):await Wl(t,n.error)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:B.OUTPUT_TOO_LARGE,hints:["Output exceeded 10MB - your pattern matched too broadly. Think about why results exploded:","Is the pattern too generic? Make it specific to target what you actually need","Searching everything? Add langType filters or path restrictions to focus scope","For node_modules: Target specific packages rather than searching the entire directory","Need file names only? FIND_FILES searches metadata without reading content","Strategy: Start with filesOnly=true to see what matched, then narrow before reading content"]}:A(n,t,{toolName:S.LOCAL_RIPGREP})}}async function Zl(e){let{queries:t}=e;return J(t||[],async n=>Le({toolName:S.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=gt.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return A(`Validation error: ${i}`,n)}return await Jl(r.data)}}),{toolName:S.LOCAL_RIPGREP,peerHints:!0},e)}import{ViewStructureQuerySchema as ql}from"@octocodeai/octocode-core/schemas";var eu={maxDepth:F(0,20).optional(),limit:F(1,1e4).optional(),page:q.default(1),itemsPerPage:F(1,50).optional()},KR=ae(ql,eu),_r=te(ql,eu),tu=X(KR,{maxQueries:5});var YR=new Set(["+","*","?"]),XR=1e3;function JR(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function nu(e,t){let n=e[t];return n===void 0?!1:YR.has(n)||n==="{"&&eb(e,t)}function ZR(e,t,n){let r=n.pop()??!1,o=nu(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?ru(e,t+1):t+1})}function qR(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:ru(e,t)})}function ai(e){if(e.length>XR)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=JR(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=ZR(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(nu(e,r)){let i=qR(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function eb(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 ru(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function M0(e,t){let n=ai(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}function tb(e){return e.startsWith(".")?e.slice(1):e}function ou(e,t){let n=e;if(t.pattern){let o=t.pattern;if(o.includes("*")||o.includes("?")||o.includes("[")){let s=o.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");s=s.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let a=`^${s}$`;if(!ai(a).safe)return n=n.filter(d=>(d.name.includes("/")?d.name.split("/").pop():d.name).includes(o)),n;let l=new RegExp(a,"i");n=n.filter(d=>{let u=d.name.includes("/")?d.name.split("/").pop():d.name;return l.test(u)})}catch{n=n.filter(a=>(a.name.includes("/")?a.name.split("/").pop():a.name).includes(o))}}else n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(o))}let r=t.extensions&&t.extensions.length>0?t.extensions.map(tb):[];return r.length>0&&(n=n.filter(o=>o.type==="directory"||o.extension&&r.includes(o.extension))),t.directoriesOnly&&(n=n.filter(o=>o.type==="directory")),t.filesOnly&&(n=n.filter(o=>o.type==="file")),n}function D0(e,t=0){let n=" ".repeat(t),r=e.type==="directory"?"[DIR] ":e.type==="symlink"?"[LINK]":"[FILE]",o=e.type==="directory"?`${e.name}/`:e.name,i=e.modified?` ${e.modified.split("T")[0]}`:"",s=e.permissions?` ${e.permissions}`:"";if(e.type==="file"&&e.size){let a=e.extension?` .${e.extension}`:"";return`${n}${r}${s} ${o} (${e.size})${i}${a}`}else return`${n}${r}${s}${i} ${o}`}function iu(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 su(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 ci(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+Rn(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Kt(r)})`}function li(e,t){let n=e.length,r=t.itemsPerPage||Me.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n);return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:i<o}}}function ui(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function di(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}async function au(e){try{let t=Ce(e,S.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return nb(e,t.sanitizedPath,n)}catch(t){let n=Fe.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode,hints:oe(S.LOCAL_VIEW_STRUCTURE,"error")}}}function nb(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=ob(e),s=r&&e.limit&&!rb(e,i)?e.limit*2:1e4,a;try{a=z.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,entryType:ib(e),limit:s})}catch(O){return cb(O,e,t)}let c=a.entries.map(O=>sb(O,n,e.details??!1)),l=ou(c,e),d=e.sortBy??"name";l=l.sort((O,$)=>{let M=0;switch(d){case"size":{let N=O.sizeBytes??(O.size?Rn(O.size):0),se=$.sizeBytes??($.size?Rn($.size):0);M=N-se;break}case"time":n&&O.modified&&$.modified?M=O.modified.localeCompare($.modified):M=O.name.localeCompare($.name);break;case"extension":M=(O.extension||"").localeCompare($.extension||"");break;default:M=O.name.localeCompare($.name);break}return e.reverse?-M:M}),e.limit&&(l=l.slice(0,e.limit));let u=l.length,{paginatedEntries:m,endIdx:p,pagination:f}=li(l,e),y=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(O=>({...su(O),path:O.path??`${t.replace(/\/$/,"")}/${O.name}`}))}:{path:t,...iu(m)},b=[...a.warnings,...di({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],g=u===0,C=typeof e.pattern=="string"?e.pattern:void 0,T=(e.extensions?.length??0)>0||!!C,P=l.filter(O=>O.type==="file").length,x=T&&P===0&&!g,I={entryCount:u,path:e.path,extensions:e.extensions,pattern:C},Q=g||x?oe(S.LOCAL_VIEW_STRUCTURE,"empty",I):["Use localSearchCode to search or localGetFileContent to read discovered files."],E=ui(l,m.length,f,p),w=ci(l);return U(cu({...g?{status:"empty"}:{},...y,summary:w,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b},hints:[...Q,...E]},e),a.entries.reduce((O,$)=>O+$.path.length,0))}function rb(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t||(e.extensions?.length??0)>0)}function ob(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function ib(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function sb(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:Kt(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=ab(e.permissions)),o}function ab(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 cb(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=Fe.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return A(a,t,{toolName:S.LOCAL_VIEW_STRUCTURE,customHints:o?[`Path not found: ${n}`]:i?[`Permission denied: ${n}`]:[`Cannot access path: ${n}`]})}function cu(e,t){return e}async function lu(e){let{queries:t}=e;return J(t||[],async n=>Le({toolName:S.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=_r.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return A(`Validation error: ${i}`,n)}return await au(r.data)}}),{toolName:S.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"],peerHints:!0},e)}import{acquirePooledClient as yu,isLanguageServerAvailable as Ru}from"octocode-lsp/manager";import{resolveWorkspaceRootForFile as bu}from"octocode-lsp/workspaceRoot";import{safeReadFile as lb}from"octocode-lsp/validation";var uu={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0};function Sn(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function du(e,t,n){if(t<=0)return e;let r=await lb(e.uri);if(!r)return e;let o=r.split(/\r?\n/),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,d)=>{let u=s+d+1;return`${u===i+1?">":" "}${String(u).padStart(4," ")}| ${l}`}).join(`
|
|
59
|
-
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function ub(e,t){return Promise.all(e.map(async n=>({...n,from:await du(n.from,t,n.fromRanges)})))}async function db(e,t){return Promise.all(e.map(async n=>({...n,to:await du(n.to,t)})))}async function pi(e,t,n,r,o){if(n<=0||!e)return{calls:[],...uu};try{let i=await e.getIncomingCalls(t),s=o>0?await ub(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Sn(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),pi(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function mi(e,t,n,r,o){if(n<=0||!e)return{calls:[],...uu};try{let i=await e.getOutgoingCalls(t),s=o>0?await db(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Sn(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),mi(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}import{readFile as pb}from"node:fs/promises";import{SymbolResolver as mb,SymbolResolutionError as fb}from"octocode-lsp/resolver";import{LSP_ERROR_CODES as pu}from"octocode-lsp/lspErrorCodes";async function fi(e,t){let n=e.uri,r=Ce({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{return{ok:!0,value:{uri:o,absolutePath:o,content:await pb(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:pu.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function mu(e,t){let n=await fi(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 mb({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:hb(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof fb)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:pu.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function hb(e){return{start:e,end:{line:e.line,character:e.character}}}var gb=40,Su=40,yb=10,Rb=8;async function yi(e){return J(e.queries||[],async t=>Le({toolName:Re,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await Ab(t);return bb(Sb(t,n))}}),{toolName:Re,peerHints:!0,minQueryTimeoutMs:3e4},e)}function bb(e){return U(e,G(e))}function Sb(e,t){return e.format!=="compact"||!Cb(t)?t:Pb(t)}function Cb(e){return Lt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Lt(e.payload)}function Pb(e){return{...e,format:"compact",payload:Eb(e.payload)}}function Eb(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(fu)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(wb)}:{locations:(e.locations??[]).map(fu)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Cu(e.root)}:{},direction:e.direction,calls:e.calls.map(xb),...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(Tb)};case"hover":case"empty":return e}}function Tb(e){if(!Lt(e))return String(e);let t=Ie(e,"line"),n=Ie(e,"character"),r=Ie(e,"endLine"),o=it(e,"kind"),i=it(e,"name"),s=Ie(e,"childCount"),a=it(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function fu(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Eu(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function wb(e){if(!Lt(e))return String(e);let t=it(e,"uri"),n=Ie(e,"firstLine"),r=Ie(e,"firstCharacter"),o=Ie(e,"count"),i=Pu(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 xb(e){if(!Lt(e))return String(e);let t=it(e,"direction"),n=Cu(e.item),r=Pu(e,"ranges").map(_b).join(","),o=Ie(e,"rangeCount"),i=Ie(e,"rangeSampleCount"),s=it(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Eu(s,180)}`:""].filter(Boolean).join(" ")}function Cu(e){if(!Lt(e))return String(e);let t=it(e,"name"),n=it(e,"kind"),r=it(e,"uri"),o=Ie(e,"line"),i=Ie(e,"endLine"),s=Ie(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function _b(e){return Lt(e)?`${Ie(e,"line")}:${Ie(e,"character")}`:String(e)}function Lt(e){return typeof e=="object"&&e!==null}function it(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ie(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Pu(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Eu(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function Ab(e){if(e.type==="documentSymbols")return Lb(e);let t=await mu(e,Re);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed",s=Array.isArray(t.error.hints)?t.error.hints:void 0;return $b(e,i,s)}let n=e.workspaceRoot??await bu(t.value.uri);if(!await Ru(t.value.uri,n))return ot(e.type,t.value,"Language server unavailable");let o=await yu(n,t.value.uri);if(!o)return ot(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?hi(e,t.value,"definition","definitionProvider",await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ot(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?hi(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ot(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?hi(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ot(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?Ob(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):ot(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?Ib(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ot(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?kb(e,t.value,o):ot(e.type,t.value,"callHierarchyProvider unsupported",!0)}}async function Lb(e){let t=await fi(e,Re);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await bu(t.value.uri),r=await Ru(t.value.uri,n),o=r?await yu(n,t.value.uri):null,i=o?o.hasCapability("documentSymbolProvider")?await o.documentSymbols(t.value.uri,t.value.content):[]:[],s=!!o?.hasCapability("documentSymbolProvider"),a=vb(Array.isArray(i)?i:[]),c=Nb(Array.isArray(i)?i:[]),{pageItems:l,pagination:d}=Lr(a,e.page??1,e.itemsPerPage??gb),u=Hb(a,f=>f.kind),p=s?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(s?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...s?{provider:"documentSymbolProvider"}:{}},summary:{totalSymbols:a.length,returnedSymbols:l.length,topLevelSymbols:c,kinds:u},payload:{kind:"documentSymbols",symbols:l,...p?{empty:p}:{}},pagination:d,hints:[...d.hasMore?[Ar(d,"symbols")]:[],...mt("documentSymbols",s)]}}function hi(e,t,n,r,o){let i=o.length>0,s=o.map(Yr),{pageItems:a,pagination:c}=Lr(s,e.page??1,e.itemsPerPage??Su);return{type:e.type,uri:t.uri,resolvedSymbol:Mt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{},hints:[...i&&c.hasMore?[Ar(c,"locations")]:[],...mt(e.type,i)]}}function Ob(e,t,n){let r=n.map(l=>{let d=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...d?{isDefinition:!0}:{}}}),o=e.groupByFile?Ub(r):void 0,i=o??r.map(Yr),{pageItems:s,pagination:a}=Lr(i,e.page??1,e.itemsPerPage??Su),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:Mt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a,hints:[...a.hasMore?[Ar(a,o?"reference files":"references")]:[],...mt("references",!0)]}}async function Ib(e,t,n){let r=Bb(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Mt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"},hints:mt(e.type,o)}}async function kb(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return ot(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await pi(n,o,i,new Set([Sn(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await mi(n,o,i,new Set([Sn(o)]),e.contextLines??0):s,l=g=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(g.to.uri),d=c.calls.filter(l).length,u=c.calls.filter(g=>!l(g)),m=[...a.calls.map(g=>({direction:"incoming",...g})),...u.map(g=>({direction:"outgoing",...g}))],p=m.map(g=>g.direction==="incoming"?Db(g,e.contextLines??0):Gb(g,e.contextLines??0)),{pageItems:f,pagination:h}=Lr(p,e.page??1,e.itemsPerPage??yb),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Mt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Ri(o),direction:y,calls:f,incomingCalls:a.calls.length,outgoingCalls:u.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...d>0&&{stdlibCallsExcluded:d}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:h,hints:[...h.hasMore?[Ar(h,"calls")]:[],...mt(e.type,!0),...a.truncatedByDepth||c.truncatedByDepth?["Calls exist beyond the traversal depth \u2014 increase depth to follow the chain further."]:[]]}}function Ar(e,t){let n=Math.min(e.currentPage*e.itemsPerPage,e.totalResults)-(e.currentPage-1)*e.itemsPerPage,r=e.nextPage??e.currentPage+1;return`Page ${e.currentPage}/${e.totalPages} (${n} of ${e.totalResults} ${t}). Next: page=${r}`}function Lr(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function vb(e){let t=[];for(let n of e)Tu(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Tu(e,t,n){if(!e||typeof e!="object")return;let r=e,o=Mb(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:gi(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)&&Fb.has(gi(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Tu(s,t,i)}}var Fb=new Set(["file","module","namespace","package","class","enum","interface","struct"]);function Mb(e){if(hu(e.range))return e.range;let t=e.location;return t&&hu(t.range)?t.range:void 0}function hu(e){if(!e||typeof e!="object")return!1;let t=e;return gu(t.start)&&gu(t.end)}function gu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function Nb(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Hb(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function Db(e,t){let n=wu(e.fromRanges);return{direction:"incoming",item:Ri(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...xu(e.from,t)}}function Gb(e,t){let n=wu(e.fromRanges);return{direction:"outgoing",item:Ri(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...xu(e.to,t)}}function Ri(e){return{name:e.name,kind:gi(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 wu(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>=Rb))break}return n}function xu(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function gi(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function _u(e,t){return/unavailable/i.test(t)?"serverUnavailable":/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function $b(e,t,n){let r=e.uri??"";return{type:e.type,uri:r,lsp:{},payload:{kind:"empty",category:_u(e.type,t),reason:t},hints:n?.length?n:mt(e.type,!1)}}function ot(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Mt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:_u(e,n),reason:n},hints:mt(e,!1)}}function Ub(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 Bb(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=>zb(r)).join(`
|
|
60
|
-
`).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 zb(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{z as R}from"zod";import{LspGetSemanticsQuerySchema as Ou}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as Qb}from"@octocodeai/octocode-core/schemas/outputs";var jb=F(1,1e9),Vb=F(0,1e5).optional(),Wb=["structured","compact"],Iu={type:R.enum(is).default("definition"),symbolName:R.string().min(1).optional(),lineHint:jb.optional(),orderHint:Vb,depth:F(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:q,itemsPerPage:F(1,100).optional(),contextLines:F(0,100).optional(),format:R.enum(Wb).optional().default("structured")},Kb=ae(Ou,Iu),Si=te(Ou,Iu),Yb=Si,Ci=X(Kb,{maxQueries:5}),Au=R.object({line:R.number(),character:R.number()}),Xb=R.object({start:Au,end:Au}),Jb=R.object({startLine:R.number(),endLine:R.number()}),Or=R.object({uri:R.string(),content:R.string().optional(),displayRange:Jb.optional(),isDefinition:R.boolean().optional()}),Ir=R.string(),Zb=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),qb=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),ku=R.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls"]),bi=R.object({category:ku,reason:R.string()}),eS=R.object({currentPage:R.number(),totalPages:R.number(),totalResults:R.number(),hasMore:R.boolean(),itemsPerPage:R.number(),nextPage:R.number().optional()}),tS=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),nS=R.string(),vu=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),rS=R.string(),oS=R.object({direction:R.enum(["incoming","outgoing"]),item:vu,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),iS=R.string(),sS=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),aS=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),cS=R.string(),lS=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Or,Ir]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Or,Ir]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Or,Ir]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Or,Ir])).optional(),byFile:R.array(R.union([aS,cS])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:bi.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([vu,rS]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([oS,iS])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:sS,empty:bi.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:Xb.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([tS,nS])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:bi.optional()}),R.object({kind:R.literal("empty"),category:ku,reason:R.string()})]),Lu=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:Zb.optional(),lsp:qb,payload:lS,pagination:eS.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional(),hints:R.array(R.string()).optional()}),uS=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),hints:R.array(R.string()).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:Lu}),R.object({id:R.string().min(1),status:R.literal("error"),data:Qb}),R.object({id:R.string().min(1),data:Lu})]))});import{existsSync as Fu}from"fs";import{delimiter as dS,dirname as pS,join as Mu}from"path";function Nu(){return process.platform==="win32"?"npm.cmd":"npm"}function mS(){let e=pS(process.execPath);return Mu(e,Nu())}function fS(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function hS(){let e=(process.env.PATH??"").split(dS).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...fS()])]}function Hu(){let e=mS();if(Fu(e))return{command:process.execPath,argsPrefix:[e]};let t=Nu();for(let n of hS()){let r=Mu(n,t);if(Fu(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var gS=["view","search","ping","config","whoami"],yS=[...yn,...Ba];async function Dv(e=1e4){let t=Hu();return dr(t.command,[...t.argsPrefix,"--version"],e)}async function Cn(e,t,n={}){if(!gS.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=pr(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=Hu(),c=await wt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:yS});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var $v=5;var Xt=new Map,Ei=5,Pn=3e4;function En(e){try{return new URL(e).host||e}catch{return e}}var Pi=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 Du(e,t=Date.now()){let n=Xt.get(En(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Pn)throw new Pi(En(e),Pn-r);n.state="half-open"}}function Ti(e){let t=Xt.get(En(e));t&&(t.failures=0,t.state="closed")}function Gu(e,t=Date.now()){let n=En(e),r=Xt.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=Ei&&(r.state="open",r.openedAt=t)),Xt.set(n,r)}function Uv(){Xt.clear(),Ei=5,Pn=3e4}function Bv(e){typeof e.failureThreshold=="number"&&(Ei=e.failureThreshold),typeof e.cooldownMs=="number"&&(Pn=e.cooldownMs)}function $u(e,t=Date.now()){let n=Xt.get(En(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Pn:!1}var RS=6e4;function Uu(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function bS(e,t,n,r){e&&ut({limit_type:"primary",retry_after_seconds:Uu(r),api_method:t,api_url:n,provider:e}).catch(je("fetch rate-limit session logging"))}function SS(e,t,n,r,o){e.body?.cancel?.().catch(je("response body cancellation")),D("fetchWithRetries",ct.FETCH_HTTP_ERROR.code).catch(je("fetch retry session logging"));let i=new Error(ct.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&as(r),e.status===429&&bS(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function CS(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=Uu(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function yt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=RS,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:d}=t,u=e;if(a){let y=e.includes("?")?"&":"?";u=`${e}${y}version=${encodeURIComponent(qe)}`}let m={"User-Agent":`Octocode-MCP/${qe}`,...i},p=globalThis.fetch;if(!p)throw D("fetchWithRetries",ct.FETCH_NOT_AVAILABLE.code).catch(je("fetch retry session logging")),new Error(ct.FETCH_NOT_AVAILABLE.message);Du(u);let f,h=n+1;for(let y=1;y<=h;y++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(u,{method:s,headers:m,signal:c});if(!b.ok)throw SS(b,s,u,d,l);if(b.status===204)return Ti(u),null;let g=await b.json();return Ti(u),g}catch(b){let g=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(g&&g.retryable===!1)throw b;if(f=b instanceof Error?b:new Error(String(b)),y===h)break;let C=CS(y,r,o,g);await new Promise(T=>setTimeout(T,C))}}throw Gu(u),await D("fetchWithRetries",ct.FETCH_FAILED_AFTER_RETRIES.code),new Error(ct.FETCH_FAILED_AFTER_RETRIES.message(h,f?.message||""))}import{z as _}from"zod";var kr=_.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()}),PS=_.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()}),Bu=_.looseObject({objects:_.array(PS),total:_.union([_.number(),_.string()]).optional()}),zu=_.union([_.string(),_.boolean(),_.number(),_.null(),_.record(_.string(),_.unknown())]);var vr="https://registry.npmjs.org",ES=3e3,Tn=null;async function wi(){if(Tn)return Tn;try{let e=await Cn("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 Tn=t,t}}catch{}return Tn=vr,vr}function oF(){Tn=null}async function iF(){try{let e=await wi(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}function Ot(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var TS="https://api.npmjs.org/downloads/point/last-week";function Ne(e){return e===void 0?0:G(e)}async function Yu(e){try{let t=`${TS}/${encodeURIComponent(e)}`,n=await yt(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:Ne(n)}}catch{return{rawResponseChars:0}}}function Fr(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Xu(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function wS(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function xS(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function Qu(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function ju(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function _S(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function xi(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Ot(e.repository):(e.repository.url&&(r=Ot(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:_S(e),...o?{repositoryDirectory:o}:{},...Qu(e.exports)?{exports:Qu(e.exports)}:{},...ju(e.bin,e.name)?{bin:ju(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function AS(e){return typeof e.links?.repository=="string"?Ot(e.links.repository):typeof e.repository=="string"?Ot(e.repository):typeof e.repository?.url=="string"?Ot(e.repository.url):null}function LS(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:AS(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 Ju(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function Zu(e){try{let t=await wi(),n=Ju(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await yt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ne(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await yt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ne(i)}}catch{return{rawResponseChars:0}}}async function _i(e,t,n){let[r,o]=await Promise.all([Yu(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Zu(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 Mr(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function OS(e,t){try{let n=await Cn("view",[e,"--json"],{timeout:ES});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,...Mr(c)?{}:{errorDetail:c},rawResponseChars:Ne(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=Ne(o),s=kr.safeParse(o);return s.success?{pkg:xi(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,...Mr(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function IS(e,t){try{let n=await wi(),r=Ju(e),o=`${n}/${r}/latest`,i;try{i=await yt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let d=l instanceof Error?l.message:String(l);return d.includes("404")||d.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:d,rawResponseChars:0}}let s=Ne(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=kr.safeParse(i);return a.success?{pkg:xi(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,...Mr(r)?{}:{errorDetail:r},rawResponseChars:0}}}function kS(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function qu(e,t){let n=0,r;for(let o of kS(e)){let i;try{i=await yt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);Mr(l)||(r=l);continue}if(n+=Ne(i),!i||typeof i!="object")continue;let s=kr.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:xi(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Ai(e,t=!1){let[n,r]=await Promise.allSettled([OS(e,t),IS(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?_i(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function vS(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Ai(e,t);if(!r){if(o){let s=Xu(o);if(s&&n){let a=await qu(e,t);if(a.pkg){let c=await _i(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function FS(e,t,n,r=0){let o=Math.max(t+r,t),i=await Cn("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:Ne(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=Ne(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let d=[...a].sort((f,h)=>{let y=f?.score?.final??0;return(h?.score?.final??0)-y}).slice(r,r+t),u=await Promise.all(d.map(async f=>{if(!f||typeof f!="object")return null;let h=f;if(!h.name)return null;if(n){let y=await Ai(h.name,!0);if(y.pkg)return y}return{pkg:LS(h),rawResponseChars:0}})),m=u.map(f=>f?.pkg).filter(f=>!!f),p=u.reduce((f,h)=>f+(h?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function MS(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${vr}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await yt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`NPM registry search failed: ${f instanceof Error?f.message:String(f)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ne(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Bu.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(h=>h.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let d=[...c.data.objects].sort((f,h)=>{let 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),u=await Promise.all(d.map(async f=>{if(n){let h=await Ai(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"?Ot(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=u.map(f=>f.pkg).filter(f=>!!f),p=u.reduce((f,h)=>f+h.rawResponseChars,0);return{packages:m,totalFound:xS(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Vu(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 yt(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:Ne(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ne(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"?Ot(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:Ne(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Wu(e,t,n,r=0){try{let o=await FS(e,t,n,r);if(!("error"in o))return o}catch{}return MS(e,t,n,r)}async function Ku(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}):Yu(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Zu(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function ed(e,t,n,r=0){let o=Ee("npm-search",{name:e,limit:t,metadata:n,from:r});return Te(o,async()=>{if($u(vr)){if(r===0&&t===1&&Fr(e)){let d=await qu(e,n);if(d.pkg){let u=await _i(e,d.pkg,d.rawResponseChars);return{packages:u.pkg?[u.pkg]:[],totalFound:u.pkg?1:0,rawResponseChars:u.rawResponseChars}}}let l=await Vu(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Fr(e)){let l=await vS(e,n,t===1);if("error"in l){if(!Xu(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Wu(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Ku(s);let a=wS(e);if(a!==e){let l=await Wu(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return Ku(l)}let c=await Vu(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function Li(e){try{let t=await Cn("view",[e,"deprecated","--json"]);if(t.error||t.exitCode!==0)return null;let n=t.stdout.trim();if(!n||n==="undefined"||n==="")return{deprecated:!1};try{let r=JSON.parse(n),o=zu.safeParse(r),i=o.success?o.data:n;return{deprecated:!0,message:typeof i=="string"?i:"This package is deprecated"}}catch{return{deprecated:!0,message:n}}}catch{return null}}async function td(e){let t=Fr(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return ed(e.name,n,!0,r)}function NS(e){return"error"in e}function Jt(e){return"npmUrl"in e}function Oi(e){return Jt(e)&&e.path?e.path:e.name}function nd(e){return Jt(e)?e.repoUrl:e.repository}function HS(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function DS(e){if(!e)return{};let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);return t?.[1]&&t[2]?{owner:t[1],repo:t[2].replace(/\.git$/,"").replace(/\/$/,"")}:{}}function GS(e){let t=Oi(e),n=nd(e),r={name:t};Jt(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.weeklyDownloads=e.weeklyDownloads)),n&&(r.repository=n);let o=HS(Jt(e)?e.repositoryDirectory:void 0);return o&&(r.repositoryDirectory=o),r}function $S(e,t){let n=[],r=Oi(e);t?.deprecated&&n.push(`DEPRECATED: ${r} \u2014 ${t.message??"use an alternative"}`);let o=Jt(e)?e.source:void 0;o==="cdn"?n.push("Metadata from npm CDN cache \u2014 verify version when registry access is restored."):o==="web"&&n.push("Metadata from npms.io fallback \u2014 verify version when registry access is restored."),n.push(`Install: npm install ${r}`);let i=nd(e),{owner:s,repo:a}=DS(i);return s&&a?n.push(`Browse source: use ghViewRepoStructure owner=${s} repo=${a}`):i?n.push(`Repository: ${i} \u2014 use ghSearchRepos to find on GitHub.`):n.push(`No repository URL for "${r}" \u2014 use ghSearchRepos to find the source repo.`),n}function US(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=Math.max(1,Math.ceil(t/i));return{currentPage:o,totalPages:s,perPage:i,totalFound:t,returned:n,hasMore:o<s}}function BS(e){if(e.totalFound===0||e.totalPages<=1)return[];if(e.currentPage>e.totalPages)return[`Requested page ${e.currentPage}/${e.totalPages} is past the end. Retry page=${e.totalPages}.`];let t=(e.currentPage-1)*e.perPage+1,n=Math.min(t+e.returned-1,e.totalFound);return e.hasMore?[`Page ${e.currentPage}/${e.totalPages} (showing ${t}-${n} of ${e.totalFound} packages). Next: page=${e.currentPage+1}`]:[]}function zS(e,t){return[`Found ${e}${t>e?` of ${t}`:""} packages. Re-run with an exact name for source details, install command, and repo navigation.`]}async function rd(e){return J(e.queries,async t=>{try{if(!t.packageName)return A("Package name is required for package search",t);let n=await td({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(NS(n))return A(n.error,t,{rawResponse:n,customHints:[...n.hints??[],...oe(S.PACKAGE_SEARCH,"error",{originalError:n.error})]});let r=n.packages,o=r.map(GS),i=o.length>0,s=r.length>1||n.totalFound>1,a=US(t,n.totalFound,o.length,s),c=null;if(!s&&i&&r[0]){let u=Jt(r[0])?r[0].source:void 0;u!=="cdn"&&u!=="web"&&(c=await Li(Oi(r[0])))}let l=[...BS(a),...i?s?zS(o.length,n.totalFound):$S(r[0],c):oe(S.PACKAGE_SEARCH,"empty",{name:t.packageName})];return Se(t,{packages:o,pagination:a},i,S.PACKAGE_SEARCH,{extraHints:l,rawResponse:n.rawResponseChars??n})}catch(n){return A(n,t,{customHints:oe(S.PACKAGE_SEARCH,"error",{originalError:n instanceof Error?n.message:String(n)})})}},{toolName:S.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"],peerHints:!0},e)}import{z as ie}from"zod";import{NpmPackageQuerySchema as od}from"@octocodeai/octocode-core/schemas";var id={page:q,mode:ie.enum(["lean","full"]).optional()},sd=te(od,id),ad=X(ae(od,id,{strict:!0}),{maxQueries:5}),SF=ie.object({results:ie.array(ie.looseObject({id:ie.string(),data:ie.looseObject({packages:ie.array(ie.object({name:ie.string(),version:ie.string().optional(),description:ie.string().optional(),license:ie.string().optional(),weeklyDownloads:ie.number().optional(),repository:ie.string().optional(),repositoryDirectory:ie.string().optional()}).passthrough()).optional(),pagination:ie.object({currentPage:ie.number(),totalPages:ie.number(),perPage:ie.number(),totalFound:ie.number(),returned:ie.number(),hasMore:ie.boolean()}).optional()}).optional(),status:ie.string().optional()})).optional()}).extend(xe);var Ii={hasTool(e){return uo(e)},getDescription(e){return lo[e]??""},getToolName(e){return S[e]??String(e)}};var cd=(e,t=Ii)=>t.getDescription(e);function QS(e,t){return t.getToolName(e)}function ze(e,t,n){let r=QS(t,e);return{...n,name:r,description:cd(r,e)}}function jS(e=Ii){let t=ze(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:vc,inputSchema:Fc,executionFn:Oc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=ze(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:hr,inputSchema:pc,executionFn:Ac,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=ze(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:ol,inputSchema:il,executionFn:tl,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=ze(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:qc,inputSchema:el,executionFn:Xc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=ze(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Pr,inputSchema:Qc,executionFn:jc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=ze(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:sd,inputSchema:ad,executionFn:rd,security:"remote",requiresServerRuntime:!0}}),a=ze(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Xo,inputSchema:lc,executionFn:ac,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=ze(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:gt,inputSchema:Gl,executionFn:Zl,security:"basic"}}),l=ze(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:_r,inputSchema:tu,executionFn:lu,security:"basic"}}),d=ze(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:wr,inputSchema:kl,executionFn:Nl,security:"basic"}}),u=ze(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Tr,inputSchema:Al,executionFn:Ll,security:"basic"}}),m={name:Re,description:cd(Re,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Si,inputSchema:Ci,executionFn:yi,security:"basic",requiresServerRuntime:!0}},p=ze(e,"LOCAL_BINARY_INSPECT",{isDefault:!1,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Er,inputSchema:al,executionFn:Pl,security:"basic"}});return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:d,LOCAL_FETCH_CONTENT:u,LSP_GET_SEMANTIC_CONTENT:m,LOCAL_BINARY_INSPECT:p,ALL_TOOLS:[t,n,r,o,i,s,a,c,l,d,u,m,p]}}var ke=jS(),ZF=ke.GITHUB_SEARCH_CODE,qF=ke.GITHUB_FETCH_CONTENT,eM=ke.GITHUB_VIEW_REPO_STRUCTURE,tM=ke.GITHUB_SEARCH_REPOSITORIES,nM=ke.GITHUB_SEARCH_PULL_REQUESTS,rM=ke.PACKAGE_SEARCH,oM=ke.GITHUB_CLONE_REPO,iM=ke.LOCAL_RIPGREP,sM=ke.LOCAL_VIEW_STRUCTURE,aM=ke.LOCAL_FIND_FILES,cM=ke.LOCAL_FETCH_CONTENT,lM=ke.LSP_GET_SEMANTIC_CONTENT,uM=ke.LOCAL_BINARY_INSPECT,ld=ke.ALL_TOOLS;import{completeMetadata as VS}from"@octocodeai/octocode-core";var wn=null;function ud(){return wn||(wn=VS),wn}async function mM(){return ud()}async function fM(){ud()}function hM(){return wn}function gM(){wn=null}import{z as Fi}from"zod";import{ContentSanitizer as WS}from"octocode-security";import{maskSensitiveData as dd}from"octocode-security/mask";function Nr(e){let t=e;if(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let r=WS.sanitizeContent(n.text),o=r.hasSecrets?dd(r.content):dd(n.text);return{...n,text:o}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:Ye(t.structuredContent)}}catch{}return t}var KS="TOOL_CALLBACK_EXCEPTION";function pd(e,t){let n=YS(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
61
|
-
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:KS,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Nr(r)}catch{return r}}function YS(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:XS(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 XS(e){try{return JSON.stringify(e)}catch{return}}import{releaseAllPooledClients as JS}from"octocode-lsp/manager";var md=["GitHub","Local","LSP","Package","Other"],fd=new Map([K.GITHUB_SEARCH_CODE,K.GITHUB_SEARCH_REPOSITORIES,K.GITHUB_SEARCH_PULL_REQUESTS,K.GITHUB_FETCH_CONTENT,K.GITHUB_VIEW_REPO_STRUCTURE,K.GITHUB_CLONE_REPO,K.LOCAL_RIPGREP,K.LOCAL_FIND_FILES,K.LOCAL_FETCH_CONTENT,K.LOCAL_VIEW_STRUCTURE,Re,K.PACKAGE_SEARCH].map((e,t)=>[e,t])),st=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},ki=null,vi=null,ZS=["id","mainResearchGoal","researchGoal","reasoning"],Hi=new Set([...ZS]),qS=["id","researchGoal","reasoning"],hd=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function eC(e){return async t=>e(t)}function tC(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:eC(t.executionFn),security:t.security,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var gd=ld.map(tC),IM=gd.map(Sd);function yd(e){let t=Di(e);return t?Sd(t):void 0}function Hr(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")?"Local":e.startsWith("lsp")?"LSP":e===K.PACKAGE_SEARCH?"Package":"Other"}function kM(e){return[...e].sort((t,n)=>{let r=md.indexOf(Hr(t)),o=md.indexOf(Hr(n));if(r!==o)return r-o;let i=fd.get(t)??Number.MAX_SAFE_INTEGER,s=fd.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function vM(e){let t=yd(e);if(!t)return"{}";try{return JSON.stringify(Fi.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(Fi.toJSONSchema(t.schema),null,2)}}function FM(e){return JSON.stringify(e??{},null,2)}function MM(e){let t=Hr(e),n=[...qS];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function NM(){return hd.map(e=>({...e}))}function HM(){return JSON.stringify(Object.fromEntries(hd.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function DM(e,t){return t?.tools?.[e]?.description??e}function Rd(e){let t=yd(e);if(!t)return[];let n=Fi.toJSONSchema(t.schema);if(!xn(n))return[];let r=Rt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Hi.has(i)&&!Ni(r[i])):[]);return Mi(r,o)}function GM(e){let t=Rd(e),n=t.filter(i=>i.required),r=n.length>0?n:t.slice(0,4),o={};for(let i of r)o[i.name]=lC(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Re&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function $M(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new st("Tool input must be valid JSON.")}return nC(e,r,n)}function nC(e,t,n={}){let r=oC(e,t,n),o=Di(e);if(!o)throw new st(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new st("Tool input does not match the expected schema.",rC(i.error));return i.data}function rC(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function oC(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(Rt(t)&&Array.isArray(t.queries))r=t.queries;else if(Rt(t))r=[t];else throw new st('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new st("At least one query is required.");let o=Rt(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,l)=>{i=!0,n.onUnknownFields?.(c,l)}},a=r.map((c,l)=>iC(e,l,aC(e,c,l,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new st("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function iC(e,t,n,r){let o={...n},i=Hr(e),s=r.sourceLabel??"direct tool execution",a=sC(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function sC(e,t){return`Execute ${e} via ${t}`}function aC(e,t,n,r={}){if(!Rt(t))throw new st("Tool input must be a JSON object or an array of objects.");let o=new Set([...Rd(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Hi]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function cC(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 bd(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let t=xn(e.items)?e.items:void 0;return`array<${t?bd(t):"value"}>`}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Mi(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Hi.has(o))continue;let s=xn(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:bd(s),constraints:cC(s),description:typeof s.description=="string"?s.description:void 0}),Rt(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(d=>typeof d=="string"?!Ni(s.properties?.[d]):!1):[]);r.push(...Mi(s.properties,l,a))}let c=s.type==="array"&&xn(s.items)?s.items:void 0;if(c&&Rt(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(d=>typeof d=="string"?!Ni(c.properties?.[d]):!1):[]);r.push(...Mi(c.properties,l,a))}}return r}function lC(e,t){if(t.startsWith("array<"))return[e];if(t==="integer"||t==="number")return 1;if(t==="boolean")return!0;if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;switch(e){case"path":return".";case"owner":return"bgauryy";case"repo":return"octocode";case"name":case"packageName":return"react";default:return e}}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e){return Rt(e)}function Ni(e){return xn(e)&&"default"in e}async function UM(e,t){let n=Di(e);if(!n)throw new Error(`Unknown tool: ${e}`);let r=uC(n,t);try{return await dC(n),e===K.GITHUB_CLONE_REPO&&!Hn()?Nr({content:[{type:"text",text:`error: ghCloneRepo is disabled
|
|
62
|
-
message: Set ENABLE_CLONE=true (and ENABLE_LOCAL=true) to enable repository cloning.
|
|
63
|
-
hints:
|
|
64
|
-
- To browse without cloning, use ghViewRepoStructure to list files or ghGetFileContent to read specific files.`}],structuredContent:{status:"error",tool:e,code:"TOOL_DISABLED",error:{message:"ghCloneRepo is disabled \u2014 set ENABLE_CLONE=true (and ENABLE_LOCAL=true) to enable repository cloning."},hints:["To browse without cloning, use ghViewRepoStructure to list files or ghGetFileContent to read specific files."]},isError:!0}):await pC(n,r)}finally{e===Re&&await JS()}}function Sd(e){return{name:e.name,schema:e.schema,inputSchema:e.inputSchema}}function Di(e){return gd.find(t=>t.name===e)}function uC(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function dC(e){e.requiresServerRuntime&&(ki||(ki=ns()),await ki),e.requiresProviders&&(vi||(vi=Ga().then(()=>{})),await vi)}async function pC(e,t){try{let n=e.security==="remote"?await mC(e,t):await fC(e,t);return Nr(n)}catch(n){return pd(e.name,n)}}async function mC(e,t){return Qi(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function fC(e,t){return ji(e.execute,e.name)(t)}import{getConfigSync as Cd}from"octocode-shared";function QM(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function jM(){try{return Cd().local.enabled}catch{return!1}}function VM(){try{if(!Cd().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}function XM(e,t){let n=we(),r=t.maxOutputChars??n,o=t.recommendedCharLength??n,i=[];if(t.charLength!==void 0||t.charOffset!==void 0){let s=t.charLength??o,a=t.charOffset??0,c=tt(e,a,s),l=dn(c);return{content:c.paginatedContent,wasLimited:!0,pagination:l,warnings:i,paginationHints:Pd(l)}}if(e.length>r){i.push(`Auto-paginated: Output (${e.length} chars) exceeds ${r} char limit. Use charOffset/charLength to navigate.`);let s=tt(e,0,o),a=dn(s);return{content:s.paginatedContent,wasLimited:!0,pagination:a,warnings:i,paginationHints:Pd(a)}}return{content:e,wasLimited:!1,warnings:i,paginationHints:[]}}function Pd(e){let t=[];if(e.hasMore){let n=(e.charOffset??0)+(e.charLength??0),r=(e.charOffset??0)+1,o=n;t.push(`Page ${e.currentPage}/${e.totalPages} (chars ${r}-${o} of ${e.totalChars}). Next: charOffset=${n}`)}return t}import{z as H}from"zod";var Dr=H.object({text:H.string()}),hC=H.object({match:H.object({text:H.string()}).optional(),start:H.number(),end:H.number()}),gC=H.object({type:H.literal("match"),data:H.object({path:Dr,lines:H.object({text:H.string()}),line_number:H.number(),absolute_offset:H.number(),submatches:H.array(hC)})}),yC=H.object({type:H.literal("context"),data:H.object({path:Dr,lines:H.object({text:H.string()}),line_number:H.number(),absolute_offset:H.number()})}),RC=H.object({type:H.literal("begin"),data:H.object({path:Dr})}),bC=H.object({type:H.literal("end"),data:H.object({path:Dr,stats:H.object({elapsed:H.object({human:H.string()}),searches:H.number(),searches_with_match:H.number()}).optional()})}),SC=H.object({type:H.literal("summary"),data:H.object({elapsed_total:H.object({human:H.string()}),stats:H.object({elapsed:H.object({human:H.string()}),searches:H.number(),searches_with_match:H.number(),bytes_searched:H.number(),bytes_printed:H.number(),matched_lines:H.number(),matches:H.number()})})}),qM=H.discriminatedUnion("type",[gC,yC,RC,bC,SC]);var CC=1e5,Gi=new Set(["hints","warnings","pagination","outputPagination"]);function Ed(){return Math.min(Math.max(we(),1),CC)}function Td(e,t=Ed()){return{offset:e.offset??0,length:Math.max(e.length??t,1),explicit:e.offset!==void 0||e.length!==void 0}}function ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function ve(e){return JSON.stringify(e)}function wd(e,t,n,r){let o=Math.max(r,1),i=Math.max(n,0),s=Math.max(1,Math.ceil(i/o)),a=i===0?0:Math.max(i-1,0),c=Math.min(Math.max(e,0),a),l=i===0?1:Math.min(s,Math.floor(c/o)+1),d=e+t<i;return{currentPage:l,totalPages:d?Math.max(s,l+1):l,hasMore:d,charOffset:e,charLength:t,totalChars:i}}function xd(e,t,n,r){let o=Array.isArray(e.hints)?e.hints.filter(p=>typeof p=="string"):[],i=t.charOffset??0,s=t.charLength??0,a=t.totalChars??0,c=i+s,l=`Page ${t.currentPage}/${t.totalPages} (${s} of ${a} chars)`,d=n==="response"?`Use responseCharOffset=${c} to continue this paginated bulk response.`:`Use charOffset=${c} to continue this paginated result.`,u=`Auto-paginated: Output (${a} chars) exceeds ${r.requestedLength} char limit.`,m=[...o];return r.autoPaginated&&t.hasMore&&!m.includes(u)&&m.push(u),m.includes(l)||m.push(l),t.hasMore&&!m.includes(d)&&m.push(d),{...e,hints:m}}function PC(e,t){let n={...e};delete n.outputPagination;for(let s of t)s.kind==="array"&&Array.isArray(n[s.field])&&(n[s.field]=[]),s.kind==="record"&&ye(n[s.field])&&(n[s.field]={});let r=ve(n).length,o=[],i=r;for(let s of t){let a=e[s.field];if(s.kind==="array"&&Array.isArray(a)&&a.length>0){let c=!0;for(let l of a){let d=ve(l),u=`${c?"":","}${d}`.length;o.push({field:s.field,kind:"array",value:l,start:i,end:i+u,itemPaginator:s.itemPaginator}),i+=u,c=!1}continue}if(s.kind==="record"&&ye(a)){let c=!0;for(let[l,d]of Object.entries(a)){let u=ve(d),m=`${c?"":","}${ve(l)}:${u}`.length;o.push({field:s.field,kind:"record",key:l,value:d,start:i,end:i+m,itemPaginator:s.itemPaginator}),i+=m,c=!1}}}return{baseObject:n,baseChars:r,segments:o,totalChars:i}}function EC(e,t){let n={...e};for(let r of t){if(r.kind==="array"){let i=Array.isArray(n[r.field])?[...n[r.field]]:[];i.push(r.value),n[r.field]=i;continue}let o=ye(n[r.field])?{...n[r.field]}:{};r.key!==void 0&&(o[r.key]=r.value),n[r.field]=o}return n}function TC(e,t,n,r){let o=n.findIndex(c=>c.end>r.offset);if(o===-1)return{selectedSegments:[],actualOffset:r.offset,pageEnd:r.offset};let i=[],s,a=0;for(let c=o;c<n.length;c+=1){let l=n[c],d=c===o?Math.max(0,r.offset-l.start):0,u=s===void 0?0:a-s,m=Math.max(r.length-u,1),p=l.end-l.start;if(d===0&&p<=m){s===void 0&&(s=r.offset<e?0:l.start),i.push(l),a=l.end;continue}if(l.itemPaginator){let f=l.itemPaginator(l.value,{offset:d,length:m,explicit:!0});if(f){s===void 0&&(s=r.offset<e?0:l.start+f.actualOffset),i.push({...l,value:f.value}),a=l.start+f.pageEnd;let h=f.pageEnd>=f.totalChars,y=a-s<r.length;if(h&&y)continue;break}}s===void 0&&(s=r.offset<e?0:l.start),i.push(l),a=l.end;break}return s===void 0&&(s=r.offset<e?0:Math.min(r.offset,t),a=Math.min(t,Math.max(e,s))),{selectedSegments:i,actualOffset:s,pageEnd:a}}function $i(e,t,n,r,o=!0){return!o||!e.explicit&&t<=e.length?{value:n,actualOffset:0,pageEnd:t,totalChars:t,paginated:!1}:e.offset>=t?{value:r,actualOffset:e.offset,pageEnd:e.offset,totalChars:t,paginated:!0}:null}function He(e,t,n){let r=ve(e).length;if(n.length===0)return{value:e,actualOffset:0,pageEnd:r,totalChars:r,paginated:!1};let{baseObject:o,baseChars:i,segments:s,totalChars:a}=PC(e,n),c=$i(t,a,e,o,s.length>0);if(c)return c;let l=TC(i,a,s,t);return{value:EC(o,l.selectedSegments),actualOffset:l.actualOffset,pageEnd:l.pageEnd,totalChars:a,paginated:!0}}function Gr(e,t){let n=Array.from(e),r=n.map(f=>Math.max(JSON.stringify(f).length-2,0)),i=2+r.reduce((f,h)=>f+h,0),s=$i(t,i,e,"");if(s)return s;let a=0,c=0;if(t.offset>1){let f=1,h=!1;for(let y=0;y<r.length;y+=1){let b=r[y];if(f+b>t.offset){a=y,c=f,h=!0;break}f+=b}if(!h)return{value:"",actualOffset:t.offset,pageEnd:t.offset,totalChars:i,paginated:!0}}let l=Math.max(1,t.length-(a===0?1:0)-1),d=0,u=a;for(;u<n.length;){let f=r[u];if(d+f>l&&u>a||(d+=f,u+=1,d>=l))break}u===a&&u<n.length&&(d+=r[u],u+=1);let m=a===0?0:c,p=d+(a===0?1:0)+(u===n.length?1:0);return{value:n.slice(a,u).join(""),actualOffset:m,pageEnd:Math.min(i,m+Math.max(p,1)),totalChars:i,paginated:!0}}function _d(e,t,n,r,o){let i={...e,[t]:r};delete i.outputPagination;let s=Math.max(ve(i).length-2,0),a=o(e[t],{offset:n.offset<=s?0:n.offset-s,length:n.offset<=s?Math.max(1,n.length-s):n.length,explicit:!0}),c=s+a.totalChars,l=$i(n,c,e,i);return l||{value:{...i,[t]:a.value},actualOffset:n.offset<=s?0:s+a.actualOffset,pageEnd:s+a.pageEnd,totalChars:c,paginated:!0}}function $r(e,t,n){return typeof e[t]!="string"?null:_d(e,t,n,"",(r,o)=>Gr(r,o))}function wC(e,t,n){return ye(e[t])?_d(e,t,n,{},(r,o)=>Ui(r,o)):null}function xC(e,t){return typeof e=="string"?Gr(e,t):ye(e)?Ui(e,t):null}function Ui(e,t){let n=[];for(let[i,s]of Object.entries(e))Gi.has(i)||Array.isArray(s)&&s.length>0&&n.push({field:i,kind:"array",itemPaginator:xC});let r=He(e,t,n);if(r.paginated)return r;for(let[i,s]of Object.entries(e)){if(Gi.has(i)||typeof s!="string")continue;let a=$r(e,i,t);if(a?.paginated)return a}for(let[i,s]of Object.entries(e)){if(Gi.has(i)||!ye(s))continue;let a=wC(e,i,t);if(a?.paginated)return a}let o=ve(e).length;return{value:e,actualOffset:0,pageEnd:o,totalChars:o,paginated:!1}}function _C(e,t){return ye(e)?He(e,t,[{field:"text_matches",kind:"array",itemPaginator:(n,r)=>typeof n=="string"?Gr(n,r):ye(n)?$r(n,"value",r):null}]):null}function AC(e,t){return!ye(e)||ve(e).length<=Ed()?null:He(e,t,[{field:"fileChanges",kind:"array",itemPaginator:(n,r)=>ye(n)?$r(n,"patch",r):null}])}function LC(e,t){return ye(e)?$r(e,"value",t):null}function OC(e,t){return ye(e)?He(e,t,[{field:"matches",kind:"array",itemPaginator:LC}]):null}function Ad(e,t,n){let r;switch(e){case S.GITHUB_SEARCH_CODE:r=He(t,n,[{field:"files",kind:"array",itemPaginator:_C}]);break;case S.GITHUB_SEARCH_REPOSITORIES:r=He(t,n,[{field:"repositories",kind:"array"},{field:"repositoryDetails",kind:"array"}]);break;case S.GITHUB_VIEW_REPO_STRUCTURE:r=He(t,n,[{field:"structure",kind:"record"}]);break;case S.PACKAGE_SEARCH:r=He(t,n,[{field:"packages",kind:"array"}]);break;case S.GITHUB_CLONE_REPO:r=He(t,n,[{field:"hints",kind:"array",itemPaginator:(o,i)=>typeof o=="string"?Gr(o,i):null}]);break;case S.LOCAL_RIPGREP:r=He(t,n,[{field:"files",kind:"array",itemPaginator:OC}]);break;case S.LOCAL_VIEW_STRUCTURE:r=He(t,n,[{field:"entries",kind:"array"}]);break;case S.GITHUB_SEARCH_PULL_REQUESTS:r=He(t,n,[{field:"pull_requests",kind:"array",itemPaginator:AC}]);break;case S.LOCAL_FIND_FILES:{let o=ve(t).length;return{value:t,actualOffset:0,pageEnd:o,totalChars:o,paginated:!1}}case S.GITHUB_FETCH_CONTENT:case S.LOCAL_FETCH_CONTENT:return{value:t,actualOffset:0,pageEnd:ve(t).length,totalChars:ve(t).length,paginated:!1};default:r={value:t,actualOffset:0,pageEnd:ve(t).length,totalChars:ve(t).length,paginated:!1};break}return r.paginated?r:Ui(t,n)}function IC(e,t,n){if(!ye(e)||!ye(e.data)||e.status!==void 0)return null;let r={...e,data:{}},o=Math.max(ve(r).length-2,0),i=Ad(n,e.data,{offset:t.offset<=o?0:t.offset-o,length:t.offset<=o?Math.max(1,t.length-o):t.length,explicit:!0}),s=o+i.totalChars;if(!i.paginated&&(!t.explicit||s<=t.length))return{value:e,actualOffset:0,pageEnd:s,totalChars:s,paginated:!1};if(t.offset>=s)return{value:r,actualOffset:t.offset,pageEnd:t.offset,totalChars:s,paginated:!0};let a=wd(i.actualOffset,Math.max(0,i.pageEnd-i.actualOffset),i.totalChars,t.length),c=i.paginated&&ye(i.value)?xd({...i.value,outputPagination:a,...n===S.LOCAL_FIND_FILES&&{charPagination:a}},a,"output",{autoPaginated:!1,requestedLength:t.length}):i.value;return{value:{...e,data:c},actualOffset:t.offset<=o?0:o+i.actualOffset,pageEnd:o+i.pageEnd,totalChars:s,paginated:!0}}function rN(e,t,n){if(!ye(e.data)||e.status!==void 0)return e;let r=Td({offset:typeof t.charOffset=="number"?t.charOffset:void 0,length:typeof t.charLength=="number"?t.charLength:void 0});if(!r.explicit)return e;let o=Ad(n,e.data,r);if(!o.paginated)return e;let i=wd(o.actualOffset,Math.max(0,o.pageEnd-o.actualOffset),o.totalChars,r.length),s=xd({...o.value,outputPagination:i},i,"output",{autoPaginated:!r.explicit,requestedLength:r.length});return{...e,data:s}}function oN(e,t,n){let r=Td(t,Vs(e.results.length));if(!r.explicit&&e.results.length>0&&e.results.every(i=>ye(i?.data)&&i.data.outputPagination!==void 0))return e;let o=He({results:e.results},r,[{field:"results",kind:"array",itemPaginator:(i,s)=>IC(i,s,n)}]);return o.paginated?{results:Array.isArray(o.value.results)?o.value.results:[]}:e}import{securityRegistry as SG,ContentSanitizer as CG}from"octocode-security";import{maskSensitiveData as EG}from"octocode-security/mask";import{configureSecurity as wG}from"octocode-security/withSecurityValidation";import{getOctocodeDir as _G,paths as AG,getDirectorySizeBytes as LG,formatBytes as OG,isWindows as IG,isMac as kG,HOME as vG,getAppDataPath as FG,storeCredentials as MG,getCredentials as NG,getCredentialsSync as HG,deleteCredentials as DG,isTokenExpired as GG,isRefreshTokenExpired as $G,getCredentialsFilePath as UG,getEnvTokenSource as BG,hasEnvToken as zG,resolveTokenFull as QG,refreshAuthToken as jG,getTokenWithRefresh as VG,getGhCliToken as WG}from"octocode-shared";import{completeMetadata as YG}from"@octocodeai/octocode-core";import{z as JG}from"zod";export{XC as ALL_ERROR_CODES,ld as ALL_TOOLS,Jp as BASE_SCHEMA,Ln as BaseCommandBuilder,lc as BulkCloneRepoLocalSchema,Ci as BulkLspGetSemanticsQuerySchema,Qr as CONFIG_ERRORS,ur as CORE_ALLOWED_ENV_VARS,Pi as CircuitOpenError,Xo as CloneRepoQueryLocalSchema,or as ContentBuilder,CG as ContentSanitizer,yI as DEFAULTS,$v as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,Ii as DEFAULT_TOOL_METADATA_GATEWAY,lo as DESCRIPTIONS,md as DIRECT_TOOL_CATEGORIES,IM as DIRECT_TOOL_DEFINITIONS,st as DirectToolInputError,j as ERROR_CODES,de as ERROR_MESSAGES,ct as FETCH_ERRORS,Ae as FILE_OPERATION_ERRORS,pc as FileContentBulkQueryLocalSchema,Dh as FileContentQueryBaseLocalSchema,hr as FileContentQueryLocalSchema,yE as GENERIC_ERROR_HINTS,oM as GITHUB_CLONE_REPO,qF as GITHUB_FETCH_CONTENT,Ji as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,ZF as GITHUB_SEARCH_CODE,De as GITHUB_SEARCH_DEFAULT_LIMIT,me as GITHUB_SEARCH_MAX_LIMIT,WC as GITHUB_SEARCH_MAX_PAGES,nM as GITHUB_SEARCH_PULL_REQUESTS,tM as GITHUB_SEARCH_REPOSITORIES,Et as GITHUB_STRUCTURE_DEFAULTS,KC as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Wi as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,eM as GITHUB_VIEW_REPO_STRUCTURE,FA as GitHubCloneRepoOutputLocalSchema,Fc as GitHubCodeSearchBulkQueryLocalSchema,AL as GitHubCodeSearchOutputLocalSchema,vc as GitHubCodeSearchQueryLocalSchema,BA as GitHubFetchContentOutputLocalSchema,rr as GitHubProvider,Qc as GitHubPullRequestSearchBulkQueryLocalSchema,Pr as GitHubPullRequestSearchQueryLocalSchema,el as GitHubReposSearchBulkQueryLocalSchema,qc as GitHubReposSearchSingleQueryLocalSchema,$L as GitHubSearchPullRequestsOutputLocalSchema,hO as GitHubSearchRepositoriesOutputLocalSchema,il as GitHubViewRepoStructureBulkQueryLocalSchema,IO as GitHubViewRepoStructureOutputLocalSchema,ol as GitHubViewRepoStructureQueryLocalSchema,Go as HINTS,vG as HOME,Wp as IGNORED_FILE_EXTENSIONS,Vp as IGNORED_FILE_NAMES,Es as IGNORED_FOLDER_NAMES,uM as LOCAL_BINARY_INSPECT,Yi as LOCAL_DEFAULT_FILES_PER_PAGE,cM as LOCAL_FETCH_CONTENT,aM as LOCAL_FIND_FILES,kt as LOCAL_MAX_DEPTH,kn as LOCAL_MAX_FILES_PER_PAGE,It as LOCAL_MAX_LIMIT,iM as LOCAL_RIPGREP,B as LOCAL_TOOL_ERROR_CODES,Zi as LOCAL_TOOL_ERROR_REGISTRY,sM as LOCAL_VIEW_STRUCTURE,lM as LSP_GET_SEMANTIC_CONTENT,Re as LSP_GET_SEMANTIC_CONTENT_TOOL_NAME,al as LocalBinaryInspectBulkQuerySchema,Er as LocalBinaryInspectQuerySchema,Al as LocalFetchContentBulkQuerySchema,Tr as LocalFetchContentQuerySchema,kl as LocalFindFilesBulkQuerySchema,wr as LocalFindFilesQuerySchema,Gl as LocalRipgrepBulkQuerySchema,gt as LocalRipgrepQuerySchema,Wd as LocalToolErrorCategory,tu as LocalViewStructureBulkQuerySchema,_r as LocalViewStructureQuerySchema,uS as LspGetSemanticsOutputSchema,Si as LspGetSemanticsQueryDisplaySchema,Yb as LspGetSemanticsQuerySchema,fp as MAX_BRANCH_CACHE_SIZE,vt as MAX_CHAR_LENGTH,Xi as MAX_CONTEXT_LINES,js as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Am as MAX_DIRECTORY_FILES,Fn as MAX_MATCH_CONTENT_LENGTH,vn as MAX_PAGE_NUMBER,Lm as MAX_TOTAL_SIZE,to as NETWORK_ERROR_PATTERNS,zu as NpmDeprecationOutputSchema,Bu as NpmRegistrySearchSchema,ad as NpmSearchBulkQueryLocalSchema,SF as NpmSearchOutputLocalSchema,sd as NpmSearchQueryLocalSchema,kr as NpmViewResultSchema,lp as OctokitWithThrottling,rM as PACKAGE_SEARCH,lt as PROMISE_ERRORS,Ia as PROVIDER_CAPABILITIES,Ba as PROXY_ENV_VARS,bt as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,Ki as PR_CONTENT_MAX_ITEMS_PER_PAGE,Yo as ProviderInitializationError,zx as QuickResult,Gn as RATE_LIMIT_CONFIG,no as RATE_LIMIT_PATTERNS,We as REPOSITORY_ERRORS,$l as REQUIRED_COMMANDS,Me as RESOURCE_LIMITS,In as RipgrepCommandBuilder,qM as RipgrepJsonMessageSchema,ne as SEARCH_ERRORS,is as SEMANTIC_CONTENT_TYPES,Q_ as SENSITIVE_ENV_VARS,Vd as STARTUP_ERRORS,K as STATIC_TOOL_NAMES,hs as STATUS_TO_ERROR_CODE,ir as StatusEmoji,Hf as StatusEmojis,yn as TOOLING_ALLOWED_ENV_VARS,Mn as TOOL_ERRORS,gE as TOOL_HINTS,jd as TOOL_METADATA_ERRORS,S as TOOL_NAMES,Pe as ToolError,Fe as ToolErrors,at as VALIDATION_ERRORS,wS as _packageNameToSearchKeywords,gM as _resetMetadataState,oF as _resetNpmRegistryUrlCache,fP as _resetTokenResolvers,mP as _setTokenResolvers,Hd as allowRipgrepCommandName,oN as applyBulkResponsePagination,Js as applyContentPagination,ou as applyEntryFilters,mg as applyExactMatchRanking,XM as applyOutputSizeLimit,tt as applyPagination,Jn as applyPartialContentFilter,rN as applyQueryOutputPagination,Aa as applyStructurePagination,Du as assertCircuitAvailable,U as attachRawResponseChars,CT as buildBlockBoundaryHint,Qo as buildChildProcessEnv,Rs as buildCodeSearchQuery,Uc as buildContentHints,GM as buildDirectToolExampleQuery,ui as buildEntryPaginationHints,Lc as buildGhSearchCodeFinalizer,_c as buildGithubFetchContentFinalizer,Gg as buildPRSearchOutput,Wt as buildPaginationHints,Ss as buildPullRequestSearchQuery,bs as buildRepoSearchQuery,dy as buildRepoStructureOutput,Yt as buildSearchResult,pd as buildToolErrorResult,di as buildWalkWarnings,zm as byteSlice,Wn as byteToCharIndex,Ws as charToByteIndex,xk as checkAllCommandsAvailability,si as checkCommandAvailability,BO as checkLargeOutputSafety,Dv as checkNpmAvailability,Li as checkNpmDeprecation,iF as checkNpmRegistryReachable,ai as checkRegexSafety,F as clampedInt,hP as cleanup,qP as clearAllCache,Ak as clearAvailabilityCache,tE as clearLSPToolCache,eE as clearLocalToolCache,$P as clearOctokitInstances,Mx as clearProviderCache,nE as clearRemoteAPICache,ja as cloneRepo,gr as collectFlatErrors,ah as commonDirPrefix,Yr as compactLocation,Mt as compactResolvedSymbol,Vc as compareIsoDateDescending,YG as completeMetadata,gh as computeQueryTimeout,Bv as configureCircuitBreaker,wG as configureSecurity,jt as contextLinesField,fT as convertByteMatchToChar,G as countSerializedChars,yo as createBasePRTransformation,Qn as createCacheMeta,Sn as createCallItemKey,A as createErrorResult,nt as createGitHubProviderError,nr as createGitHubProviderErrorFromResult,Be as createLazyProviderContext,dn as createPaginationInfo,wh as createProviderExecutionContext,X as createRelaxedBulkQuerySchema,gn as createResponseFormat,Bx as createResult,sr as createRoleBasedResult,M0 as createSafeRegExp,Se as createSuccessResult,xt as dedupeHints,DG as deleteCredentials,QM as detectEnvironment,jn as ensureCloneParentDir,zt as evictExpiredClones,J as executeBulkOperation,ac as executeCloneRepo,UM as executeDirectTool,Ll as executeFetchContent,Nl as executeFindFiles,Wl as executeGrepFallbackSearch,Pl as executeInspectBinary,yi as executeLspGetSemantics,Cn as executeNpmCommand,ft as executeProviderOperation,sc as executeProviderOperations,Zl as executeRipgrepSearch,jl as executeRipgrepSearchInternal,lu as executeViewStructure,Ya as executeWithErrorIsolation,Le as executeWithToolBoundary,tl as exploreMultipleRepositoryStructures,Yn as extractMatchingLines,Ka as fallbackOnBestEffortFailure,wl as fetchContent,Ds as fetchDirectoryContents,Po as fetchDirectoryContentsRecursivelyAPI,Zs as fetchFileTimestamp,ea as fetchGitHubFileContentAPI,lw as fetchGitHubPullRequestByNumberAPI,Co as fetchGitHubPullRequestByNumberAPIInternal,Ea as fetchHistory,Ac as fetchMultipleGitHubFileContents,Bs as fetchRawGitHubFileContent,yt as fetchWithRetries,ta as filterPatch,uy as filterStructure,ii as finalizeFetchContentResult,Fl as finalizeFindFilesResult,Ql as finalizeRipgrepResult,cu as finalizeViewStructureResult,yd as findDirectToolDefinition,vl as findFiles,mn as findNextBlockBoundary,OG as formatBytes,Qx as formatCallToolResultForOutput,FM as formatDirectToolMetadataSchemaText,HM as formatDirectToolOutputSchemaText,vM as formatDirectToolSchemaText,rC as formatDirectToolValidationIssues,D0 as formatEntryString,Kt as formatFileSize,yr as formatFinalizedResponse,fn as formatPRForResponse,rO as formatRepoLine,pi as gatherIncomingCallsRecursive,mi as gatherOutgoingCallsRecursive,Ee as generateCacheKey,_a as generatePaginationHints,er as generateStructurePaginationHints,rn as getActiveProvider,Kr as getActiveProviderConfig,FG as getAppDataPath,Vs as getBulkDefaultCharLength,Ks as getByteLength,rE as getCacheStats,gm as getCacheTTL,Un as getCloneDir,NG as getCredentials,UG as getCredentialsFilePath,HG as getCredentialsSync,cd as getDescription,MM as getDirectToolAutoFilledFields,Hr as getDirectToolCategory,DM as getDirectToolDescription,Rd as getDirectToolDisplayFields,NM as getDirectToolOutputFields,LG as getDirectorySizeBytes,bE as getDynamicHints,Uo as getDynamicToolHints,BG as getEnvTokenSource,iE as getExtension,Ma as getFileContent,SE as getGenericErrorHintsSync,WG as getGhCliToken,rs as getGitHubToken,oe as getHints,VM as getLspEnvironmentHint,ym as getMaxCacheSizeBytes,Rm as getMaxCloneCount,hM as getMetadataOrNull,_k as getMissingCommandError,wi as getNpmRegistryUrl,_G as getOctocodeDir,re as getOctokit,we as getOutputCharLimit,Lp as getOwnerQualifier,To as getProvider,ee as getRawResponseChars,Ha as getRepoStructure,Is as getReposBaseDir,Nn as getServerConfig,Nt as getSessionManager,yP as getTokenSource,VG as getTokenWithRefresh,RE as getToolHintsSync,No as ghCloneRepoHints,Io as ghSearchCodeHints,Fo as ghSearchPRsHints,vo as ghViewRepoStructureHints,ko as githubFetchContentHints,Mo as githubSearchReposHints,ge as handleCatchError,Z as handleGitHubAPIError,lr as handleProviderError,$o as hasDynamicHints,zG as hasEnvToken,Nc as hasExpensiveContentRequest,Za as hoistSharedFields,je as ignoreBestEffortFailure,ns as initialize,Ga as initializeProviders,_P as initializeSession,fM as initializeToolMetadata,H_ as invokeCallbackSafely,zn as isCacheHit,ks as isCacheValid,$u as isCircuitOpen,Hn as isCloneEnabled,Fr as isExactPackageName,Tt as isGitHubAPIError,hf as isGitHubAPISuccess,gP as isLocalEnabled,Xr as isLocalTool,os as isLoggingEnabled,kG as isMac,pn as isMidBlockCut,Ct as isNoResultsSearchError,Eh as isProviderError,mr as isProviderSuccess,$G as isRefreshTokenExpired,gf as isRepository,GG as isTokenExpired,jr as isToolError,uo as isToolInMetadata,IG as isWindows,Vt as lineNumberField,mM as loadToolContent,Ao as localFetchContentHints,Oo as localFindFilesHints,_o as localRipgrepHints,Lo as localViewStructureHints,as as logPackageRegistryFailure,OP as logPromptCall,ut as logRateLimit,D as logSessionError,AP as logSessionInit,LP as logToolCall,Do as lspSemanticContentHints,gc as mapCodeSearchProviderResult,fc as mapCodeSearchToolQuery,Pc as mapFileContentProviderResult,Cc as mapFileContentToolQuery,Sc as mapPullRequestProviderResultData,bc as mapPullRequestToolQuery,Rc as mapRepoSearchProviderRepositories,yc as mapRepoSearchToolQuery,Tc as mapRepoStructureProviderResult,Ec as mapRepoStructureToolQuery,EG as maskSensitiveData,hn as normalizeOwnerRepo,Mc as normalizePullRequestContentRequest,$n as normalizeResponseHeaders,Ho as npmSearchHints,li as paginateEntries,YA as paginateGroupsCharWindow,xR as parseCountOutput,Rn as parseFileSize,wR as parseFilesOnlyOutput,pe as parseGitHubProjectId,Ul as parseRipgrepJson,zl as parseRipgrepOutput,AG as paths,xr as preflightValidateRipgrepPattern,nC as prepareDirectToolInput,$M as prepareDirectToolInputFromJsonText,qs as processFileContentAPI,fr as providerSupports,mo as readCacheMeta,Gu as recordCircuitFailure,Ti as recordCircuitSuccess,nn as redactPath,jG as refreshAuthToken,Ja as relativizeResultPaths,q as relaxedPageNumberField,fo as removeCloneDir,Uv as resetCircuitBreaker,IP as resetSessionManager,$e as resolveDefaultBranch,fi as resolveFileAnchor,Qd as resolveRgFromPath,On as resolveRipgrepBinary,mu as resolveSymbolAnchor,QG as resolveTokenFull,xe as responseEnvelopeFields,Oe as safeExec,Nr as sanitizeCallToolResult,Ye as sanitizeStructuredContent,va as searchCode,Jl as searchContentRipgrep,As as searchGitHubCodeAPI,Ca as searchGitHubPullRequestsAPI,xa as searchGitHubReposAPI,Oc as searchMultipleGitHubCode,jc as searchMultipleGitHubPullRequests,Xc as searchMultipleGitHubRepos,ed as searchNpmPackage,td as searchPackage,rd as searchPackages,Na as searchPullRequests,Fa as searchRepos,SG as securityRegistry,yT as serializeForPagination,$c as shapePullRequestForContent,an as shouldIgnoreDir,Ut as shouldIgnoreFile,jM as shouldUseMCPLsp,Cs as shouldUseSearchForPRs,RT as sliceByCharRespectLines,go as sliceContent,Kn as snapToSemanticBoundary,kM as sortDirectToolNames,dr as spawnCheckSuccess,j_ as spawnCollectStdout,wt as spawnWithTimeout,VE as startCacheGC,WE as stopCacheGC,MG as storeCredentials,ci as summarizeEntries,su as toEntryObject,iu as toGroupedLists,qi as toToolError,Sf as transformCodeSearchResult,Ef as transformFileContentResult,qn as transformPullRequestItemFromREST,ga as transformPullRequestItemFromSearch,_f as transformPullRequestResult,Cf as transformRepoSearchResult,Lf as transformRepoStructureResult,na as trimDiffContext,pr as validateArgs,Ce as validateToolPath,Oa as viewGitHubRepositoryStructureAPI,au as viewStructure,ji as withBasicSecurityValidation,Te as withDataCache,Jx as withResponseEnvelope,Qi as withSecurityValidation,Bn as writeCacheMeta,JG as z};
|
|
44
|
+
`)}async function bp(e,t){let n=await Js(GS(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?BS(n.stdout,n.commandUsed):n.stdout).split(`
|
|
45
|
+
`).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function Sp(e,t){return Js(US(e,t))}function zS(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return Ze(Rp,e)?[c]:Ze(Xs,e)?[s,a,o,n,r]:Ze(Ys,e)?[o,s,a,n,r]:Ze(Ks,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Cp(e,t){return Js(zS(e,t))}var QS={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},jS=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],$S={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"};function VS(e){let t=e.toLowerCase();for(let{ext:n,format:r}of jS)if(t.endsWith(n))return r}async function WS(e){let t=await On("file",["--mime-type","-b",e]);if(t.success)return $S[t.stdout.trim().toLowerCase()]}async function KS(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await On(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await On(r.command,r.args)).stderr,commandUsed:r.command}}async function Pp(e,t){let n;if(t!=="auto"?n=t:n=VS(e)??await WS(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=QS[n],o=await KS(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}function Ep(e){try{return{success:!0,info:O.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function Tp(e,t,n,r=0){try{let o=O.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var ZS=S.LOCAL_BINARY_INSPECT;function wp(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function qS(e){return Zs(W.unzip,`${qo(e)}-${wp()}`)}function eC(e,t){return Zs(W.binary,`${qo(e)}-${t}-${wp()}`)}function tC(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function qs(e,t,n,r){let o=xp(eC(e,t)),i=xp(Zs(o,tC(n)));if(!i.startsWith(o+XS)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await In.mkdir(YS(i),{recursive:!0}),await In.writeFile(i,r,"utf-8"),i}var nC=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],_p=!1;function rC(){if(!_p){try{JS.addAllowedCommands(nC)}catch{}_p=!0}}var oC=1e3,iC=8;function Ap(e,t,n){let r=O.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
|
|
46
|
+
`):null}function ea(e,t,n,r){let s=mt(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function sC(e,t){let n=Ep(e);if(!n.success||!n.info)return L(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function aC(e,t){let n=t.verbose??!1,r=await bp(e,n);if(!r.success)return L(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??oC,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,u=a?s.slice((c-1)*a,c*a):s,l=a?Math.ceil(s.length/a):1,d=a?c<l:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:u,...a&&{pagination:{currentPage:c,totalPages:l,hasMore:d,entriesPerPage:a,totalEntries:s.length}}}}async function cC(e,t){let n=t.archiveFile,r=await Sp(e,n);if(!r.success)return L(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return L("Entry is empty",t);let i=await qs(e,"extract",n,o);if(t.matchString){let c=Ap(o,t.matchString,t.matchStringContextLines??3);if(!c)return L(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=Ce(),a=ea(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,contentLength:o.length,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function uC(e,t){let n=await Pp(e,t.format??"auto");if(!n.success)return L(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return L("Decompressed file is empty",t);let o=await qs(e,"decompress",`${qo(e)}.decompressed.txt`,r);if(t.matchString){let a=Ap(r,t.matchString,t.matchStringContextLines??3);if(!a)return L(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=Ce(),s=ea(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,contentLength:r.length,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function lC(e,t){let n=t.minLength??iC,r=t.includeOffsets??!1,o=t.scanOffset??0,i=Tp(e,n,r,o);if(!i.success)return L(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
|
|
47
|
+
`),a=s?await qs(e,"strings",`${qo(e)}.strings.txt`,s):void 0,c=Ce(),u=ea(s,t.charOffset,t.charLength,c);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},contentLength:s.length,totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function dC(e,t){try{await In.stat(e)}catch{return L(`File not found: ${e}`,t)}let n=qS(e);await In.mkdir(n,{recursive:!0});let r=await Cp(e,n);if(!r.success)return L(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await In.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function Lp(e){rC();let t=ve(e,ZS);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await In.stat(n)).isFile())return L(`Path is not a regular file: ${n}`,e)}catch{return L(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return sC(n,e);case"list":return aC(n,e);case"extract":return cC(n,e);case"decompress":return uC(n,e);case"strings":return lC(n,e);case"unpack":return dC(n,e);default:return L(`Unknown mode: ${String(e.mode)}`,e)}}async function Op(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Le(Zo,n);if(r.ok===!1)return r.error;let o=await Lp(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return U(o,s),o}}),{toolName:S.LOCAL_BINARY_INSPECT},e)}import{open as pC,readFile as fC,stat as mC}from"fs/promises";import{ContentSanitizer as gC}from"@octocodeai/octocode-engine/contentSanitizer";var oN={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},st={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 kp(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ip(e,t,n){return{...e,...kp(t,n)}}function hC(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};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 yC(e,t){try{return{fileStats:await mC(t)}}catch(n){let r=De.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:L(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function RC(e,t){return t>st.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function bC(e,t,n){let r=De.fileTooLarge(e.path,n,st.LARGE_FILE_THRESHOLD_KB);return L(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function SC(e,t){let n=De.binaryFileUnsupported(e.path);return L(n,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function CC(e){let n=Buffer.alloc(8192),r;try{r=await pC(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let u=i[c];if(u===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 l=u===9||u===10||u===13;u<32&&!l&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(Tu("binary sample handle close",void 0))}}async function PC(e,t){try{return{content:await fC(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?De.fileAccessFailed(e.path,r):De.fileReadFailed(e.path,r);return{errorResult:L(i,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function EC(e,t){return{status:"empty",errorCode:H.NO_MATCHES,totalLines:t}}function TC(e,t,n){let r=xo(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:EC(e,n)};let o=r.lines.join(`
|
|
48
|
+
`),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.`,u,l,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(u=m.start,l=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:u,actualEndLine:l,matchRanges:d,warnings:[c]}}function xC(e){return e.startLine!==void 0&&e.endLine!==void 0}function _C(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:H.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:H.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
|
|
49
|
+
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function wC(e,t,n){let r=t.split(`
|
|
50
|
+
`),o=Wt(t);return e.matchString?TC(e,r,o):xC(e)?_C(e,r,o):{resultContent:t,isPartial:!1}}function AC(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),u=i?O.applyContentViewMinification(t.resultContent,c):t.resultContent,l=e.charLength,d=e.charOffset??0,m=l,p=!1,f=d;m===void 0&&u.length>o&&(m=o,p=!0,a.push(`Auto-paginated: Content (${u.length} chars) exceeds ${o} char limit`));let g="char-limit",h=m;if(m!==void 0){let C=To(u,f,m,c);g=C.chunkMode,h=C.length}let R=mt(u,f,h,m!==void 0?{pageSize:m}:void 0),b=t.isPartial||R.hasMore,P;if(R.hasMore&&g==="char-limit"&&Sr(R.paginatedContent)){let C=R.charOffset+R.charLength;P=Cr(u,C,c)}let x=R.hasMore&&R.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:R.nextCharOffset,charLength:m??R.charLength,minify:e.minify}}}:void 0;return{path:c,content:R.paginatedContent,...s!=="standard"&&{contentView:s},...b&&{isPartial:b},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...(m!==void 0||d>0||p)&&{pagination:{...br(R),chunkMode:g,...P!==void 0&&{nextBlockChar:P}}},...x?{next:x}:{},...a.length>0&&{warnings:a}}}function LC(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function vp(e){let t=Ce();try{let n=ve(e,S.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=hC(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await yC(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,u=c/1024;if(await CC(o))return U(SC(e,o),c);if(RC(e,u))return U(bC(e,o,u),c);let{content:l,errorResult:d}=await PC(e,o);if(d||l===void 0)return d;let m=gC.sanitizeContent(l,i),p=m.content,f=p.length,g=Buffer.byteLength(p,"utf-8"),h=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,R=e.minify,b=R==="standard"||R==="symbols",P=b?"standard":"none",x;if(R==="symbols"){let w=O.extractSignatures(p,i);if(w===null&&(x=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),w!==null){let A=Wt(p),Q=O.applyContentViewMinification(w,i);return U({path:e.path,content:Q,contentView:"symbols",isSkeleton:!0,totalLines:A,...kp(f,g),...h?{warnings:[h]}:{}},f)}}let C=Wt(p),_=wC(e,p,t),I=w=>{let A=[...x?[x]:[],...h?[h]:[]];if(A.length===0)return w;let Q=w.warnings??[];return{...w,warnings:[...Q,...A]}};if(_.earlyResult){let w=_.earlyResult.content,A=b&&typeof w=="string"?{..._.earlyResult,content:O.applyContentViewMinification(w,i)}:_.earlyResult;return U(Ip(I(ta(LC(A,P),e,C)),f,g),f)}let j=AC(e,_,s,C,t,b,P);return U(Ip(I(ta(j,e,C)),f,g),f)}catch(n){return L(n,e,{toolName:S.LOCAL_FETCH_CONTENT})}}function ta(e,t,n){return e}import{z as OC}from"zod";import{FetchContentQuerySchema as Fp}from"@octocodeai/octocode-core/schemas";var IC=OC.enum(["none","standard","symbols"]).optional().default("standard"),Mp={startLine:Ln,endLine:Ln,contextLines:An.default(5),charOffset:v(0,1e8).optional(),charLength:v(1,5e4).optional(),minify:IC},kC=ce(Fp,Mp),ei=re(Fp,Mp),Np=X(kC,{maxQueries:5});async function Dp(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Le(ei,n);return r.ok===!1?r.error:await vp(r.data)}}),{toolName:S.LOCAL_FETCH_CONTENT},e)}import{z as vC}from"zod";import{FindFilesQuerySchema as FC}from"@octocodeai/octocode-core/schemas";var Hp={maxDepth:v(0,100).optional(),minDepth:v(0,100).optional(),limit:v(1,1e4).optional(),page:q.default(1),itemsPerPage:v(1,50).optional()},Gp=vC.object(Object.fromEntries(Object.entries(FC.shape).filter(([e])=>e!=="regexType")));function MC(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 NC=ce(Gp,Hp),ti=re(Gp,Hp).superRefine(MC),Up=X(NC,{maxQueries:5});function kn(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function Ar(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var DC=[];function HC(e,t){let n=t??DC,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Bp(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=ve(e,S.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:HC(i.path,i.excludeDir)},a=QC(s),c=e.limit??1e4,u=O.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),l=u.totalDiscovered,d=u.wasCapped,m=u.entries.map(A=>GC(A,r)),p=e.sortBy||"modified";UC(m,p,r);let f=BC(m,t,n),g=f.length,h=e.itemsPerPage||20,R=e.page||1,b=Math.max(1,Math.ceil(g/h)),P=(R-1)*h,x=Math.min(P+h,g),_=f.slice(P,x),I=[...u.warnings,...u.skipped>0?[`${u.skipped} entr${u.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],j=[...a,...I],w={...g===0?{status:"empty"}:{},path:i.path,files:_,pagination:{currentPage:R,totalPages:b,filesPerPage:h,totalFiles:g,hasMore:R<b,...R<b?{nextPage:R+1}:{},...d?{totalFilesFound:l}:{}},...j.length>0&&{warnings:j}};return U(zp(w,e,{totalFiles:g}),u.entries.reduce((A,Q)=>A+Q.path.length,0))}catch(o){return L(o,e,{toolName:S.LOCAL_FIND_FILES})}}function GC(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 zp(e,t,n){return e}function UC(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 BC(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=kn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var zC=/^\d+[hdwm]$/;function QC(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!zC.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}async function Qp(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Le(ti,n);return r.ok===!1?r.error:await Bp(r.data)}}),{toolName:S.LOCAL_FIND_FILES},e)}import{z as na}from"zod";import{RipgrepQuerySchema as jp}from"@octocodeai/octocode-core/schemas";var jC=["semanticRanking"],$p={contextLines:An,matchContentLength:v(1,1e5).optional().default(500),maxMatchesPerFile:v(1,1e5).optional(),maxFiles:v(1,1e5).optional(),matchPage:q.optional(),itemsPerPage:v(1,1e3).optional(),page:q.default(1),unique:na.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:na.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},$C={...$p,semanticRanking:na.never().optional()},VC=ce(jp,$C),WC=re(jp,$p,{strict:!0,omit:jC}),vn=WC.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),Vp=X(VC,{maxQueries:5});import{validateRipgrepQuery as FP}from"@octocodeai/octocode-core/schemas/runtime";var Wp=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],ee={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},KC=2e3,YC=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Kp={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Lr={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Kp},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Kp},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/]}},XC=/^\s*#{1,6}\s/,oa=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,JC=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,ZC=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,qC=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,eP=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,tP=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,nP=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,rP=new Set(["typescript","javascript","rust","python","go","java","scala"]),Xp=/\.([a-z0-9]+)$/i;function ia(e){return Xp.exec(e)?.[1]?.toLowerCase()??""}function oP(e){let t=ia(e);if(!t)return!1;for(let n of rP)if(Lr[n].extensions.includes(t))return!0;return!1}function iP(e,t,n){if(n&&n!=="auto")return Lr[n];let r=ia(e),o=(t??"").toLowerCase();for(let i of Wp){let s=Lr[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Wp){let s=Lr[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Lr.generic}function Jp(e){return JC.test(e)?"generated":qC.test(e)?"fixture":ZC.test(e)?"test":tP.test(e)?"config":eP.test(e)?"docs":!oa.test(e)&&(nP.test(e)||oP(e))?"source":"unknown"}function sP(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function aP(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 cP(e,t,n,r,o){if(!e||e.length===0)return 0;let i=bP(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=SP(u,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${qp(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(d+=ee.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(d+=ee.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(d+=ee.substring,m.push("substring match")));let p=c.kind;if(p)d+=uP(p,m);else{let f=CP(l,r,t.id,n.caseSensitive);f!=="code"?(d+=ee.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(ra(t.declaration,l)&&(d+=ee.declarationLine,m.push("declaration line")),ra(t.export,l)&&(d+=ee.exportLine,m.push("export/public line")),ra(t.import,l)&&(d+=ee.importLine,m.push("import line")),t.id==="markdown"&&XC.test(l)&&(d+=ee.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&lP(l,r)&&(d+=ee.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function uP(e,t){switch(e){case"declaration":return t.push("AST: declaration"),ee.declarationLine;case"export":return t.push("AST: export/public"),ee.exportLine;case"configKey":return t.push("AST: config key"),ee.configKeyLine;case"heading":return t.push("AST: heading"),ee.headingLine;case"import":return t.push("AST: import"),ee.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),ee.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function lP(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 dP(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(Xp,"").includes(u))&&(s+=ee.pathSegmentToken,i.push("query token in path"))}let a=ia(e);return r.extensions.includes(a)&&t.langType&&(s+=ee.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=ee.sourceDir,i.push("source file")),s}function pP(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),ee.lowSignalPathPenalty):0}function fP(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*ee.matchCountScale,r=Math.min(n,ee.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function mP(e,t){let n=aP(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=>gP(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 gP(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${qp(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function hP(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 u=Math.log2((t.candidateCount+1)/(c+1)),l=Math.min(u*ee.rareQueryTokenScale,ee.rareQueryTokenCap);l>i&&(i=l,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function yP(e,t,n){let r=iP(e.path,t.langType,t.profileOverride),o=Jp(e.path),i=sP(t.keyword),s=[],a=0;return a+=cP(e.matches,r,t,i,s),a+=dP(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=ee.pathUnderQuery,s.push("under requested subtree")),a+=pP(o,t,s),oa.test(e.path)&&!t.explicitLowSignal&&(a+=ee.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=fP(e.matchCount??0,s),a+=hP(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Zp(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Yp),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??KC,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Yp);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=mP(i,n),u=i.map(d=>{try{return{file:d,s:yP(d,n,c)}}catch{return{file:d,s:RP()}}});u.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let l={files:[...u.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(l.debug=new Map(u.map(d=>[d.file.path,d.s]))),l}function RP(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Yp(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function ra(e,t){for(let n of e)if(n.test(t))return!0;return!1}function qp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bP(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function SP(e,t,n){if(e.indexOf(`
|
|
51
|
+
`)<0)return e;let o=e.split(`
|
|
52
|
+
`);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 CP(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(YC.test(e))return"comment";let o=PP(e,t,r);if(o<0)return"code";let i=EP(e);return i>=0&&o>i?"comment":TP(e,o)?"string":"code"}function PP(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function EP(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 TP(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 ef(e){if(!e)return!1;if(oa.test(e))return!0;let t=Jp(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var tf=8,xP=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"]),_P=/^[A-Za-z_$][A-Za-z0-9_$]*$/;async function ri(e,t,n,r,o){let i=t.sort??"relevance",s;try{s=Zp(e,i,IP(t),{debug:!!t.debugRanking})}catch{s={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let a=s.files,c=s.debug,u=a,l=!1;t.maxFiles&&a.length>t.maxFiles&&(u=a.slice(0,t.maxFiles),l=!0);let d=u.length,m=!!(t.filesOnly||t.filesWithoutMatch),p=!!(t.countLinesPerFile||t.countMatchesPerFile),f=m||p,g=u.reduce(($,D)=>$+(D.matchCount??0),0),h=f?o?.matchCount??g:g,R=t,b=R.itemsPerPage||st.DEFAULT_FILES_PER_PAGE,P=R.page||1,x=Math.ceil(d/b),C=(P-1)*b,_=Math.min(C+b,d),I=u.slice(C,_),j=R.maxMatchesPerFile||st.DEFAULT_MATCHES_PER_PAGE,w=I.map($=>{let D=$.matches?.length??0,Re=Math.ceil(D/j),ue=Math.max(1,R.matchPage||1),at=(ue-1)*j,en=Math.min(at+j,D),V=f?void 0:$.matches?.slice(at,en),qe=c?.get($.path);return{path:$.path,...m?{}:{matchCount:p?$.matchCount||1:D},...V!==void 0&&{matches:V},...qe?{ranking:{score:qe.score,profile:qe.profile,pathRole:qe.pathRole,reasons:qe.reasons}}:{},pagination:!f&&D>j?{currentPage:ue,totalPages:Re,matchesPerPage:j,totalMatches:D,hasMore:ue<Re,...ue<Re?{nextMatchPage:ue+1}:{}}:void 0}}),A=w.filter($=>$.pagination?.hasMore),Q=wP(w,t,n,{isFileListMode:f,currentPage:P,totalFilePages:x,matchPage:R.matchPage||1,matchesPerPage:j,hasFileWithMoreMatches:A.length>0}),se={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:P,totalPages:x,filesPerPage:b,totalFiles:d,...m?{}:{totalMatches:h},hasMore:P<x,...P<x?{nextPage:P+1}:{},...l?{totalFilesFound:a.length}:{}},...r.length>0?{warnings:r}:{},...Object.keys(Q).length>0?{next:Q}:{}};return nf(se,t,{totalMatches:h,totalFiles:d})}function nf(e,t,n){return e}function wP(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=AP(i);s.fetchExact={tool:"localGetFileContent",query:ni({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:ni({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=LP(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:ni({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:ni({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function AP(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-tf),endLine:n+tf}}function LP(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return OP(e?.metavars);if(!t.matchWindow)return t.onlyMatching?sa(e?.value):sa(t.keywords)}}function OP(e){if(e)for(let t of Object.values(e))for(let n of t){let r=sa(n);if(r)return r}}function sa(e){if(typeof e!="string")return;let t=e.trim();if(_P.test(t)&&!xP.has(t))return t}function ni(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function IP(e){let t=e.rankingProfile,n=!!(e.include?.length||ef(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function rf(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=O.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&kP(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&vP(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function kP(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function vP(e){return/\(\?[=!<]/.test(e)}function MP(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function NP(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:MP(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function DP(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 of(e){let t=[],n=FP(e);if(!n.isValid)return L(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=vn.safeParse(e);if(!r.success){let g=r.error.issues.map(h=>h.message);return L(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return L(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}});let s=ve(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=rf({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return L(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await O.searchRipgrep(NP(a))}catch(g){return L(g instanceof Error?g:new Error(String(g)),o,{toolName:S.LOCAL_RIPGREP})}let d=l.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(h=>{let R={line:h.line,column:h.column,value:h.value};return h.count!==void 0&&(R.count=h.count),h.kind!==void 0&&(R.kind=h.kind),h.scoreHint!==void 0&&(R.scoreHint=h.scoreHint),R})})),m=DP(d),p={matchCount:l.stats.matchCount,matchedLines:l.stats.matchedLines,filesMatched:l.stats.filesMatched,filesSearched:l.stats.filesSearched,bytesSearched:l.stats.bytesSearched??void 0,searchTime:l.stats.searchTime};if(d.length===0)return U({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...u]},m);!a.filesOnly&&m>st.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let f=await ri(d,o,"rg",[...t,...u],p);return U(f,m)}var HP=[],GP=2e3,UP=1e6,BP="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`.",zP={ts:["ts","tsx","mts","cts"],typescript:["ts","tsx","mts","cts"],tsx:["tsx"],js:["js","jsx","mjs","cjs"],javascript:["js","jsx","mjs","cjs"],jsx:["jsx"],py:["py","pyi"],python:["py","pyi"],go:["go"],rs:["rs"],rust:["rs"],java:["java"],c:["c","h"],cpp:["cpp","hpp","cc","cxx","hh","hxx"],"c++":["cpp","hpp","cc","cxx","hh","hxx"],cs:["cs"],csharp:["cs"],sh:["sh","bash","zsh"],bash:["sh","bash","zsh"],shell:["sh","bash","zsh"],html:["html","htm"],css:["css"],scss:["scss"],less:["less"],scala:["scala","sc","sbt"],json:["json","jsonc"],yaml:["yaml","yml"],yml:["yaml","yml"],toml:["toml"]};function QP(e){if(!e)return;let t=e.trim().toLowerCase();return(zP[t]??[t.replace(/^[.*]+/,"")]).filter(Boolean).map(r=>`*.${r}`)}async function sf(e){let t=ve(e,S.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=O.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,include:e.include?.length?e.include:QP(e.langType),excludeDir:e.excludeDir?.length?e.excludeDir:HP,maxFiles:e.maxFiles??GP,maxFileBytes:UP})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return L(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:S.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.split(`
|
|
53
|
+
`,1)[0],column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={matchCount:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&i.push(BP),await ri(r,e,"structural",i,o)}function jP(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function af(e){let t=jP(e);if(t.mode==="structural")return await sf(t);t.contextLines===void 0&&(t.contextLines=2);try{return await of(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:H.OUTPUT_TOO_LARGE}:L(n,t,{toolName:S.LOCAL_RIPGREP})}}async function cf(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Le(vn,n);return r.ok===!1?r.error:await af(r.data)}}),{toolName:S.LOCAL_RIPGREP},e)}import{ViewStructureQuerySchema as uf}from"@octocodeai/octocode-core/schemas";var lf={maxDepth:v(0,20).optional(),limit:v(1,1e4).optional(),page:q.default(1),itemsPerPage:v(1,50).optional()},$P=ce(uf,lf),oi=re(uf,lf),df=X($P,{maxQueries:5});var VP=new Set(["+","*","?"]),WP=1e3;function KP(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function pf(e,t){let n=e[t];return n===void 0?!1:VP.has(n)||n==="{"&&JP(e,t)}function YP(e,t,n){let r=n.pop()??!1,o=pf(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?ff(e,t+1):t+1})}function XP(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:ff(e,t)})}function aa(e){if(e.length>WP)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=KP(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=YP(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(pf(e,r)){let i=XP(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function JP(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 ff(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function XD(e,t){let n=aa(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}function mf(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(!aa(s).safe)return n=n.filter(u=>(u.name.includes("/")?u.name.split("/").pop():u.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(u=>{let l=u.name.includes("/")?u.name.split("/").pop():u.name;return c.test(l)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function gf(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 hf(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 ca(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+Ar(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${kn(r)})`}function ua(e,t){let n=e.length,r=t.itemsPerPage||st.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function ZP(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function la(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}async function yf(e){try{let t=ve(e,S.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return qP(e,t.sanitizedPath,n)}catch(t){let n=De.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function qP(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=tE(e),s=r&&e.limit&&!eE(e,i)?e.limit*2:1e4,a;try{a=O.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:nE(e),limit:s})}catch(P){return iE(P,e,t)}let c=a.entries.map(P=>rE(P,n,e.details??!1)),u=mf(c,e),l=e.sortBy??"name";u=u.sort((P,x)=>{let C=0;switch(l){case"size":{let _=P.sizeBytes??(P.size?Ar(P.size):0),I=x.sizeBytes??(x.size?Ar(x.size):0);C=_-I;break}case"time":n&&P.modified&&x.modified?C=P.modified.localeCompare(x.modified):C=P.name.localeCompare(x.name);break;case"extension":C=(P.extension||"").localeCompare(x.extension||"");break;default:C=P.name.localeCompare(x.name);break}return e.reverse?-C:C}),e.limit&&(u=u.slice(0,e.limit));let d=u.length,{paginatedEntries:m,pagination:p}=ua(u,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(P=>({...hf(P),path:P.path??`${t.replace(/\/$/,"")}/${P.name}`}))}:{path:t,...gf(m)},h=[...a.warnings,...la({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],R=d===0,b=ca(u);return U(Rf({...R?{status:"empty"}:{},...g,summary:b,...p.hasMore||p.totalPages>1?{pagination:p}:{},...h.length>0&&{warnings:h}},e),a.entries.reduce((P,x)=>P+x.path.length,0))}function eE(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function tE(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function nE(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function rE(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:kn(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=oE(e.permissions)),o}function oE(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 iE(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=De.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return L(a,t,{toolName:S.LOCAL_VIEW_STRUCTURE})}function Rf(e,t){return e}async function bf(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Le(oi,n);return r.ok===!1?r.error:await yf(r.data)}}),{toolName:S.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import fE from"node:path";import{acquirePooledClient as wf,isLanguageServerAvailable as Af}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as mE}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Lf}from"@octocodeai/octocode-engine/lsp/workspaceRoot";import{safeReadFile as sE}from"@octocodeai/octocode-engine/lsp/validation";var Sf={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0};function Or(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Cf(e,t,n){if(t<=0)return e;let r=await sE(e.uri);if(!r)return e;let o=Rr(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((u,l)=>{let d=s+l+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${u}`}).join(`
|
|
54
|
+
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function aE(e,t){return Promise.all(e.map(async n=>({...n,from:await Cf(n.from,t,n.fromRanges)})))}async function cE(e,t){return Promise.all(e.map(async n=>({...n,to:await Cf(n.to,t)})))}async function da(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Sf};try{let i=await e.getIncomingCalls(t),s=o>0?await aE(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let u=Or(c.from);return r.has(u)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(u),da(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,u)=>c+u.cycleCount,0),failedRequestCount:a.reduce((c,u)=>c+u.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function pa(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Sf};try{let i=await e.getOutgoingCalls(t),s=o>0?await cE(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let u=Or(c.to);return r.has(u)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(u),pa(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,u)=>c+u.cycleCount,0),failedRequestCount:a.reduce((c,u)=>c+u.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}import{readFile as uE}from"node:fs/promises";import{SymbolResolver as lE,SymbolResolutionError as dE}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as Pf}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function fa(e,t){let n=e.uri,r=ve({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{return{ok:!0,value:{uri:o,absolutePath:o,content:await uE(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:Pf.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Ef(e,t){let n=await fa(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 lE({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),u=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:pE(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u}}}}}catch(o){if(o instanceof dE)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:Pf.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function pE(e){return{start:e,end:{line:e.line,character:e.character}}}var ma;function Of(e){return ma||(ma=new Set(O.getSupportedJsTsExtensions().map(t=>`.${t}`))),ma.has(fE.extname(e).toLowerCase())}function gE(e,t){if(!Of(e))return null;try{let n=O.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var hE=40,If=40,yE=10,RE=8;async function ya(e){return J(e.queries||[],async t=>ke({toolName:Ie,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await AE(t);return bE(SE(t,n))}}),{toolName:Ie,minQueryTimeoutMs:3e4},e)}function bE(e){return U(e,N(e))}function SE(e,t){return e.format!=="compact"||!CE(t)?t:PE(t)}function CE(e){return Zt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Zt(e.payload)}function PE(e){return{...e,format:"compact",payload:EE(e.payload)}}function EE(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Tf)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(xE)}:{locations:(e.locations??[]).map(Tf)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:kf(e.root)}:{},direction:e.direction,calls:e.calls.map(_E),...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(TE)};case"hover":case"empty":return e}}function TE(e){if(!Zt(e))return String(e);let t=Fe(e,"line"),n=Fe(e,"character"),r=Fe(e,"endLine"),o=yt(e,"kind"),i=yt(e,"name"),s=Fe(e,"childCount"),a=yt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Tf(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Ff(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function xE(e){if(!Zt(e))return String(e);let t=yt(e,"uri"),n=Fe(e,"firstLine"),r=Fe(e,"firstCharacter"),o=Fe(e,"count"),i=vf(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 _E(e){if(!Zt(e))return String(e);let t=yt(e,"direction"),n=kf(e.item),r=vf(e,"ranges").map(wE).join(","),o=Fe(e,"rangeCount"),i=Fe(e,"rangeSampleCount"),s=yt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Ff(s,180)}`:""].filter(Boolean).join(" ")}function kf(e){if(!Zt(e))return String(e);let t=yt(e,"name"),n=yt(e,"kind"),r=yt(e,"uri"),o=Fe(e,"line"),i=Fe(e,"endLine"),s=Fe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function wE(e){return Zt(e)?`${Fe(e,"line")}:${Fe(e,"character")}`:String(e)}function Zt(e){return typeof e=="object"&&e!==null}function yt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Fe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function vf(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ff(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function AE(e){if(e.type==="documentSymbols")return LE(e);let t=await Ef(e,Ie);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return BE(e,i)}let n=e.workspaceRoot??await Lf(t.value.uri);if(!await Af(t.value.uri,n)){if(e.type==="references"){let i=IE(e,t.value);if(i)return i}return ht(e.type,t.value,"Language server unavailable")}let o=await wf(n,t.value.uri);if(!o)return ht(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?ga(e,t.value,"definition","definitionProvider",await mE({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):ht(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?ga(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ht(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?ga(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ht(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?Mf(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):ht(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?kE(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ht(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?vE(e,t.value,o):ht(e.type,t.value,"callHierarchyProvider unsupported",!0)}}async function LE(e){let t=await fa(e,Ie);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Lf(t.value.uri),r=await Af(t.value.uri,n),o=r?await wf(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a;if(i&&o){let h=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(h)?h:[],a="lsp"}else{let h=gE(t.value.uri,t.value.content);h&&(s=h,a="native")}let c=a!==void 0,u=FE(s),l=DE(s),{pageItems:d,pagination:m}=ii(u,e.page??1,e.itemsPerPage??hE),p=HE(u,h=>h.kind),g=c?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(c?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable; native outline supports JS/TS only")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:d.length,topLevelSymbols:l,kinds:p},payload:{kind:"documentSymbols",symbols:d,...g?{empty:g}:{}},pagination:m}}function ga(e,t,n,r,o){let i=o.length>0,s=o.map(Xi),{pageItems:a,pagination:c}=ii(s,e.page??1,e.itemsPerPage??If);return{type:e.type,uri:t.uri,resolvedSymbol:bn(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}:{}}}var OE={kind:"lsp"};function Mf(e,t,n,r=OE){let o=r.kind==="native",i=n.map(d=>{let m=d.uri===t.uri&&d.range.start.line===t.resolvedSymbol.position.line&&d.range.start.character===t.resolvedSymbol.position.character;return{...d,...m?{isDefinition:!0}:{}}}),s=e.groupByFile?zE(i):void 0,a=s??i.map(Xi),{pageItems:c,pagination:u}=ii(a,e.page??1,e.itemsPerPage??If),l=i.length===0?{category:"noReferences",reason:o?"no in-file references found":"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:o?{serverAvailable:!1,source:"native"}:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...s?{byFile:c}:{locations:c},totalReferences:i.length,totalFiles:new Set(i.map(d=>d.uri)).size,...l?{empty:l}:{}},pagination:u,...l&&o?{warnings:["source: native (oxc) \u2014 same-file references only; install a language server for cross-file references."]}:{}}}function IE(e,t){if(!Of(t.uri))return null;let n;try{let i=O.findInFileReferences(t.content,t.uri,t.resolvedSymbol.position.line,t.resolvedSymbol.position.character);if(!i)return null;let s=JSON.parse(i);if(!Array.isArray(s))return null;n=s}catch{return null}let r=t.content.split(`
|
|
55
|
+
`),o=n.map(i=>({uri:t.uri,range:i,content:(r[i.start.line]??"").trim()}));return Mf(e,t,o,{kind:"native",scope:"file"})}async function kE(e,t,n){let r=QE(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function vE(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return ht(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await da(n,o,i,new Set([Or(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await pa(n,o,i,new Set([Or(o)]),e.contextLines??0):s,u=b=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(b.to.uri),l=c.calls.filter(u).length,d=c.calls.filter(b=>!u(b)),m=[...a.calls.map(b=>({direction:"incoming",...b})),...d.map(b=>({direction:"outgoing",...b}))],p=m.map(b=>b.direction==="incoming"?GE(b,e.contextLines??0):UE(b,e.contextLines??0)),{pageItems:f,pagination:g}=ii(p,e.page??1,e.itemsPerPage??yE),h=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",R=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Ra(o),direction:h,calls:f,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:R,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}function ii(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function FE(e){let t=[];for(let n of e)Nf(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Nf(e,t,n){if(!e||typeof e!="object")return;let r=e,o=NE(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:ha(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)&&ME.has(ha(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Nf(s,t,i)}}var ME=new Set(["file","module","namespace","package","class","enum","interface","struct"]);function NE(e){if(xf(e.range))return e.range;let t=e.location;return t&&xf(t.range)?t.range:void 0}function xf(e){if(!e||typeof e!="object")return!1;let t=e;return _f(t.start)&&_f(t.end)}function _f(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function DE(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function HE(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function GE(e,t){let n=Df(e.fromRanges);return{direction:"incoming",item:Ra(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Hf(e.from,t)}}function UE(e,t){let n=Df(e.fromRanges);return{direction:"outgoing",item:Ra(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Hf(e.to,t)}}function Ra(e){return{name:e.name,kind:ha(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 Df(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>=RE))break}return n}function Hf(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function ha(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function Gf(e,t){return/unavailable/i.test(t)?"serverUnavailable":/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function BE(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Gf(e.type,t),reason:t}}}function ht(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Gf(e,n),reason:n}}}function zE(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 QE(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=>jE(r)).join(`
|
|
56
|
+
`).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 jE(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{z as y}from"zod";import{LspGetSemanticsQuerySchema as zf}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as $E}from"@octocodeai/octocode-core/schemas/outputs";var VE=v(1,1e9),WE=v(0,1e5).optional(),KE=["structured","compact"],Qf={type:y.enum(mu).default("definition"),symbolName:y.string().min(1).optional(),lineHint:VE.optional(),orderHint:WE,depth:v(0,20).optional(),includeDeclaration:y.boolean().optional().default(!0),page:q,itemsPerPage:v(1,100).optional(),contextLines:v(0,100).optional(),format:y.enum(KE).optional().default("structured")},YE=ce(zf,Qf),Sa=re(zf,Qf),XE=Sa,Ca=X(YE,{maxQueries:5}),Uf=y.object({line:y.number(),character:y.number()}),JE=y.object({start:Uf,end:Uf}),ZE=y.object({startLine:y.number(),endLine:y.number()}),si=y.object({uri:y.string(),content:y.string().optional(),displayRange:ZE.optional(),isDefinition:y.boolean().optional()}),ai=y.string(),qE=y.object({name:y.string(),uri:y.string(),foundAtLine:y.number(),orderHint:y.number().optional()}),eT=y.object({serverAvailable:y.boolean().optional(),provider:y.string().optional(),source:y.string().optional()}),jf=y.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls"]),ba=y.object({category:jf,reason:y.string()}),tT=y.object({currentPage:y.number(),totalPages:y.number(),totalResults:y.number(),hasMore:y.boolean(),itemsPerPage:y.number(),nextPage:y.number().optional()}),nT=y.object({name:y.string(),kind:y.string(),line:y.number(),character:y.number(),endLine:y.number(),childCount:y.number(),containerName:y.string().optional()}),rT=y.string(),$f=y.object({name:y.string(),kind:y.string(),uri:y.string(),line:y.number(),endLine:y.number(),selectionLine:y.number().optional()}),oT=y.string(),iT=y.object({direction:y.enum(["incoming","outgoing"]),item:$f,ranges:y.array(y.object({line:y.number(),character:y.number()})),rangeCount:y.number(),rangeSampleCount:y.number(),contentPreview:y.string().optional()}),sT=y.string(),aT=y.object({complete:y.boolean(),truncatedByDepth:y.boolean(),cycleCount:y.number(),failedRequestCount:y.number(),dynamicCallsExcluded:y.literal(!0),stdlibCallsExcluded:y.number().optional()}),cT=y.object({uri:y.string(),count:y.number(),firstLine:y.number(),firstCharacter:y.number(),lines:y.array(y.number()),hasDefinition:y.boolean().optional()}),uT=y.string(),lT=y.discriminatedUnion("kind",[y.object({kind:y.literal("definition"),locations:y.array(y.union([si,ai]))}),y.object({kind:y.literal("typeDefinition"),locations:y.array(y.union([si,ai]))}),y.object({kind:y.literal("implementation"),locations:y.array(y.union([si,ai]))}),y.object({kind:y.literal("references"),locations:y.array(y.union([si,ai])).optional(),byFile:y.array(y.union([cT,uT])).optional(),totalReferences:y.number(),totalFiles:y.number(),empty:ba.optional()}),...["callers","callees","callHierarchy"].map(e=>y.object({kind:y.literal(e),root:y.union([$f,oT]).optional(),direction:y.enum(["incoming","outgoing","both"]),calls:y.array(y.union([iT,sT])),incomingCalls:y.number(),outgoingCalls:y.number(),completeness:aT,empty:ba.optional()})),y.object({kind:y.literal("hover"),markdown:y.string().optional(),text:y.string().optional(),range:JE.optional()}),y.object({kind:y.literal("documentSymbols"),symbols:y.array(y.union([nT,rT])),totalSymbols:y.number().optional(),topLevelSymbols:y.number().optional(),empty:ba.optional()}),y.object({kind:y.literal("empty"),category:jf,reason:y.string()})]),Bf=y.object({type:y.string(),uri:y.string(),format:y.enum(["structured","compact"]).optional(),resolvedSymbol:qE.optional(),lsp:eT,payload:lT,pagination:tT.optional(),summary:y.record(y.string(),y.unknown()).optional(),warnings:y.array(y.string()).optional()}),dT=y.object({base:y.string().optional(),shared:y.record(y.string(),y.union([y.string(),y.number(),y.boolean()])).optional(),results:y.array(y.union([y.object({id:y.string().min(1),status:y.literal("empty"),data:Bf}),y.object({id:y.string().min(1),status:y.literal("error"),data:$E}),y.object({id:y.string().min(1),data:Bf})]))});import{existsSync as Vf}from"fs";import{delimiter as pT,dirname as fT,join as Wf}from"path";function Kf(){return process.platform==="win32"?"npm.cmd":"npm"}function mT(){let e=fT(process.execPath);return Wf(e,Kf())}function gT(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function hT(){let e=(process.env.PATH??"").split(pT).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...gT()])]}function Yf(){let e=mT();if(Vf(e))return{command:process.execPath,argsPrefix:[e]};let t=Kf();for(let n of hT()){let r=Wf(n,t);if(Vf(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var yT=["view","search","ping","config","whoami"],RT=[..._r,...Jl];async function eG(e=1e4){let t=Yf();return Zl(t.command,[...t.argsPrefix,"--version"],e)}async function Ir(e,t,n={}){if(!yT.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Bo(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=Yf(),c=await Xt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:RT});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var nG=5;var Fn=new Map,Ea=5,kr=3e4;function vr(e){try{return new URL(e).host||e}catch{return e}}var Pa=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 Xf(e,t=Date.now()){let n=Fn.get(vr(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<kr)throw new Pa(vr(e),kr-r);n.state="half-open"}}function Ta(e){let t=Fn.get(vr(e));t&&(t.failures=0,t.state="closed")}function Jf(e,t=Date.now()){let n=vr(e),r=Fn.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=Ea&&(r.state="open",r.openedAt=t)),Fn.set(n,r)}function rG(){Fn.clear(),Ea=5,kr=3e4}function oG(e){typeof e.failureThreshold=="number"&&(Ea=e.failureThreshold),typeof e.cooldownMs=="number"&&(kr=e.cooldownMs)}function Zf(e,t=Date.now()){let n=Fn.get(vr(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<kr:!1}var bT=6e4;function qf(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function ST(e,t,n,r){e&&Lt({limit_type:"primary",retry_after_seconds:qf(r),api_method:t,api_url:n,provider:e}).catch(xe("fetch rate-limit session logging"))}function CT(e,t,n,r,o){e.body?.cancel?.().catch(xe("response body cancellation")),M("fetchWithRetries",St.FETCH_HTTP_ERROR.code).catch(xe("fetch retry session logging"));let i=new Error(St.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&gu(r),e.status===429&&ST(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function PT(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=qf(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function vt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=bT,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:u,packageRegistry:l}=t,d=e;if(a){let h=e.includes("?")?"&":"?";d=`${e}${h}version=${encodeURIComponent(ft)}`}let m={"User-Agent":`Octocode-MCP/${ft}`,...i},p=globalThis.fetch;if(!p)throw M("fetchWithRetries",St.FETCH_NOT_AVAILABLE.code).catch(xe("fetch retry session logging")),new Error(St.FETCH_NOT_AVAILABLE.message);Xf(d);let f,g=n+1;for(let h=1;h<=g;h++){if(c?.aborted)throw new Error("Request aborted");try{let R=await p(d,{method:s,headers:m,signal:c});if(!R.ok)throw CT(R,s,d,l,u);if(R.status===204)return Ta(d),null;let b=await R.json();return Ta(d),b}catch(R){let b=R;if(c?.aborted||R instanceof Error&&R.name==="AbortError")throw new Error("Request aborted");if(b&&b.retryable===!1)throw R;if(f=R instanceof Error?R:new Error(String(R)),h===g)break;let P=PT(h,r,o,b);await new Promise(x=>setTimeout(x,P))}}throw Jf(d),await M("fetchWithRetries",St.FETCH_FAILED_AFTER_RETRIES.code),new Error(St.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}import{z as T}from"zod";var ci=T.looseObject({name:T.string(),version:T.string(),repository:T.union([T.string(),T.object({url:T.string().optional(),type:T.string().optional(),directory:T.string().optional()})]).optional(),main:T.string().optional(),module:T.string().optional(),type:T.string().optional(),exports:T.unknown().optional(),types:T.string().optional(),typings:T.string().optional(),description:T.string().optional(),keywords:T.array(T.string()).optional(),license:T.union([T.string(),T.object({type:T.string().optional()})]).optional(),homepage:T.string().optional(),author:T.union([T.string(),T.object({name:T.string().optional(),email:T.string().optional(),url:T.string().optional()})]).optional(),maintainers:T.array(T.object({name:T.string().optional(),email:T.string().optional()})).optional(),engines:T.record(T.string(),T.string()).optional(),dependencies:T.record(T.string(),T.string()).optional(),devDependencies:T.record(T.string(),T.string()).optional(),peerDependencies:T.record(T.string(),T.string()).optional(),time:T.record(T.string(),T.string().optional()).optional()}),ET=T.looseObject({package:T.looseObject({name:T.string().nullish(),version:T.string().nullish(),description:T.string().nullish(),links:T.looseObject({npm:T.string().nullish(),homepage:T.string().nullish(),repository:T.string().nullish()}).nullish()}),score:T.looseObject({final:T.number().nullish(),detail:T.looseObject({quality:T.number().nullish(),popularity:T.number().nullish(),maintenance:T.number().nullish()}).nullish()}).nullish()}),em=T.looseObject({objects:T.array(ET),total:T.union([T.number(),T.string()]).optional()}),tm=T.union([T.string(),T.boolean(),T.number(),T.null(),T.record(T.string(),T.unknown())]);var ui="https://registry.npmjs.org",TT=3e3,Fr=null;async function xa(){if(Fr)return Fr;try{let e=await Ir("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 Fr=t,t}}catch{}return Fr=ui,ui}function SG(){Fr=null}async function CG(){try{let e=await xa(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}function qt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var xT="https://api.npmjs.org/downloads/point/last-week";function Ue(e){return e===void 0?0:N(e)}async function am(e){try{let t=`${xT}/${encodeURIComponent(e)}`,n=await vt(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:Ue(n)}}catch{return{rawResponseChars:0}}}function li(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function cm(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function _T(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function wT(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function nm(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function rm(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function AT(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function _a(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=qt(e.repository):(e.repository.url&&(r=qt(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:AT(e),...o?{repositoryDirectory:o}:{},...nm(e.exports)?{exports:nm(e.exports)}:{},...rm(e.bin,e.name)?{bin:rm(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function LT(e){return typeof e.links?.repository=="string"?qt(e.links.repository):typeof e.repository=="string"?qt(e.repository):typeof e.repository?.url=="string"?qt(e.repository.url):null}function OT(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:LT(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 um(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function lm(e){try{let t=await xa(),n=um(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await vt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ue(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await vt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ue(i)}}catch{return{rawResponseChars:0}}}async function wa(e,t,n){let[r,o]=await Promise.all([am(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):lm(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 di(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function IT(e,t){try{let n=await Ir("view",[e,"--json"],{timeout:TT});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,...di(c)?{}:{errorDetail:c},rawResponseChars:Ue(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=Ue(o),s=ci.safeParse(o);return s.success?{pkg:_a(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,...di(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function kT(e,t){try{let n=await xa(),r=um(e),o=`${n}/${r}/latest`,i;try{i=await vt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(u){let l=u instanceof Error?u.message:String(u);return l.includes("404")||l.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:l,rawResponseChars:0}}let s=Ue(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=ci.safeParse(i);return a.success?{pkg:_a(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,...di(r)?{}:{errorDetail:r},rawResponseChars:0}}}function vT(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function dm(e,t){let n=0,r;for(let o of vT(e)){let i;try{i=await vt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);di(u)||(r=u);continue}if(n+=Ue(i),!i||typeof i!="object")continue;let s=ci.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:_a(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Aa(e,t=!1){let[n,r]=await Promise.allSettled([IT(e,t),kT(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?wa(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function FT(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Aa(e,t);if(!r){if(o){let s=cm(o);if(s&&n){let a=await dm(e,t);if(a.pkg){let c=await wa(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function MT(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ir("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:Ue(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=Ue(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let l=[...a].sort((f,g)=>{let h=f?.score?.final??0;return(g?.score?.final??0)-h}).slice(r,r+t),d=await Promise.all(l.map(async f=>{if(!f||typeof f!="object")return null;let g=f;if(!g.name)return null;if(n){let h=await Aa(g.name,!0);if(h.pkg)return h}return{pkg:OT(g),rawResponseChars:0}})),m=d.map(f=>f?.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function NT(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${ui}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await vt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`NPM registry search failed: ${f instanceof Error?f.message:String(f)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ue(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=em.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let l=[...c.data.objects].sort((f,g)=>{let h=f.score?.final??0;return(g.score?.final??0)-h}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),d=await Promise.all(l.map(async f=>{if(n){let g=await Aa(f.name,!0);if(g.pkg)return g}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"?qt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=d.map(f=>f.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+g.rawResponseChars,0);return{packages:m,totalFound:wT(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function om(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 vt(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:Ue(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ue(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"?qt(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:Ue(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function im(e,t,n,r=0){try{let o=await MT(e,t,n,r);if(!("error"in o))return o}catch{}return NT(e,t,n,r)}async function sm(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}):am(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):lm(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function pm(e,t,n,r=0){let o=_e("npm-search",{name:e,limit:t,metadata:n,from:r});return we(o,async()=>{if(Zf(ui)){if(r===0&&t===1&&li(e)){let l=await dm(e,n);if(l.pkg){let d=await wa(e,l.pkg,l.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let u=await om(e,t);return!("error"in u)&&u.packages.length>0?u:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&li(e)){let u=await FT(e,n,t===1);if("error"in u){if(!cm(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await im(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return sm(s);let a=_T(e);if(a!==e){let u=await im(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return sm(u)}let c=await om(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function DT(e){try{let t=await Ir("view",[e,"deprecated","--json"]);if(t.error||t.exitCode!==0)return null;let n=t.stdout.trim();if(!n||n==="undefined"||n==="")return{deprecated:!1};try{let r=JSON.parse(n),o=tm.safeParse(r),i=o.success?o.data:n;return{deprecated:!0,message:typeof i=="string"?i:"This package is deprecated"}}catch{return{deprecated:!0,message:n}}}catch{return null}}async function fm(e){let t=li(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return pm(e.name,n,!0,r)}function HT(e){return"error"in e}function pi(e){return"npmUrl"in e}function GT(e){return pi(e)&&e.path?e.path:e.name}function UT(e){return pi(e)?e.repoUrl:e.repository}function BT(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function zT(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function QT(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 jT(e,t){let n=QT(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function $T(e){let t=GT(e),n=zT(UT(e)),r={name:t};pi(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=BT(pi(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=jT(n,o);return i&&(r.next=i),r}function VT(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=Math.max(1,Math.ceil(t/i)),a=o<s;return{currentPage:o,totalPages:s,perPage:i,totalFound:t,returned:n,hasMore:a,...a?{nextPage:o+1}:{}}}async function mm(e){return J(e.queries,async t=>{try{if(!t.packageName)return L("Package name is required for package search",t);let n=await fm({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(HT(n))return L(n.error,t,{rawResponse:n});let r=n.packages,o=r.map($T),i=o.length>0,s=r.length>1||n.totalFound>1,a=VT(t,n.totalFound,o.length,s);return Pe(t,{packages:o,pagination:a},i,S.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return L(n,t,{toolName:S.PACKAGE_SEARCH})}},{toolName:S.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{z as Y}from"zod";import{NpmPackageQuerySchema as gm}from"@octocodeai/octocode-core/schemas";var hm={page:q,mode:Y.enum(["lean","full"]).optional()},ym=re(gm,hm),Rm=X(ce(gm,hm,{strict:!0}),{maxQueries:5}),MG=Y.object({results:Y.array(Y.looseObject({id:Y.string(),data:Y.looseObject({packages:Y.array(Y.object({name:Y.string(),version:Y.string().optional(),description:Y.string().optional(),license:Y.string().optional(),downloads:Y.number().optional(),repository:Y.string().optional(),repositoryDirectory:Y.string().optional(),next:Y.record(Y.string(),Y.unknown()).optional()}).passthrough()).optional(),pagination:Y.object({currentPage:Y.number(),totalPages:Y.number(),perPage:Y.number(),totalFound:Y.number(),returned:Y.number(),hasMore:Y.boolean(),nextPage:Y.number().optional()}).optional()}).optional(),status:Y.string().optional()})).optional()}).extend(Ae);var La={hasTool(e){return ds(e)},getDescription(e){return ls[e]??""},getToolName(e){return S[e]??String(e)}};var bm=(e,t=La)=>t.getDescription(e);function WT(e,t){return t.getToolName(e)}function We(e,t,n){let r=WT(t,e);return{...n,name:r,description:bm(r,e)}}function KT(e=La){let t=We(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:zd,inputSchema:Qd,executionFn:Gd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=We(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:jo,inputSchema:Pd,executionFn:Dd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=We(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:pp,inputSchema:fp,executionFn:up,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=We(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ap,inputSchema:cp,executionFn:op,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=We(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Jo,inputSchema:Jd,executionFn:Zd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=We(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ym,inputSchema:Rm,executionFn:mm,security:"remote",requiresServerRuntime:!0}}),a=We(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Bs,inputSchema:bd,executionFn:gd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=We(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:vn,inputSchema:Vp,executionFn:cf,security:"basic"}}),u=We(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:oi,inputSchema:df,executionFn:bf,security:"basic"}}),l=We(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:ti,inputSchema:Up,executionFn:Qp,security:"basic"}}),d=We(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:ei,inputSchema:Np,executionFn:Dp,security:"basic"}}),m={name:Ie,description:bm(Ie,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Sa,inputSchema:Ca,executionFn:ya,security:"basic",requiresServerRuntime:!0}},p=We(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Zo,inputSchema:hp,executionFn:Op,security:"basic"}});return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:u,LOCAL_FIND_FILES:l,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,LOCAL_BINARY_INSPECT:p,ALL_TOOLS:[t,n,r,o,i,s,a,c,u,l,d,m,p]}}var Me=KT(),fU=Me.GITHUB_SEARCH_CODE,mU=Me.GITHUB_FETCH_CONTENT,gU=Me.GITHUB_VIEW_REPO_STRUCTURE,hU=Me.GITHUB_SEARCH_REPOSITORIES,yU=Me.GITHUB_SEARCH_PULL_REQUESTS,RU=Me.PACKAGE_SEARCH,bU=Me.GITHUB_CLONE_REPO,SU=Me.LOCAL_RIPGREP,CU=Me.LOCAL_VIEW_STRUCTURE,PU=Me.LOCAL_FIND_FILES,EU=Me.LOCAL_FETCH_CONTENT,TU=Me.LSP_GET_SEMANTIC_CONTENT,xU=Me.LOCAL_BINARY_INSPECT,Sm=Me.ALL_TOOLS;import{completeMetadata as YT}from"@octocodeai/octocode-core";var Mr=null;function Cm(){return Mr||(Mr=YT),Mr}async function AU(){return Cm()}async function LU(){Cm()}function OU(){return Mr}function IU(){Mr=null}import{z as Fa}from"zod";import{ContentSanitizer as XT}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as Pm}from"@octocodeai/octocode-engine/mask";function Oa(e){let t=e;if(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let r=XT.sanitizeContent(n.text),o=r.hasSecrets?Pm(r.content):Pm(n.text);return{...n,text:o}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:ot(t.structuredContent)}}catch{}return t}var JT="TOOL_CALLBACK_EXCEPTION";function Ia(e,t){let n=ZT(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
57
|
+
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:JT,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Oa(r)}catch{return r}}function ZT(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:qT(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 qT(e){try{return JSON.stringify(e)}catch{return}}import{releaseAllPooledClients as ex}from"@octocodeai/octocode-engine/lsp/manager";var Em=["GitHub","Local","LSP","Package","Other"],Tm=new Map([ge.GITHUB_SEARCH_CODE,ge.GITHUB_SEARCH_REPOSITORIES,ge.GITHUB_SEARCH_PULL_REQUESTS,ge.GITHUB_FETCH_CONTENT,ge.GITHUB_VIEW_REPO_STRUCTURE,ge.GITHUB_CLONE_REPO,ge.LOCAL_RIPGREP,ge.LOCAL_FIND_FILES,ge.LOCAL_FETCH_CONTENT,ge.LOCAL_VIEW_STRUCTURE,Ie,ge.PACKAGE_SEARCH].map((e,t)=>[e,t])),Rt=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},ka=null,va=null,tx=["id","mainResearchGoal","researchGoal","reasoning"],Da=new Set([...tx]),nx=["id","researchGoal","reasoning"],xm=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function rx(e){return async t=>e(t)}function ox(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:rx(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var _m=Sm.map(ox),WU=_m.map(Om);function wm(e){let t=Ha(e);return t?Om(t):void 0}function fi(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")?"Local":e.startsWith("lsp")?"LSP":e===ge.PACKAGE_SEARCH?"Package":"Other"}function KU(e){return[...e].sort((t,n)=>{let r=Em.indexOf(fi(t)),o=Em.indexOf(fi(n));if(r!==o)return r-o;let i=Tm.get(t)??Number.MAX_SAFE_INTEGER,s=Tm.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function YU(e){let t=wm(e);if(!t)return"{}";try{return JSON.stringify(Fa.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(Fa.toJSONSchema(t.schema),null,2)}}function XU(e){return JSON.stringify(e??{},null,2)}function JU(e){let t=fi(e),n=[...nx];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function ZU(){return xm.map(e=>({...e}))}function qU(){return JSON.stringify(Object.fromEntries(xm.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function eB(e,t){return t?.tools?.[e]?.description??e}function Am(e){let t=wm(e);if(!t)return[];let n=Fa.toJSONSchema(t.schema);if(!Nr(n))return[];let r=Ft(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Da.has(i)&&!Na(r[i])):[]);return Ma(r,o)}function tB(e){let t=Am(e),n=t.filter(i=>i.required),r=n.length>0?n:t.slice(0,4),o={};for(let i of r)o[i.name]=px(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Ie&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function nB(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Rt("Tool input must be valid JSON.")}return ix(e,r,n)}function ix(e,t,n={}){let r=ax(e,t,n),o=Ha(e);if(!o)throw new Rt(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Rt("Tool input does not match the expected schema.",sx(i.error));return i.data}function sx(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function ax(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(Ft(t)&&Array.isArray(t.queries))r=t.queries;else if(Ft(t))r=[t];else throw new Rt('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Rt("At least one query is required.");let o=Ft(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,u)=>{i=!0,n.onUnknownFields?.(c,u)}},a=r.map((c,u)=>cx(e,u,lx(e,c,u,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new Rt("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function cx(e,t,n,r){let o={...n},i=fi(e),s=r.sourceLabel??"direct tool execution",a=ux(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function ux(e,t){return`Execute ${e} via ${t}`}function lx(e,t,n,r={}){if(!Ft(t))throw new Rt("Tool input must be a JSON object or an array of objects.");let o=new Set([...Am(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Da]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function dx(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 Lm(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let t=Nr(e.items)?e.items:void 0;return`array<${t?Lm(t):"value"}>`}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Ma(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Da.has(o))continue;let s=Nr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Lm(s),constraints:dx(s),description:typeof s.description=="string"?s.description:void 0}),Ft(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!Na(s.properties?.[l]):!1):[]);r.push(...Ma(s.properties,u,a))}let c=s.type==="array"&&Nr(s.items)?s.items:void 0;if(c&&Ft(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!Na(c.properties?.[l]):!1):[]);r.push(...Ma(c.properties,u,a))}}return r}function px(e,t){if(t.startsWith("array<"))return[e];if(t==="integer"||t==="number")return 1;if(t==="boolean")return!0;if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;switch(e){case"path":return".";case"owner":return"bgauryy";case"repo":return"octocode";case"name":case"packageName":return"react";default:return e}}function Ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nr(e){return Ft(e)}function Na(e){return Nr(e)&&"default"in e}async function rB(e,t){let n=Ha(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=fx(n,t);return await mx(n),gx(n),await hx(n,r)}catch(r){return Ia(n.name,r)}finally{e===Ie&&await ex()}}function Om(e){return{name:e.name,schema:e.schema,inputSchema:e.inputSchema}}function Ha(e){return _m.find(t=>t.name===e)}function fx(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function mx(e){e.requiresServerRuntime&&(ka||(ka=du()),await ka),e.requiresProviders&&(va||(va=Yl().then(()=>{})),await va)}function gx(e){if(!e.isLocal&&!e.isClone)return;let t=ae();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.enabled&&t.local.enableClone)){let n=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true and ENABLE_LOCAL=true to use it.`);throw n.code="cloneDisabled",n}}async function hx(e,t){try{let n=e.security==="remote"?await yx(e,t):await Rx(e,t);return Oa(n)}catch(n){return Ia(e.name,n)}}async function yx(e,t){return Qa(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function Rx(e,t){return ja(e.execute,e.name)(t)}function sB(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function aB(){try{return ae().local.enabled}catch{return!1}}function cB(){try{if(!ae().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}function pB(e,t){let n=Ce(),r=t.maxOutputChars??n,o=t.recommendedCharLength??n,i=[];if(t.charLength!==void 0||t.charOffset!==void 0){let s=t.charLength??o,a=t.charOffset??0,c=mt(e,a,s),u=br(c);return{content:c.paginatedContent,wasLimited:!0,pagination:u,warnings:i,paginationHints:Im(u)}}if(e.length>r){i.push(`Auto-paginated: Output (${e.length} chars) exceeds ${r} char limit. Use charOffset/charLength to navigate.`);let s=mt(e,0,o),a=br(s);return{content:s.paginatedContent,wasLimited:!0,pagination:a,warnings:i,paginationHints:Im(a)}}return{content:e,wasLimited:!1,warnings:i,paginationHints:[]}}function Im(e){let t=[];if(e.hasMore){let n=(e.charOffset??0)+(e.charLength??0),r=(e.charOffset??0)+1,o=n;t.push(`Page ${e.currentPage}/${e.totalPages} (chars ${r}-${o} of ${e.totalChars}). Next: charOffset=${n}`)}return t}function gB(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=O.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={matchCount:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}import{z as F}from"zod";var mi=F.object({text:F.string()}),bx=F.object({match:F.object({text:F.string()}).optional(),start:F.number(),end:F.number()}),Sx=F.object({type:F.literal("match"),data:F.object({path:mi,lines:F.object({text:F.string()}),line_number:F.number(),absolute_offset:F.number(),submatches:F.array(bx)})}),Cx=F.object({type:F.literal("context"),data:F.object({path:mi,lines:F.object({text:F.string()}),line_number:F.number(),absolute_offset:F.number()})}),Px=F.object({type:F.literal("begin"),data:F.object({path:mi})}),Ex=F.object({type:F.literal("end"),data:F.object({path:mi,stats:F.object({elapsed:F.object({human:F.string()}),searches:F.number(),searches_with_match:F.number()}).optional()})}),Tx=F.object({type:F.literal("summary"),data:F.object({elapsed_total:F.object({human:F.string()}),stats:F.object({elapsed:F.object({human:F.string()}),searches:F.number(),searches_with_match:F.number(),bytes_searched:F.number(),bytes_printed:F.number(),matched_lines:F.number(),matches:F.number()})})}),RB=F.discriminatedUnion("type",[Sx,Cx,Px,Ex,Tx]);var xx=1e5,Ga=new Set(["hints","warnings","pagination","outputPagination"]);function km(){return Math.min(Math.max(Ce(),1),xx)}function vm(e,t=km()){return{offset:e.offset??0,length:Math.max(e.length??t,1),explicit:e.offset!==void 0||e.length!==void 0}}function ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Ne(e){return JSON.stringify(e)}function Fm(e,t,n,r){let o=Math.max(r,1),i=Math.max(n,0),s=Math.max(1,Math.ceil(i/o)),a=i===0?0:Math.max(i-1,0),c=Math.min(Math.max(e,0),a),u=i===0?1:Math.min(s,Math.floor(c/o)+1),l=e+t<i;return{currentPage:u,totalPages:l?Math.max(s,u+1):u,hasMore:l,charOffset:e,charLength:t,totalChars:i}}function _x(e,t){let n={...e};delete n.outputPagination;for(let s of t)s.kind==="array"&&Array.isArray(n[s.field])&&(n[s.field]=[]),s.kind==="record"&&ye(n[s.field])&&(n[s.field]={});let r=Ne(n).length,o=[],i=r;for(let s of t){let a=e[s.field];if(s.kind==="array"&&Array.isArray(a)&&a.length>0){let c=!0;for(let u of a){let l=Ne(u),d=`${c?"":","}${l}`.length;o.push({field:s.field,kind:"array",value:u,start:i,end:i+d,itemPaginator:s.itemPaginator}),i+=d,c=!1}continue}if(s.kind==="record"&&ye(a)){let c=!0;for(let[u,l]of Object.entries(a)){let d=Ne(l),m=`${c?"":","}${Ne(u)}:${d}`.length;o.push({field:s.field,kind:"record",key:u,value:l,start:i,end:i+m,itemPaginator:s.itemPaginator}),i+=m,c=!1}}}return{baseObject:n,baseChars:r,segments:o,totalChars:i}}function wx(e,t){let n={...e};for(let r of t){if(r.kind==="array"){let i=Array.isArray(n[r.field])?[...n[r.field]]:[];i.push(r.value),n[r.field]=i;continue}let o=ye(n[r.field])?{...n[r.field]}:{};r.key!==void 0&&(o[r.key]=r.value),n[r.field]=o}return n}function Ax(e,t,n,r){let o=n.findIndex(c=>c.end>r.offset);if(o===-1)return{selectedSegments:[],actualOffset:r.offset,pageEnd:r.offset};let i=[],s,a=0;for(let c=o;c<n.length;c+=1){let u=n[c],l=c===o?Math.max(0,r.offset-u.start):0,d=s===void 0?0:a-s,m=Math.max(r.length-d,1),p=u.end-u.start;if(l===0&&p<=m){s===void 0&&(s=r.offset<e?0:u.start),i.push(u),a=u.end;continue}if(u.itemPaginator){let f=u.itemPaginator(u.value,{offset:l,length:m,explicit:!0});if(f){s===void 0&&(s=r.offset<e?0:u.start+f.actualOffset),i.push({...u,value:f.value}),a=u.start+f.pageEnd;let g=f.pageEnd>=f.totalChars,h=a-s<r.length;if(g&&h)continue;break}}s===void 0&&(s=r.offset<e?0:u.start),i.push(u),a=u.end;break}return s===void 0&&(s=r.offset<e?0:Math.min(r.offset,t),a=Math.min(t,Math.max(e,s))),{selectedSegments:i,actualOffset:s,pageEnd:a}}function Ua(e,t,n,r,o=!0){return!o||!e.explicit&&t<=e.length?{value:n,actualOffset:0,pageEnd:t,totalChars:t,paginated:!1}:e.offset>=t?{value:r,actualOffset:e.offset,pageEnd:e.offset,totalChars:t,paginated:!0}:null}function Ke(e,t,n){let r=Ne(e).length;if(n.length===0)return{value:e,actualOffset:0,pageEnd:r,totalChars:r,paginated:!1};let{baseObject:o,baseChars:i,segments:s,totalChars:a}=_x(e,n),c=Ua(t,a,e,o,s.length>0);if(c)return c;let u=Ax(i,a,s,t);return{value:wx(o,u.selectedSegments),actualOffset:u.actualOffset,pageEnd:u.pageEnd,totalChars:a,paginated:!0}}function Ba(e,t){let n=Array.from(e),r=n.map(f=>Math.max(JSON.stringify(f).length-2,0)),i=2+r.reduce((f,g)=>f+g,0),s=Ua(t,i,e,"");if(s)return s;let a=0,c=0;if(t.offset>1){let f=1,g=!1;for(let h=0;h<r.length;h+=1){let R=r[h];if(f+R>t.offset){a=h,c=f,g=!0;break}f+=R}if(!g)return{value:"",actualOffset:t.offset,pageEnd:t.offset,totalChars:i,paginated:!0}}let u=Math.max(1,t.length-(a===0?1:0)-1),l=0,d=a;for(;d<n.length;){let f=r[d];if(l+f>u&&d>a||(l+=f,d+=1,l>=u))break}d===a&&d<n.length&&(l+=r[d],d+=1);let m=a===0?0:c,p=l+(a===0?1:0)+(d===n.length?1:0);return{value:n.slice(a,d).join(""),actualOffset:m,pageEnd:Math.min(i,m+Math.max(p,1)),totalChars:i,paginated:!0}}function Mm(e,t,n,r,o){let i={...e,[t]:r};delete i.outputPagination;let s=Math.max(Ne(i).length-2,0),a=o(e[t],{offset:n.offset<=s?0:n.offset-s,length:n.offset<=s?Math.max(1,n.length-s):n.length,explicit:!0}),c=s+a.totalChars,u=Ua(n,c,e,i);return u||{value:{...i,[t]:a.value},actualOffset:n.offset<=s?0:s+a.actualOffset,pageEnd:s+a.pageEnd,totalChars:c,paginated:!0}}function gi(e,t,n){return typeof e[t]!="string"?null:Mm(e,t,n,"",(r,o)=>Ba(r,o))}function Lx(e,t,n){return ye(e[t])?Mm(e,t,n,{},(r,o)=>za(r,o)):null}function Ox(e,t){return typeof e=="string"?Ba(e,t):ye(e)?za(e,t):null}function za(e,t){let n=[];for(let[i,s]of Object.entries(e))Ga.has(i)||Array.isArray(s)&&s.length>0&&n.push({field:i,kind:"array",itemPaginator:Ox});let r=Ke(e,t,n);if(r.paginated)return r;for(let[i,s]of Object.entries(e)){if(Ga.has(i)||typeof s!="string")continue;let a=gi(e,i,t);if(a?.paginated)return a}for(let[i,s]of Object.entries(e)){if(Ga.has(i)||!ye(s))continue;let a=Lx(e,i,t);if(a?.paginated)return a}let o=Ne(e).length;return{value:e,actualOffset:0,pageEnd:o,totalChars:o,paginated:!1}}function Ix(e,t){return ye(e)?Ke(e,t,[{field:"text_matches",kind:"array",itemPaginator:(n,r)=>typeof n=="string"?Ba(n,r):ye(n)?gi(n,"value",r):null}]):null}function kx(e,t){return!ye(e)||Ne(e).length<=km()?null:Ke(e,t,[{field:"fileChanges",kind:"array",itemPaginator:(n,r)=>ye(n)?gi(n,"patch",r):null}])}function vx(e,t){return ye(e)?gi(e,"value",t):null}function Fx(e,t){return ye(e)?Ke(e,t,[{field:"matches",kind:"array",itemPaginator:vx}]):null}function Nm(e,t,n){let r;switch(e){case S.GITHUB_SEARCH_CODE:r=Ke(t,n,[{field:"files",kind:"array",itemPaginator:Ix}]);break;case S.GITHUB_SEARCH_REPOSITORIES:r=Ke(t,n,[{field:"repositories",kind:"array"},{field:"repositoryDetails",kind:"array"}]);break;case S.GITHUB_VIEW_REPO_STRUCTURE:r=Ke(t,n,[{field:"structure",kind:"record"}]);break;case S.PACKAGE_SEARCH:r=Ke(t,n,[{field:"packages",kind:"array"}]);break;case S.LOCAL_RIPGREP:r=Ke(t,n,[{field:"files",kind:"array",itemPaginator:Fx}]);break;case S.LOCAL_VIEW_STRUCTURE:r=Ke(t,n,[{field:"entries",kind:"array"}]);break;case S.GITHUB_SEARCH_PULL_REQUESTS:r=Ke(t,n,[{field:"pull_requests",kind:"array",itemPaginator:kx}]);break;case S.LOCAL_FIND_FILES:{let o=Ne(t).length;return{value:t,actualOffset:0,pageEnd:o,totalChars:o,paginated:!1}}case S.GITHUB_FETCH_CONTENT:case S.LOCAL_FETCH_CONTENT:return{value:t,actualOffset:0,pageEnd:Ne(t).length,totalChars:Ne(t).length,paginated:!1};default:r={value:t,actualOffset:0,pageEnd:Ne(t).length,totalChars:Ne(t).length,paginated:!1};break}return r.paginated?r:za(t,n)}function Mx(e,t,n){if(!ye(e)||!ye(e.data)||e.status!==void 0)return null;let r={...e,data:{}},o=Math.max(Ne(r).length-2,0),i=Nm(n,e.data,{offset:t.offset<=o?0:t.offset-o,length:t.offset<=o?Math.max(1,t.length-o):t.length,explicit:!0}),s=o+i.totalChars;if(!i.paginated&&(!t.explicit||s<=t.length))return{value:e,actualOffset:0,pageEnd:s,totalChars:s,paginated:!1};if(t.offset>=s)return{value:r,actualOffset:t.offset,pageEnd:t.offset,totalChars:s,paginated:!0};let a=Fm(i.actualOffset,Math.max(0,i.pageEnd-i.actualOffset),i.totalChars,t.length),c=i.paginated&&ye(i.value)?{...i.value,outputPagination:a,...n===S.LOCAL_FIND_FILES&&{charPagination:a}}:i.value;return{value:{...e,data:c},actualOffset:t.offset<=o?0:o+i.actualOffset,pageEnd:o+i.pageEnd,totalChars:s,paginated:!0}}function PB(e,t,n){if(!ye(e.data)||e.status!==void 0)return e;let r=vm({offset:typeof t.charOffset=="number"?t.charOffset:void 0,length:typeof t.charLength=="number"?t.charLength:void 0});if(!r.explicit)return e;let o=Nm(n,e.data,r);if(!o.paginated)return e;let i=Fm(o.actualOffset,Math.max(0,o.pageEnd-o.actualOffset),o.totalChars,r.length),s={...o.value,outputPagination:i};return{...e,data:s}}function EB(e,t,n){let r=vm(t,tl(e.results.length));if(!r.explicit&&e.results.length>0&&e.results.every(i=>ye(i?.data)&&i.data.outputPagination!==void 0))return e;let o=Ke({results:e.results},r,[{field:"results",kind:"array",itemPaginator:(i,s)=>Mx(i,s,n)}]);return o.paginated?{results:Array.isArray(o.value.results)?o.value.results:[]}:e}import{securityRegistry as RQ,ContentSanitizer as bQ}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as CQ}from"@octocodeai/octocode-engine/mask";import{configureSecurity as EQ}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as kQ}from"@octocodeai/octocode-core";import{z as FQ}from"zod";export{zx as ALL_ERROR_CODES,Sm as ALL_TOOLS,Wh as BASE_SCHEMA,$a as BaseCommandBuilder,bd as BulkCloneRepoLocalSchema,Ca as BulkLspGetSemanticsQuerySchema,hi as CONFIG_ERRORS,Xc as CONFIG_FILE_NAME,er as CONFIG_FILE_PATH,Xn as CONFIG_SCHEMA_VERSION,Uo as CORE_ALLOWED_ENV_VARS,Ye as CREDENTIALS_FILE,Pa as CircuitOpenError,Bs as CloneRepoQueryLocalSchema,Fo as ContentBuilder,bQ as ContentSanitizer,oN as DEFAULTS,nG as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,co as DEFAULT_CONFIG,Jn as DEFAULT_GITHUB_CONFIG,At as DEFAULT_LOCAL_CONFIG,qn as DEFAULT_LSP_CONFIG,Ja as DEFAULT_MATCH_SNIPPET_CHARS,ln as DEFAULT_NETWORK_CONFIG,pt as DEFAULT_OUTPUT_CONFIG,Zn as DEFAULT_TELEMETRY_CONFIG,Bt as DEFAULT_TOOLS_CONFIG,La as DEFAULT_TOOL_METADATA_GATEWAY,ls as DESCRIPTIONS,Uy as DIFF_PREVIEW_MAX_LINES,Em as DIRECT_TOOL_CATEGORIES,WU as DIRECT_TOOL_DEFINITIONS,Rt as DirectToolInputError,an as ENV_TOKEN_VARS,G as ERROR_CODES,le as ERROR_MESSAGES,St as FETCH_ERRORS,Oe as FILE_OPERATION_ERRORS,Pd as FileContentBulkQueryLocalSchema,bb as FileContentQueryBaseLocalSchema,jo as FileContentQueryLocalSchema,bU as GITHUB_CLONE_REPO,mU as GITHUB_FETCH_CONTENT,Xa as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,fU as GITHUB_SEARCH_CODE,Be as GITHUB_SEARCH_DEFAULT_LIMIT,pe as GITHUB_SEARCH_MAX_LIMIT,Gx as GITHUB_SEARCH_MAX_PAGES,yU as GITHUB_SEARCH_PULL_REQUESTS,hU as GITHUB_SEARCH_REPOSITORIES,Kt as GITHUB_STRUCTURE_DEFAULTS,Ux as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Va as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,gU as GITHUB_VIEW_REPO_STRUCTURE,h0 as GitHubCloneRepoOutputLocalSchema,Qd as GitHubCodeSearchBulkQueryLocalSchema,lF as GitHubCodeSearchOutputLocalSchema,zd as GitHubCodeSearchQueryLocalSchema,T0 as GitHubFetchContentOutputLocalSchema,vo as GitHubProvider,Jd as GitHubPullRequestSearchBulkQueryLocalSchema,Jo as GitHubPullRequestSearchQueryLocalSchema,cp as GitHubReposSearchBulkQueryLocalSchema,ap as GitHubReposSearchSingleQueryLocalSchema,TF as GitHubSearchPullRequestsOutputLocalSchema,qF as GitHubSearchRepositoriesOutputLocalSchema,fp as GitHubViewRepoStructureBulkQueryLocalSchema,gM as GitHubViewRepoStructureOutputLocalSchema,pp as GitHubViewRepoStructureQueryLocalSchema,ut as HOME,gL as IGNORED_FILE_EXTENSIONS,hL as IGNORED_FILE_NAMES,yL as IGNORED_FOLDER_NAMES,rt as KEY_FILE,xU as LOCAL_BINARY_INSPECT,Ka as LOCAL_DEFAULT_FILES_PER_PAGE,EU as LOCAL_FETCH_CONTENT,PU as LOCAL_FIND_FILES,nn as LOCAL_MAX_DEPTH,Hr as LOCAL_MAX_FILES_PER_PAGE,tn as LOCAL_MAX_LIMIT,SU as LOCAL_RIPGREP,H as LOCAL_TOOL_ERROR_CODES,Za as LOCAL_TOOL_ERROR_REGISTRY,CU as LOCAL_VIEW_STRUCTURE,TU as LSP_GET_SEMANTIC_CONTENT,Ie as LSP_GET_SEMANTIC_CONTENT_TOOL_NAME,hp as LocalBinaryInspectBulkQuerySchema,Zo as LocalBinaryInspectQuerySchema,Np as LocalFetchContentBulkQuerySchema,ei as LocalFetchContentQuerySchema,Up as LocalFindFilesBulkQuerySchema,ti as LocalFindFilesQuerySchema,Vp as LocalRipgrepBulkQuerySchema,vn as LocalRipgrepQuerySchema,Qm as LocalToolErrorCategory,df as LocalViewStructureBulkQuerySchema,oi as LocalViewStructureQuerySchema,dT as LspGetSemanticsOutputSchema,Sa as LspGetSemanticsQueryDisplaySchema,XE as LspGetSemanticsQuerySchema,fh as MAX_BRANCH_CACHE_SIZE,rn as MAX_CHAR_LENGTH,Ya as MAX_CONTEXT_LINES,el as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Py as MAX_DIRECTORY_FILES,Ur as MAX_MATCH_CONTENT_LENGTH,hn as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,Gr as MAX_PAGE_NUMBER,mn as MAX_RETRIES,pn as MAX_TIMEOUT,Ey as MAX_TOTAL_SIZE,gn as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,fn as MIN_RETRIES,dn as MIN_TIMEOUT,ns as NETWORK_ERROR_PATTERNS,tm as NpmDeprecationOutputSchema,em as NpmRegistrySearchSchema,Rm as NpmSearchBulkQueryLocalSchema,MG as NpmSearchOutputLocalSchema,ym as NpmSearchQueryLocalSchema,ci as NpmViewResultSchema,Ci as OCTOCODE_DIR,be as OCTOCODE_HOME,uo as OctocodeConfigSchema,ch as OctokitWithThrottling,RU as PACKAGE_SEARCH,Ct as PROMISE_ERRORS,Bl as PROVIDER_CAPABILITIES,Jl as PROXY_ENV_VARS,Mt as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,Wa as PR_CONTENT_MAX_ITEMS_PER_PAGE,Us as ProviderInitializationError,rv as QuickResult,Ro as RATE_LIMIT_CONFIG,rs as RATE_LIMIT_PATTERNS,et as REPOSITORY_ERRORS,st as RESOURCE_LIMITS,RB as RipgrepJsonMessageSchema,oe as SEARCH_ERRORS,mu as SEMANTIC_CONTENT_TYPES,wv as SENSITIVE_ENV_VARS,xt as SESSION_FILE,zm as STARTUP_ERRORS,ge as STATIC_TOOL_NAMES,_t as STATS_FILE,Eu as STATUS_TO_ERROR_CODE,Mo as StatusEmoji,LR as StatusEmojis,_r as TOOLING_ALLOWED_ENV_VARS,Br as TOOL_ERRORS,Bm as TOOL_METADATA_ERRORS,S as TOOL_NAMES,Te as ToolError,De as ToolErrors,bt as VALIDATION_ERRORS,Vi as _getCacheState,tc as _getLogHandler,_T as _packageNameToSearchKeywords,$i as _resetConfigCache,IU as _resetMetadataState,SG as _resetNpmRegistryUrlCache,Yc as _resetSessionState,bA as _resetTokenResolvers,RA as _setTokenResolvers,EB as applyBulkResponsePagination,sl as applyContentPagination,mf as applyEntryFilters,Kb as applyExactMatchRanking,pB as applyOutputSizeLimit,mt as applyPagination,wo as applyPartialContentFilter,PB as applyQueryOutputPagination,Nl as applyStructurePagination,Xf as assertCircuitAvailable,U as attachRawResponseChars,OO as buildBlockBoundaryHint,Ms as buildChildProcessEnv,wu as buildCodeSearchQuery,Pr as buildDiffPreview,tB as buildDirectToolExampleQuery,ZP as buildEntryPaginationHints,Hd as buildGhSearchCodeFinalizer,Nd as buildGithubFetchContentFinalizer,A0 as buildPaginationHints,Lu as buildPullRequestSearchQuery,Au as buildRepoSearchQuery,ri as buildSearchResult,Ia as buildToolErrorResult,la as buildWalkWarnings,vy as byteSlice,Eo as byteToCharIndex,nl as charToByteIndex,_M as checkLargeOutputSafety,eG as checkNpmAvailability,DT as checkNpmDeprecation,CG as checkNpmRegistryReachable,aa as checkRegexSafety,v as clampedInt,SA as cleanup,aL as clearAllCache,uL as clearLSPToolCache,cL as clearLocalToolCache,VA as clearOctokitInstances,Yk as clearProviderCache,lL as clearRemoteAPICache,td as cloneRepo,$o as collectFlatErrors,KR as commonDirPrefix,Xi as compactLocation,bn as compactResolvedSymbol,qd as compareIsoDateDescending,kQ as completeMetadata,nb as computeQueryTimeout,lo as configExists,oG as configureCircuitBreaker,EQ as configureSecurity,An as contextLinesField,EO as convertByteMatchToChar,Wt as countLines,N as countSerializedChars,Cs as createBasePRTransformation,gr as createCacheMeta,Or as createCallItemKey,L as createErrorResult,gt as createGitHubProviderError,ko as createGitHubProviderErrorFromResult,$e as createLazyProviderContext,tt as createLogger,br as createPaginationInfo,lb as createProviderExecutionContext,X as createRelaxedBulkQuerySchema,xr as createResponseFormat,nv as createResult,No as createRoleBasedResult,XD as createSafeRegExp,Pe as createSuccessResult,$r as decrypt,Pc as deleteCredentials,Kc as deleteSession,sB as detectEnvironment,jr as encrypt,Jm as ensureBinary,uc as ensureClone,hr as ensureCloneParentDir,Bn as ensureHome,Ym as ensureLogs,Pt as ensureOctocodeDir,Km as ensureRepos,zn as ensureTmp,Xm as ensureTree,Zm as ensureUnzip,Co as evictExpiredClones,dr as evictExpiredTrees,J as executeBulkOperation,gd as executeCloneRepo,rB as executeDirectTool,Dp as executeFetchContent,Qp as executeFindFiles,Op as executeInspectBinary,ya as executeLspGetSemantics,Ir as executeNpmCommand,kt as executeProviderOperation,md as executeProviderOperations,cf as executeRipgrepSearch,of as executeRipgrepSearchInternal,bf as executeViewStructure,od as executeWithErrorIsolation,ke as executeWithToolBoundary,up as exploreMultipleRepositoryStructures,xo as extractMatchingLines,Tu as fallbackOnBestEffortFailure,vp as fetchContent,Zu as fetchDirectoryContents,As as fetchDirectoryContentsRecursivelyAPI,qu as fetchFileContentToDisk,al as fetchFileTimestamp,ul as fetchGitHubFileContentAPI,SI as fetchGitHubPullRequestByNumberAPI,xs as fetchGitHubPullRequestByNumberAPIInternal,kl as fetchHistory,Dd as fetchMultipleGitHubFileContents,So as fetchRawGitHubFileContent,vt as fetchWithRetries,ll as filterPatch,vS as filterStructure,ta as finalizeFetchContentResult,zp as finalizeFindFilesResult,nf as finalizeRipgrepResult,Rf as finalizeViewStructureResult,wm as findDirectToolDefinition,Bp as findFiles,Cr as findNextBlockBoundary,zc as flushSession,Qc as flushSessionSync,Zg as formatBytes,ov as formatCallToolResultForOutput,XU as formatDirectToolMetadataSchemaText,qU as formatDirectToolOutputSchemaText,YU as formatDirectToolSchemaText,sx as formatDirectToolValidationIssues,kn as formatFileSize,Vo as formatFinalizedResponse,Er as formatPRForResponse,BF as formatRepoLine,da as gatherIncomingCallsRecursive,pa as gatherOutgoingCallsRecursive,_e as generateCacheKey,ZI as generatePaginationHints,Oo as generateStructurePaginationHints,ir as getActiveProvider,Yi as getActiveProviderConfig,zr as getAppDataPath,ac as getArchitecture,tl as getBulkDefaultCharLength,rl as getByteLength,dL as getCacheStats,my as getCacheTTL,fs as getCloneBaseDir,$u as getCloneDir,go as getConfig,qc as getConfigPath,ae as getConfigSync,lu as getConfigValue,Ut as getCredentials,wc as getCredentialsFilePath,Yr as getCredentialsSync,cc as getDefaultOctocodeHome,bm as getDescription,JU as getDirectToolAutoFilledFields,fi as getDirectToolCategory,eB as getDirectToolDescription,Am as getDirectToolDisplayFields,ZU as getDirectToolOutputFields,or as getDirectorySizeBytes,Ti as getEnvTokenSource,ku as getExtension,$l as getFileContent,Wr as getGhCliToken,pu as getGitHubToken,ic as getLocalAppDataPath,cB as getLspEnvironmentHint,gy as getMaxCacheSizeBytes,hy as getMaxCloneCount,OU as getMetadataOrNull,xa as getNpmRegistryUrl,zt as getOctocodeDir,ie as getOctokit,to as getOrCreateSession,Ce as getOutputCharLimit,Ah as getOwnerQualifier,sc as getPlatformName,Os as getProvider,ne as getRawResponseChars,ws as getRecursiveFetchFailureCount,Wl as getRepoStructure,sO as getReposBaseDir,ho as getServerConfig,jc as getSessionId,Sn as getSessionManager,Ac as getToken,Vr as getTokenFromEnv,EA as getTokenSource,Lc as getTokenSync,Oi as getTokenWithRefresh,ju as getTreeBaseDir,ms as getTreeDir,Ee as handleCatchError,Z as handleGitHubAPIError,Go as handleProviderError,xc as hasCredentials,_c as hasCredentialsSync,xi as hasEnvToken,pF as hasExpensiveContentRequest,ad as hoistSharedFields,xe as ignoreBestEffortFailure,ro as incrementErrors,so as incrementGitHubCacheHits,ao as incrementGitHubCacheRateLimits,Vc as incrementPackageRegistryFailures,$c as incrementRateLimitByProvider,oo as incrementRateLimits,no as incrementToolCalls,io as incrementToolCharSavings,LP as inferLspSymbolName,du as initialize,Yl as initializeProviders,vA as initializeSession,LU as initializeToolMetadata,yn as invalidateConfigCache,Gn as invalidateCredentialsCache,Sv as invokeCallbackSafely,mr as isCacheHit,Vu as isCacheValid,Zf as isCircuitOpen,PA as isCloneEnabled,li as isExactPackageName,Yt as isGitHubAPIError,aR as isGitHubAPISuccess,bi as isLinux,CA as isLocalEnabled,Ji as isLocalTool,fu as isLoggingEnabled,Un as isMac,Sr as isMidBlockCut,$t as isNoResultsSearchError,cb as isProviderError,zo as isProviderSuccess,Dn as isRefreshTokenExpired,cR as isRepository,ct as isTokenExpired,yi as isToolError,ds as isToolInMetadata,Nt as isWindows,Ln as lineNumberField,Ec as listStoredHosts,Tc as listStoredHostsSync,Zc as loadConfig,tr as loadConfigSync,AU as loadToolContent,gu as logPackageRegistryFailure,NA as logPromptCall,Lt as logRateLimit,M as logSessionError,FA as logSessionInit,MA as logToolCall,_d as mapCodeSearchProviderResult,Td as mapCodeSearchToolQuery,kd as mapFileContentProviderResult,Id as mapFileContentToolQuery,Od as mapPullRequestProviderResultData,Ld as mapPullRequestToolQuery,Ad as mapRepoSearchProviderRepositories,wd as mapRepoSearchToolQuery,Fd as mapRepoStructureProviderResult,vd as mapRepoStructureToolQuery,CQ as maskSensitiveData,Tr as normalizeOwnerRepo,jd as normalizePullRequestContentRequest,bo as normalizeResponseHeaders,ua as paginateEntries,k0 as paginateGroupsCharWindow,Ar as parseFileSize,de as parseGitHubProjectId,Bi as parseLoggingEnv,gB as parseRipgrepJson,W as paths,rf as preflightValidateRipgrepPattern,ix as prepareDirectToolInput,nB as prepareDirectToolInputFromJsonText,cl as processFileContentAPI,Qo as providerSupports,gs as readCacheMeta,lt as readCredentialsStore,Jf as recordCircuitFailure,Ta as recordCircuitSuccess,Nn as redactPath,Oc as refreshAuthToken,sd as relativizeResultPaths,q as relaxedPageNumberField,ji as reloadConfig,hs as removeCloneDir,rG as resetCircuitBreaker,DA as resetSessionManager,Wc as resetSessionStats,_i as resetTokenResolution,Qi as resolveConfig,rr as resolveConfigSync,Ge as resolveDefaultBranch,fa as resolveFileAnchor,Ef as resolveSymbolAnchor,wi as resolveToken,Tt as resolveTokenFull,Ai as resolveTokenWithRefresh,Ae as responseEnvelopeFields,On as safeExec,Le as safeParseOrError,Oa as sanitizeCallToolResult,ot as sanitizeStructuredContent,Ql as searchCode,af as searchContentRipgrep,Nu as searchGitHubCodeAPI,Ol as searchGitHubPullRequestsAPI,Ml as searchGitHubReposAPI,Gd as searchMultipleGitHubCode,Zd as searchMultipleGitHubPullRequests,op as searchMultipleGitHubRepos,pm as searchNpmPackage,fm as searchPackage,mm as searchPackages,Vl as searchPullRequests,jl as searchRepos,RQ as securityRegistry,_O as serializeForPagination,ec as setLogHandler,Kd as shapePullRequestForContent,cr as shouldIgnoreDir,xn as shouldIgnoreFile,aB as shouldUseMCPLsp,Ou as shouldUseSearchForPRs,wO as sliceByCharRespectLines,Ss as sliceContent,To as snapToSemanticBoundary,KU as sortDirectToolNames,Zl as spawnCheckSuccess,Av as spawnCollectStdout,Xt as spawnWithTimeout,Rr as splitLines,aO as startCacheGC,cO as stopCacheGC,Li as storeCredentials,ca as summarizeEntries,hf as toEntryObject,gf as toGroupedLists,qa as toToolError,pR as transformCodeSearchResult,gR as transformFileContentResult,Lo as transformPullRequestItemFromREST,xl as transformPullRequestItemFromSearch,bR as transformPullRequestResult,fR as transformRepoSearchResult,CR as transformRepoStructureResult,dl as trimDiffContext,Sb as truncateSnippetChars,He as updateSessionStats,Xr as updateToken,Bo as validateArgs,po as validateConfig,ve as validateToolPath,Ul as viewGitHubRepositoryStructureAPI,yf as viewStructure,ja as withBasicSecurityValidation,we as withDataCache,dv as withResponseEnvelope,Qa as withSecurityValidation,fr as writeCacheMeta,FQ as z};
|