@octocodeai/octocode-tools-core 16.3.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/direct.js
CHANGED
|
@@ -5,49 +5,42 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
var gr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{z as Ho}from"zod";import{resolveTokenFull as ju,getConfigSync as Ko,invalidateConfigCache as DS}from"octocode-shared";var ct="16.2.0";var yr={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},Ze={PROMISES_NOT_ARRAY:{code:"VALIDATION_PROMISES_NOT_ARRAY",message:"promises must be an array"},TIMEOUT_NOT_POSITIVE:{code:"VALIDATION_TIMEOUT_NOT_POSITIVE",message:"timeout must be positive"},CONCURRENCY_NOT_POSITIVE:{code:"VALIDATION_CONCURRENCY_NOT_POSITIVE",message:"concurrency must be positive"}},Je={FETCH_NOT_AVAILABLE:{code:"FETCH_NOT_AVAILABLE",message:"Global fetch is not available in this environment."},FETCH_FAILED_AFTER_RETRIES:{code:"FETCH_FAILED_AFTER_RETRIES",message:(e,t)=>`Failed to fetch after ${e} attempts: ${t}`},FETCH_HTTP_ERROR:{code:"FETCH_HTTP_ERROR",message:(e,t)=>`Failed to fetch (${e} ${t})`}},zu={INVALID_FORMAT:{code:"TOOL_METADATA_INVALID_FORMAT",message:"Invalid tool metadata format from remote source."},INVALID_API_RESPONSE:{code:"TOOL_METADATA_INVALID_API_RESPONSE",message:"Invalid API response structure"}},Ce={PATH_IS_DIRECTORY:{code:"FILE_PATH_IS_DIRECTORY",message:e=>`Path is a directory. Use ${e} to list directory contents`},FILE_TOO_LARGE:{code:"FILE_TOO_LARGE",message:(e,t,n)=>`File too large (${e}KB > ${t}KB). Use ${n} to search within the file or use startLine/endLine parameters to get specific sections`},FILE_EMPTY:{code:"FILE_EMPTY",message:"File is empty - no content to display"},BINARY_FILE:{code:"FILE_BINARY",message:"Binary file detected. Cannot display as text - download directly from GitHub"},DECODE_FAILED:{code:"FILE_DECODE_FAILED",message:"Failed to decode file. Encoding may not be supported (expected UTF-8)"},UNSUPPORTED_TYPE:{code:"FILE_UNSUPPORTED_TYPE",message:e=>`Unsupported file type: ${e}`}},Ge={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},te={QUERY_EMPTY:{code:"SEARCH_QUERY_EMPTY",message:"Search query cannot be empty"},NO_VALID_PARAMETERS:{code:"SEARCH_NO_VALID_PARAMETERS",message:"No valid search parameters provided"},PR_REQUIRED_PARAMS:{code:"SEARCH_PR_REQUIRED_PARAMS",message:"Owner, repo, and prNumber are required parameters"},PR_SINGLE_VALUES:{code:"SEARCH_PR_SINGLE_VALUES",message:"Owner and repo must be single values"},PULL_REQUEST_SEARCH_FAILED:{code:"SEARCH_PR_SEARCH_FAILED",message:e=>`Pull request search failed: ${e}`},PULL_REQUEST_LIST_FAILED:{code:"SEARCH_PR_LIST_FAILED",message:e=>`Pull request list failed: ${e}`},PULL_REQUEST_FETCH_FAILED:{code:"SEARCH_PR_FETCH_FAILED",message:(e,t)=>`Failed to fetch pull request #${e}: ${t}`}},Qu={NO_TOOLS_REGISTERED:{code:"STARTUP_NO_TOOLS_REGISTERED",message:"No tools were successfully registered"},UNCAUGHT_EXCEPTION:{code:"STARTUP_UNCAUGHT_EXCEPTION",message:e=>`Uncaught exception: ${e}`},UNHANDLED_REJECTION:{code:"STARTUP_UNHANDLED_REJECTION",message:e=>`Unhandled rejection: ${e}`},STARTUP_FAILED:{code:"STARTUP_FAILED",message:e=>`Startup failed: ${e}`}},qe={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Rr={EXECUTION_FAILED:{code:"TOOL_EXECUTION_FAILED",message:(e,t)=>`Tool ${e} execution failed: ${t}`},SECURITY_VALIDATION_FAILED:{code:"TOOL_SECURITY_VALIDATION_FAILED",message:(e,t)=>`Security validation failed for ${e}: ${t}`}},MS={...yr,...Ze,...Je,...zu,...Ce,...Ge,...te,...Qu,...qe,...Rr};import{maskSensitiveData as Vu}from"octocode-security/mask";var Nt=null,Mt=null,Wu=ju;var Ku=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"]);async function Yo(){try{let e=await Wu({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:Ku.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Xo(){if(Nt!==null)return;if(Mt!==null)return Mt;let e=(async()=>{let t=Ko(),n=await Yo();Nt={version:ct,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,loggingEnabled:t.telemetry.logging,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Mt=e;try{await e}catch(t){throw Mt===e&&(Nt=null,Mt=null),t}}function br(){if(!Nt){let e=Vu(yr.NOT_INITIALIZED.message);throw new Error(e)}return Nt}async function Zo(){return(await Yo()).token}function un(){let e=br();return e.enableLocal&&e.enableClone}function dn(){return"github"}function Sr(){let e=Ko().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as Qd}from"octocode-security/contentSanitizer";import{createRequire as Yu}from"node:module";var Xu=Yu(import.meta.url),Jo="@octocodeai/octocode-context-utils",pn,Zu=()=>Xu(Jo),Cr=class extends Error{constructor(n){super(`Failed to load native dependency ${Jo}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function le(){if(pn)return pn;try{return pn=Zu(),pn}catch(e){throw new Cr(e)}}var U={applyContentViewMinification(e,t){return le().applyContentViewMinification(e,t)},applyMinification(e,t){return le().applyMinification(e,t)},minifyContent(e,t){return le().minifyContent(e,t)},minifyContentSync(e,t){return le().minifyContentSync(e,t)},minifyContentResult(e,t){return le().minifyContentResult(e,t)},minifyMarkdownCore(e){return le().minifyMarkdownCore(e)},extractSignatures(e,t){return le().extractSignatures(e,t)},structuralSearch(e,t,n,r){return le().structuralSearch(e,t,n,r)},getSemanticBoundaryOffsets(e,t){return le().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return le().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return le().parseRipgrepJson(e,t)},queryFileSystem(e){return le().queryFileSystem(e)},extractMatchingLines(e,t,n){return le().extractMatchingLines(e,t,n)},filterPatch(e,t){return le().filterPatch(e,t)},charToByteOffset(e,t){return le().charToByteOffset(e,t)},byteToCharOffset(e,t){return le().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return le().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return le().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return le().SIGNATURES_ONLY_HINT}};import{Octokit as ed}from"octokit";import{throttling as td}from"@octokit/plugin-throttling";import{createHash as nd}from"crypto";import{getOrCreateSession as eC,incrementToolCalls as tC,incrementErrors as nC,incrementRateLimits as rC,incrementGitHubCacheRateLimits as oC,updateSessionStats as iC}from"octocode-shared";import{completeMetadata as Ju}from"@octocodeai/octocode-core";var ge="lspGetSemantics",qo=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation"];function bt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Pr(e){return{uri:e.uri,...e.content!==void 0&&{content:e.content},...e.displayRange&&{displayRange:e.displayRange},...e.isDefinition&&{isDefinition:!0}}}var W=Ju.toolNames,KS=new Set([W.LOCAL_RIPGREP,W.LOCAL_FETCH_CONTENT,W.LOCAL_FIND_FILES,W.LOCAL_VIEW_STRUCTURE,W.LOCAL_BINARY_INSPECT,ge]);var qu=null;function Er(){return qu}async function H(e,t){let n=Er();n&&await n.logError(e,t)}async function et(e){let t=Er();t&&await t.logRateLimit(e)}function ei(e){let t=Er();t&&t.logPackageRegistryFailure(e)}function rd(e){return nd("sha256").update(e).digest("hex").substring(0,16)}var od=ed.plugin(td),id=300*1e3,Tr=50,sd=60*1e3;function wr(e){return Date.now()-e.createdAt>id}var Me=new Map,Ht=null,Dt=null;function si(){for(let[e,t]of Me.entries())wr(t)&&Me.delete(e);if(Me.size>Tr){let e=[...Me.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=Me.size-Tr;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Me.delete(r[0])}}}function ad(){Dt||(Dt=setInterval(si,sd),typeof Dt=="object"&&"unref"in Dt&&Dt.unref())}var ti=3,ni=60;function ri(e,t,n){et({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var cd=()=>({onRateLimit:(e,t,n,r)=>(ri("primary",e,t),r<ti&&e<ni),onSecondaryRateLimit:(e,t,n,r)=>(ri("secondary",e,t),r<ti&&e<ni)});function oi(e){let t=br(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${ct}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:cd(),log:r,...e&&{auth:e}};return new od(o)}async function ne(e){if(ad(),e?.token){let n=rd(e.token),r=Me.get(n);if(r&&!wr(r))return r.client;Me.size>=Tr&&si();let o=oi(e.token);return Me.set(n,{client:o,createdAt:Date.now()}),o}let t=Me.get("DEFAULT");return t&&!wr(t)?t.client:Ht||(Ht=(async()=>{try{let n=await Zo(),r=oi(n??void 0);return Me.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{Ht=null}})(),Ht)}var ld=200,Gt=new Map;async function Oe(e,t,n){let r=`${e}/${t}`,o=Gt.get(r);if(o)return o;let i=await ne(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return ii(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),ii(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function ii(e,t){if(Gt.size>=ld){let n=Gt.keys().next().value;n!==void 0&&Gt.delete(n)}Gt.set(e,t)}import{RequestError as ci}from"octokit";var z={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},ue={[z.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[z.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[z.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[z.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[z.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[z.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[z.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[z.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[z.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[z.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},ai={401:z.AUTH_REQUIRED,403:z.FORBIDDEN_PERMISSIONS,404:z.NOT_FOUND,422:z.INVALID_REQUEST,502:z.SERVER_UNAVAILABLE,503:z.SERVER_UNAVAILABLE,504:z.SERVER_UNAVAILABLE},_r={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},xr={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},mn={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var ud=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function lt(e){if(!(e instanceof ci)||e.status!==422)return!1;let t=e.response?.data?.errors;return!Array.isArray(t)||t.length===0?!1:t.some(n=>{let r=typeof n?.message=="string"?n.message.toLowerCase():"";return ud.some(o=>r.includes(o))})}function Z(e){return e instanceof ci?dd(e):e instanceof Error?bd(e):{error:typeof e=="string"?e:ue[z.UNKNOWN].message,type:"unknown"}}function dd(e){let{status:t,message:n,response:r}=e;if(t===403)return md(n,r);if(t===429)return pd(n,r);let o=ai[t];return o?Rd(o,t):St(z.UNKNOWN,{error:n||ue[z.UNKNOWN].message,status:t})}function Ar(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function pd(e,t){let n=t?.headers,r=Ar(n,"retry-after"),o=Ar(n,"x-ratelimit-reset"),i=Ar(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+mn.RESET_BUFFER_SECONDS,0):void 0);return et({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),St(z.RATE_LIMIT_PRIMARY,{error:e||ue[z.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ue[z.RATE_LIMIT_PRIMARY].suggestion})}function md(e,t){let n=t?.headers;if(xr.SECONDARY.test(e))return fd(n);let r=n?.["x-ratelimit-remaining"],o=yd(t);return r==="0"||o?hd(n):gd(n)}function fd(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?mn.SECONDARY_FALLBACK_SECONDS:t;return et({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),St(z.RATE_LIMIT_SECONDARY,{error:ue[z.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ue[z.RATE_LIMIT_SECONDARY].suggestion})}function hd(e){let t=e?.["x-ratelimit-reset"],n=t?parseInt(String(t),10):NaN,r=isNaN(n)?null:new Date(n*1e3),o=r?Math.max(Math.ceil((r.getTime()-Date.now())/1e3)+mn.RESET_BUFFER_SECONDS,0):void 0,i=r?ue[z.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ue[z.RATE_LIMIT_PRIMARY].messageWithoutTime;return et({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),St(z.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ue[z.RATE_LIMIT_PRIMARY].suggestion})}function gd(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ue[z.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Sd(String(t),String(n))),St(z.FORBIDDEN_PERMISSIONS,{error:ue[z.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function yd(e){return e?.data?.errors?.some(n=>n.type===xr.GRAPHQL_TYPE)??!1}function Rd(e,t){let n=ue[e];return St(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function bd(e){return _r.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ue[z.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ue[z.NETWORK_CONNECTION_FAILED].suggestion}:_r.TIMEOUT.some(t=>e.message.includes(t))?{error:ue[z.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ue[z.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function St(e,t){return{type:"http",...t}}function Sd(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?ue[z.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ue[z.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Cd(e){return`user:${e}`}var Pd=/[@/]/,Ed=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Td=/^[A-Za-z0-9_-]+$/;function li(e){return e.startsWith('"')||Td.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var $t=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(Cd(r))});return this}addDateFilters(t){return Object.entries({created:"created",updated:"updated","author-date":"author-date","committer-date":"committer-date","merged-at":"merged",closed:"closed"}).forEach(([r,o])=>{let i=t[r];i&&this.queryParts.push(`${o}:${i}`)}),this}addArrayFilter(t,n,r=!1){return t&&t!==null&&(Array.isArray(t)?t:[t]).forEach(i=>{let s=r?`"${i}"`:i;this.queryParts.push(`${n}:${s}`)}),this}addBooleanFilter(t,n,r){return t===!0?this.queryParts.push(n):t===!1&&this.queryParts.push(r),this}addSimpleFilter(t,n){return t!=null&&this.queryParts.push(`${n}:${t}`),this}addQuotedFilter(t,n){if(t!=null){let o=Pd.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},Lr=class extends $t{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(li))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Ed):null;return o&&(r=o[1],n=n.slice(0,o.index)||void 0),this.addSimpleFilter(r,"filename"),this.addSimpleFilter(t.extension,"extension"),this.addQuotedFilter(n,"path"),t.language&&this.queryParts.push(`language:${t.language}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="file"?this.queryParts.push("in:file"):r==="path"&&this.queryParts.push("in:path")}),this}},Ir=class extends $t{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(li)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},Or=class extends $t{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function ui(e){return new Lr().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function di(e){return new Ir().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function pi(e){return new Or().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function mi(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import wd from"node-cache";import _d from"crypto";import{incrementGitHubCacheHits as xd}from"octocode-shared";var Ad="v1",Ld=300*1e3,ut=new wd({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Ct={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},fi={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},Bt=new Map;function Id(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Od(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function kd(e){let t=Id(e);if(!(!t||!Od(t)))try{xd(t,1)}catch{}}function vd(){let e=Date.now();for(let[t,n]of Bt.entries())e-n.startedAt>Ld&&Bt.delete(t)}var Fd=new Set([]);function Md(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t=e,n=!1,r={};for(let o of Object.keys(t)){if(Fd.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Pe(e,t,n){let r=kr(Md(t)),o=n?`${n}:${r}`:r,i=_d.createHash("sha256").update(o).digest("hex");return`${Ad}-${e}:${i}`}function kr(e,t=new WeakSet){return e===null?"null":e===void 0?"undefined":typeof e!="object"?String(e):t.has(e)?'"[Circular]"':(t.add(e),Array.isArray(e)?`[${e.map(o=>kr(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${kr(i,t)}`}).join(",")}}`)}function Nd(e){return fi[e]||fi.default}function Hd(e,t,n){try{return ut.set(e,t,n),Ct.sets++,Ct.totalKeys=ut.keys().length,!0}catch{try{let r=ut.keys();for(let o of r)ut.get(o);return ut.set(e,t,n),Ct.sets++,Ct.totalKeys=ut.keys().length,!0}catch{return!1}}}async function Ee(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=ut.get(e);if(i!==void 0)return Ct.hits++,kd(e),i}catch{}vd();let r=Bt.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Ct.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Nd(l)}Hd(e,i,a)}return i}finally{Bt.delete(e)}})();return Bt.set(e,{promise:o,startedAt:Date.now()}),o}var hi=[".github",".git",".vscode",".devcontainer",".config",".cargo",".changeset",".husky",".aspect",".eslint-plugin-local",".yarn",".gemini",".ng-dev",".configurations",".tx","dist","build","out","output","target","release","node_modules","vendor","third_party","tmp","temp","cache",".cache",".tmp",".pytest_cache",".tox",".venv",".mypy_cache",".next",".svelte-kit",".turbo",".angular",".dart_tool","__pycache__",".ruff_cache",".nox","htmlcov","cover",".gradle",".m2",".sbt",".bloop",".metals",".bsp","bin","obj","TestResults","BenchmarkDotNet.Artifacts",".vendor-new","Godeps","composer.phar",".phpunit.result.cache",".bundle",".byebug_history",".rspec_status",".mvn",".aws",".gcp","fastlane","DerivedData","xcuserdata","local.properties",".navigation","captures",".externalNativeBuild",".cxx",".idea",".idea_modules",".vs",".history","coverage",".nyc_output","logs","log",".DS_Store"],Dd=["package-lock.json",".secrets",".secret","secrets.json","secrets.yaml","secrets.yml","credentials.json","credentials.yaml","credentials.yml","auth.json","auth.yaml","auth.yml","api-keys.json","api_keys.json","service-account.json","service_account.json","private-key.pem","private_key.pem","id_rsa","id_dsa","id_ecdsa","id_ed25519","keyfile","keyfile.json","gcloud-service-key.json","firebase-adminsdk.json","google-services.json","GoogleService-Info.plist",".DS_Store","Thumbs.db","db.sqlite3","db.sqlite3-journal",".eslintcache",".stylelintcache",".node_repl_history",".yarn-integrity","celerybeat-schedule","celerybeat.pid","ThirdPartyNoticeText.txt","ThirdPartyNotices.txt","cglicenses.json","cgmanifest.json"],Gd=[".lock",".log",".tmp",".temp",".cache",".bak",".backup",".orig",".swp",".swo",".rej",".pid",".seed",".old",".save",".temporary",".exe",".dll",".so",".dylib",".a",".lib",".o",".obj",".bin",".class",".pdb",".dSYM",".pyc",".pyo",".pyd",".jar",".war",".ear",".nar",".db",".sqlite",".sqlite3",".mdb",".accdb",".zip",".tar",".gz",".bz2",".xz",".lz",".lzma",".Z",".tgz",".rar",".7z",".deb",".rpm",".pkg",".dmg",".msi",".appx",".snap",".map",".d.ts.map",".min.js",".min.css",".key",".pem",".p12",".pfx",".crt",".cer",".der",".csr",".jks",".keystore",".truststore",".kate-swp",".gnome-desktop",".sublime-project",".sublime-workspace",".iml",".iws",".ipr",".patch",".diff",".prof",".profile",".trace",".perf",".coverage",".egg-info",".egg",".mo",".pot",".setup",".paket.template"];function Ut(e){return hi.includes(e)}function Pt(e){let t=e.split("/").pop()||"";for(let r of Gd)if(t.endsWith(r))return!0;if(Dd.includes(t))return!0;let n=e.split("/");for(let r of n)if(hi.includes(r))return!0;return!1}import{completeMetadata as vr}from"@octocodeai/octocode-core";var S=new Proxy({},{get(e,t){return vr.toolNames[t]},ownKeys(){return Object.keys(vr.toolNames)},getOwnPropertyDescriptor(e,t){let n=vr.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as $d}from"@octocodeai/octocode-core";var Fr=new Proxy({},{get(e,t){return $d.tools[t]?.description??""}});import{completeMetadata as Bd}from"@octocodeai/octocode-core";function Mr(e){return Object.prototype.hasOwnProperty.call(Bd.tools,e)}import{completeMetadata as Ud}from"@octocodeai/octocode-core";function Nr(){return Ud.baseSchema}var zd=new Proxy({},{get(e,t){return Nr()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Nr())]))},getOwnPropertyDescriptor(e,t){let n=Nr();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as Et}from"@octocodeai/octocode-core";function gi(e){return Et.tools[e]?.hints??{hasResults:[],empty:[]}}var NC=new Proxy({},{get(e,t){if(typeof t=="string")return t==="base"?Et.baseHints:gi(t)},ownKeys(){return["base",...Object.keys(Et.tools)]},getOwnPropertyDescriptor(e,t){if(typeof t=="string"&&(t==="base"||t in Et.tools))return{enumerable:!0,configurable:!0,value:t==="base"?Et.baseHints:gi(t)}}}),HC=new Proxy([],{get(e,t){return Et.genericErrorHints[t]}});var yi=Symbol.for("octocode.rawResponseChars");function $(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Ri(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function D(e,t){let n=typeof t=="number"?Ri(t):$(t);if(n===void 0)return e;try{Object.defineProperty(e,yi,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function q(e){if(!(typeof e!="object"||e===null))return Ri(e[yi])}function fn(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var bi=30;async function Si(e,t,n){let r=Pe("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await Ee(r,async()=>await jd(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function jd(e,t){try{let n=await ne(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(R=>R&&R.trim()).length===0)return await H(S.GITHUB_SEARCH_CODE,te.QUERY_EMPTY.code),{error:te.QUERY_EMPTY.message,type:"http",status:400};let r=ui(e);if(!r.trim())return await H(S.GITHUB_SEARCH_CODE,te.QUERY_EMPTY.code),{error:te.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:bi,100),i=e.page||1,s={q:r,per_page:o,page:i,headers:{Accept:"application/vnd.github.v3.text-match+json"}},a=await n.rest.search.code(s),c=await Vd(a.data.items,a.data.total_count),l=c.total_count,d=Math.min(l,1e3),u=Math.min(Math.ceil(d/o),10),m=Math.min(i,Math.max(1,u)),p=m<u,f=Math.min(d,u*o);return{data:{total_count:c.total_count,items:c.items,repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:m,totalPages:u,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:f,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:p,uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:fn(a.headers),rawResponseChars:$(a.data)}}catch(n){if(lt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:bi,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}async function Vd(e,t){let n=Wd(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Pt(p.path)),c=0,l=0,d=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],h=await Promise.allSettled((p.text_matches||[]).map(async E=>{let L=E.fragment,I=Qd.sanitizeContent(L||"",p.path);L=I.content,I.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${I.secretsDetected.join(", ")}`),I.warnings.length>0&&I.warnings.forEach(k=>r.add(`${p.path}: ${k}`));try{let k=await U.minifyContent(L||"",p.path);L=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}return{context:L||"",positions:E.matches?.map(k=>Array.isArray(k.indices)&&k.indices.length>=2?[k.indices[0],k.indices[1]]:[0,0])||[]}})),R=h.filter(E=>E.status==="fulfilled").map(E=>E.value),b=h.filter(E=>E.status==="rejected").length;b>0&&(l+=b);let g=p,C=Array.from(new Set(f));return{path:p.path,matches:R,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...g.last_modified_at&&{lastModifiedAt:g.last_modified_at},...C.length>0&&{minificationType:C.join(",")}}})),u=d.filter(p=>p.status==="fulfilled").map(p=>p.value);c=d.filter(p=>p.status==="rejected").length;let m={items:u,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function Wd(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var Ci=30;function Pi(e){let t={},n=e.license;n?.spdx_id&&n.spdx_id!=="NOASSERTION"&&(t.license=n.spdx_id);let r=e.homepage;return r&&(t.homepage=r),t}async function Ei(e,t,n){let r=Pe("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await Ee(r,async()=>await Yd(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Kd(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch{try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){return Z(p)}}let a=i.map(p=>{let h=p.full_name.split("/"),R=h[0]||"",b=h[1]||"";return{owner:R,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description.length>150?p.description.substring(0,150)+"...":p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...Pi(p)}}),c=a.length,l=c===n,d=(r-1)*n+c,u=s??d+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:u,reachableTotalMatches:d,totalMatchesKind:m,hasMore:l}},status:200,rawResponseChars:$(i)}}async function Yd(e,t){try{let n=await ne(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await Kd({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=di(e);if(!i.trim())return await H(S.GITHUB_SEARCH_REPOSITORIES,te.QUERY_EMPTY.code),{error:te.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Ci,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let d=await n.rest.search.repos(c),u=d.data.items.map(g=>{let E=g.full_name.split("/"),L=E[0]||"",I=E[1]||"";return{owner:L,repo:I,defaultBranch:g.default_branch,stars:g.stargazers_count||0,description:g.description?g.description.length>150?g.description.substring(0,150)+"...":g.description:"No description",url:g.html_url,createdAt:g.created_at,updatedAt:g.updated_at,pushedAt:g.pushed_at,visibility:g.visibility,...g.topics&&g.topics.length>0&&{topics:g.topics},...g.forks_count&&g.forks_count>0&&{forksCount:g.forks_count},...g.open_issues_count&&g.open_issues_count>0&&{openIssuesCount:g.open_issues_count},...g.language&&{language:g.language},...Pi(g)}}),m=d.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),h=Math.min(a,Math.max(1,f)),R=h<f,b=Math.min(p,f*s);return{data:{repositories:u,pagination:{currentPage:h,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:R}},status:200,headers:fn(d.headers),rawResponseChars:$(d.data)}}catch(n){if(lt(n)){let r=Math.min(e.limit||Ci,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}function Tt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function de(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function Xd(e){if(e.rateLimitRemaining===void 0&&e.retryAfter===void 0&&e.rateLimitReset===void 0)return;let t=e.rateLimitReset,n=t&&!isNaN(t)?Math.floor(t/1e3):Math.floor(Date.now()/1e3)+(e.retryAfter??3600);return{remaining:e.rateLimitRemaining??0,reset:n,retryAfter:e.retryAfter}}function je(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:Xd(e)}}function hn(e){return Zd(e)?je({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function Zd(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||Jd(n)}function Jd(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Ti(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function qd(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Ti(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope}}function ep(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Ti(e.pagination)},nonExistentScope:e.nonExistentScope}}async function wi(e,t,n=de){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await Si(s,t);return Tt(a)?je(a):a.data?{data:qd(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??$(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function _i(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await Ei(n,t);return"error"in r?hn(r)??{error:"Unknown GitHub API error",status:500,provider:"github"}:!("data"in r)||!r.data?{error:"No data returned from GitHub API",status:500,provider:"github"}:{data:ep(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??$(r.data)}}import{RequestError as xi}from"octokit";async function np(e,t,n,r,o,i,s,a){let c=await Oe(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let d=Z(t),u=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await ki(e,r,o,i,s||c);return m.length>0&&(d.hints=[...d.hints||[],...Oi(i,m)]),{...d,...u&&{scopesSuggestion:u}}}async function rp(e,t,n,r,o,i){let s=Z(t),a=await ki(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Oi(o,a)]),s}async function Ai(e,t){let n=e.replace(/\s/g,"");if(!n)return await H(S.GITHUB_FETCH_CONTENT,Ce.FILE_EMPTY.code),{error:Ce.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?(await H(S.GITHUB_FETCH_CONTENT,Ce.BINARY_FILE.code),{error:Ce.BINARY_FILE.message,type:"unknown",status:415}):{data:r.toString("utf-8"),status:200}}catch{return await H(S.GITHUB_FETCH_CONTENT,Ce.DECODE_FAILED.code),{error:Ce.DECODE_FAILED.message,type:"unknown",status:422}}}async function Li(e,t,n,r,o){try{let i=await e.rest.git.getBlob({owner:t,repo:n,file_sha:r}),{content:s,encoding:a}=i.data;return a==="base64"?Ai(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return Z(i)}}async function op(e,t,n,r,o,i){try{let s=r.split("/").slice(0,-1).join("/"),a=r.split("/").pop();if(!a)return{error:`Cannot determine file name from path: ${r}`,type:"unknown",status:400};let c=o||await Oe(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let d=l.data.find(m=>m.name===a&&m.type==="file");if(!d)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let u=await Li(e,t,n,d.sha,r);return"error"in u?u:{data:{rawContent:u.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return Z(s)}}async function Ii(e,t){try{let n=await ne(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(u){if(u instanceof xi&&u.status===404)if(s){let m=await np(n,u,a,r,o,i,s,t);if("result"in m)c=m.result,l=m.actualBranch;else return m}else return await rp(n,u,r,o,i,s);else{if(u instanceof xi&&u.status===413)return await op(n,r,o,i,s||l,t);throw u}}let d=c.data;if(Array.isArray(d))return await H(S.GITHUB_FETCH_CONTENT,Ce.PATH_IS_DIRECTORY.code),{error:Ce.PATH_IS_DIRECTORY.message(S.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let u=typeof d.content=="string"?d.content:"",m=d.size??0,p;if(u.length>0)p=await Ai(u,i);else if(m>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)p=await Li(n,r,o,d.sha,i);else return await H(S.GITHUB_FETCH_CONTENT,Ce.FILE_EMPTY.code),{error:Ce.FILE_EMPTY.message,type:"unknown",status:404};if("error"in p)return p;if(!l&&!s)try{l=await Oe(r,o,t)}catch{}return{data:{rawContent:p.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:$(d)}}return await H(S.GITHUB_FETCH_CONTENT,Ce.UNSUPPORTED_TYPE.code),{error:Ce.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(n){return Z(n)}}function Oi(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function ki(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],d=c.find(p=>p.name.toLowerCase()===s.toLowerCase());d&&l.push(d.path);let u=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(u+".")).forEach(p=>l.push(p.path)),l.length===0&&u.length>=3&&c.filter(f=>{let h=f.name.replace(/\.[^/.]+$/,"");return h!==u&&h.length>=3&&(u.startsWith(h)||h.startsWith(u))}).forEach(f=>l.push(f.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}import{getConfigSync as ip}from"octocode-shared";import{DEFAULT_OUTPUT_CONFIG as sp}from"octocode-shared";function $e(){try{return ip().output.pagination.defaultCharLength}catch{return sp.pagination.defaultCharLength}}import{ContentSanitizer as Hi}from"octocode-security/contentSanitizer";function Hr(e,t){return U.byteToCharOffset(e,t)}function vi(e,t){return U.charToByteOffset(e,t)}function Fi(e){return U.charToByteOffset(e,e.length)}function Dr(e,t,n,r){return U.sliceContent(e,t,n,r)}function wt(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Fi(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,d,u,m,p,f,h;if(o==="bytes"){let R=Math.min(t,s),b=Math.min(R+n,s);u=Hr(e,R),m=Hr(e,b),m<i&&vi(e,m)<b&&(m+=1);let g=Dr(e,u,m-u);c=g.text,u=g.charOffset,m=g.charOffset+g.charLength,l=g.byteOffset,d=g.byteOffset+g.byteLength,p=d<s;let C=r.actualOffset??R;f=Math.floor(C/a)+1,h=Math.max(f,Math.ceil(s/a))}else{let R=Dr(e,t,n);c=R.text,u=R.charOffset,m=R.charOffset+R.charLength,l=R.byteOffset,d=R.byteOffset+R.byteLength,p=m<i;let b=r.actualOffset??u;f=Math.floor(b/a)+1,h=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:d-l,totalBytes:s,nextByteOffset:p?d:void 0,charOffset:u,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:h}}function Mi(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}var ap=8e3,cp="__octocode_generic__.unknown";function lp(e){return e&&e.trim().length>0?e:cp}function Ni(e,t){return U.getSemanticBoundaryOffsets(e,lp(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function up(e,t){let n=e.indexOf(`
|
|
9
|
-
`,t);return n===-1?void 0:n+1}function gn(e){let t=e.trimEnd().split(`
|
|
10
|
-
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function yn(e,t,n){let r=up(e,Math.max(0,t));if(r!==void 0)return Ni(e,n).find(o=>o>=r&&o>t)}function Rn(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=Ni(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(d=>d>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=ap?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function bn(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let d=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${d}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
11
|
-
|
|
12
|
-
`).length
|
|
13
|
-
`),
|
|
14
|
-
`)
|
|
15
|
-
`)
|
|
8
|
+
import{z as as}from"zod";var zp=null;function Qp(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}
|
|
9
|
+
`)}function Xe(e){function t(n,r,o){let i={level:n,module:e,message:r,...o&&{data:o}};(zp??Qp)(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 tt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function xt(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 Hn(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Kt=new Map,$p=300*1e3;function jp(e){let t=tt(e),n=Kt.get(t);return!n||Date.now()-n.cachedAt>=$p?!1:n.credentials?!xt(n.credentials):!0}function Xr(e){e?Kt.delete(tt(e)):Kt.clear()}function hs(e){let t=tt(e);if(jp(t))return Kt.get(t).credentials}function ys(e,t){let n=tt(e);Kt.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as Cs,readFileSync as Ts,writeFileSync as Ps,unlinkSync as hE,statSync as tm,chmodSync as nm}from"node:fs";import{createCipheriv as rm,createDecipheriv as om,randomBytes as Es}from"node:crypto";import{existsSync as Kp,mkdirSync as Yp}from"node:fs";import{join as ue}from"node:path";import Gn from"node:os";import Vp from"node:path";var Un=Gn.platform()==="win32",Jr=Gn.platform()==="darwin",Wp=Gn.platform()==="linux",At=Gn.homedir();function Zr(){return Un?process.env.APPDATA||Vp.join(At,"AppData","Roaming"):At}var qr=".octocode",Xp=448;function Jp(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function Zp(){return Un?ue(Zr(),qr):Jr?ue(At,qr):ue(Jp("XDG_CONFIG_HOME")??ue(At,".config"),qr)}var Re=Zp(),be={home:Re,config:ue(Re,".octocoderc"),credentials:ue(Re,"credentials.json"),key:ue(Re,".key"),session:ue(Re,"session.json"),stats:ue(Re,"stats.json"),tmp:ue(Re,"tmp"),clone:ue(Re,"tmp","clone"),tree:ue(Re,"tmp","tree"),binary:ue(Re,"tmp","binary"),repos:ue(Re,"tmp","clone"),logs:ue(Re,"logs"),unzip:ue(Re,"tmp","unzip"),cliConfig:ue(Re,"config.json"),lspConfig:ue(Re,"lsp-servers.json")};function Rs(){Kp(be.home)||Yp(be.home,{recursive:!0,mode:Xp})}import{z as le}from"zod";var qp=le.object({token:le.string(),tokenType:le.literal("oauth"),scopes:le.array(le.string()).optional(),refreshToken:le.string().optional(),expiresAt:le.string().optional(),refreshTokenExpiresAt:le.string().optional()}),em=le.object({hostname:le.string(),username:le.string(),token:qp,gitProtocol:le.enum(["ssh","https"]),createdAt:le.string(),updatedAt:le.string()}),bs=le.object({version:le.number(),credentials:le.record(le.string(),em)});var Ss=Xe("token-storage");function im(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 ws=be.home,mt=be.credentials,pt=be.key,_s="aes-256-gcm",sm=16;function ft(){Rs()}function xs(){if(ft(),Cs(pt))return tm(pt).mode&511&63&&nm(pt,384),Buffer.from(Ts(pt,"utf8"),"hex");let e=Es(32);return Ps(pt,e.toString("hex"),{mode:384}),e}function eo(e){let t=xs(),n=Es(sm),r=rm(_s,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 to(e){let t=xs(),[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=om(_s,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function Bn(){if(ft(),!Cs(mt))return{version:1,credentials:{}};try{let e=Ts(mt,"utf8"),t=to(e),n=JSON.parse(t),r=bs.safeParse(n);return r.success?r.data:(Ss.warn("Credentials file has invalid format \u2014 starting fresh",{file:mt}),{version:1,credentials:{}})}catch(e){let t=e instanceof Error&&e.message?im(e.message):void 0;return Ss.warn("Could not read credentials file \u2014 you may need to login again",{file:mt,...t&&{reason:t}}),{version:1,credentials:{}}}}function As(e){ft();let t=eo(JSON.stringify(e,null,2));Ps(mt,t,{mode:384})}import{refreshToken as am}from"@octokit/oauth-methods";import{request as cm}from"@octokit/request";var Yt="178c6fc778ccc68e1d6a",Lt="github.com";function um(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 lm(e){return e==="github.com"||e===Lt?"https://api.github.com":`https://${e}/api/v3`}async function Ls(e,t=Lt,n=Yt){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(Hn(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await am({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:cm.defaults({baseUrl:lm(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?um(o.message):"Token refresh failed"}}}async function Os(e,t=Lt,n=Yt){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!xt(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Ls(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 no=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN"];function Is(){for(let e of no){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}import{execFile as dm}from"child_process";var pm=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function ro(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=pm.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;dm("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var oo=null;function ks(e){oo=e}function mm(){if(!oo)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return oo}async function zn(e){let t=e?.hostname??Lt,n=e?.clientId??Yt,r=e?.getGhCliToken??ro,o=Is();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await mm().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}var Sm=Xe("token-storage");async function vs(e){let t=tt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Bn();return r.credentials[t]=n,As(r),Xr(t),{success:!0}}catch(r){let o=r instanceof Error?r.message:String(r);throw Sm.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 io(e="github.com",t){let n=tt(e);if(!t?.bypassCache){let i=hs(n);if(i!==void 0)return i}let o=Bn().credentials[n]||null;return ys(n,o),o}async function Fs(e,t){let n=await io(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await vs(n),!0):!1}async function Ms(e,t){return Os({getCredentials:io,updateToken:Fs},e,t)}ks({getTokenWithRefresh:Ms});import{randomUUID as ww}from"node:crypto";import{existsSync as Us,readFileSync as Bs,writeFileSync as wm,unlinkSync as uw,renameSync as _m}from"node:fs";import{z as B}from"zod";var Cm=B.object({rawChars:B.number(),responseChars:B.number(),savedChars:B.number(),calls:B.number()}),Tm=B.object({hits:B.record(B.string(),B.number()).default({}),rateLimits:B.number().default(0)}),Qn=B.record(B.string(),B.number()).default({}),Pm=B.object({toolCalls:B.number(),errors:B.number(),rateLimits:B.number(),rateLimitsByProvider:Qn,rawChars:B.number(),responseChars:B.number(),savedChars:B.number(),charSavingsCalls:B.number(),githubCacheHits:B.number(),githubCacheRateLimits:B.number(),packageRegistryFailures:B.number().default(0),packageRegistryFailuresByRegistry:Qn}),$n=B.object({toolCalls:B.number(),errors:B.number(),rateLimits:B.number(),rateLimitsByProvider:Qn,charsSavedByTool:B.record(B.string(),Cm).default({}),githubCacheHits:Tm.default({hits:{},rateLimits:0}),packageRegistryFailures:Qn,totalUsage:Pm.optional()}),Ns=B.object({version:B.literal(1),sessionId:B.string(),createdAt:B.string(),lastActiveAt:B.string(),stats:$n.optional()}),Ds=B.object({version:B.literal(1),stats:$n});function Hs(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Em(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:Hs(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Hs(o),packageRegistryFailuresByRegistry:o}}function Je(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Em(t)}}function so(){return Je({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var zs=Xe("session"),Ot=be.session,It=be.stats;function Gs(e,t){let n=`${e}.tmp`;wm(n,JSON.stringify(t,null,2),{mode:384}),_m(n,e)}function xm(e){let{stats:t,...n}=e;return n}function Am(e){let t=JSON.parse(e),n=Ds.safeParse(t);if(n.success)return Je(n.data.stats);let r=$n.safeParse(t);return r.success?Je(r.data):null}function Lm(e){let t=e?Je(e):so();if(!Us(It))return t;try{let n=Bs(It,"utf8"),r=Am(n);return r||(zs.warn("Stats file has invalid format",{file:It}),t)}catch{return t}}function ao(e){ft(),Gs(It,{version:e.version,stats:Je(e.stats)}),Gs(Ot,xm(e))}function Qs(){if(!Us(Ot))return null;try{let e=Bs(Ot,"utf8"),t=JSON.parse(e),n=Ns.safeParse(t);return n.success?{...n.data,stats:Lm(n.data.stats)}:(zs.warn("Session file has invalid format",{file:Ot}),null)}catch{return null}}var Om=6e4,nt=null,Xt=!1,co=null,$s=!1,js=null,Vs=null,Ws=null,uo=!1;function Im(){$s||($s=!0,js=()=>{jn()},Vs=()=>{jn()},Ws=()=>{jn()},process.on("exit",js),process.on("SIGINT",Vs),process.on("SIGTERM",Ws))}function km(){co||(co=setInterval(()=>{Xt&&nt&&(ao(nt),Xt=!1)},Om),co.unref())}function Ks(){if(nt)return nt;let e=Qs();return e&&(nt=e),e}function Ys(e){nt=e,Xt=!0,Im(),km()}function jn(){if(!uo&&Xt&&nt){uo=!0;try{ao(nt),Xt=!1}catch{}finally{uo=!1}}}function vm(e){return Je(e)}function Fm(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 Xs(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 Mm(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 Vn(e){let t=Ks();if(!t)return{success:!1,session:null};let n=vm(t.stats),r=Je({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Xs(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Fm(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:Mm(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Xs(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Ys(o),{success:!0,session:o}}function lo(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Vn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function po(e,t=1){return Vn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}var Wn={apiUrl:"https://api.github.com"},gt={enabled:!1,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},kt={enabled:null,enableAdditional:null,disabled:null},Jt={timeout:3e4,maxRetries:3},Kn={logging:!0},Yn={configPath:void 0},rt={format:"yaml",pagination:{defaultCharLength:2e4}},mo={version:1,github:Wn,local:gt,tools:kt,network:Jt,telemetry:Kn,lsp:Yn,output:rt},Zt=5e3,qt=3e5,en=0,tn=10,nn=1e3,rn=5e4;import{existsSync as Js,readFileSync as Bm}from"node:fs";import{z as q}from"zod";var fo=q.looseObject({$schema:q.string().optional(),version:q.number().int().optional(),github:q.record(q.string(),q.unknown()).optional(),local:q.record(q.string(),q.unknown()).optional(),tools:q.record(q.string(),q.unknown()).optional(),network:q.record(q.string(),q.unknown()).optional(),telemetry:q.record(q.string(),q.unknown()).optional(),lsp:q.record(q.string(),q.unknown()).optional(),output:q.record(q.string(),q.unknown()).optional()});var go=be.config;function zm(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]!==`
|
|
10
|
+
`;)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 Qm(e){let t=zm(e);return JSON.parse(t)}function ho(){return Js(go)}function yo(){let e=go;if(!Js(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=Bm(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=Qm(t),r=fo.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 vt(){return be.home}function $m(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 So(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 Co(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function Zs(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 jm(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 Ro(e,t){return e===void 0||e===null?null:Zs(e,t)}function qs(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function Vm(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=$m(e.apiUrl,"github.apiUrl");r&&t.push(r)}function Wm(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=Co(n.enabled,"local.enabled");r&&t.push(r);let o=Co(n.enableClone,"local.enableClone");o&&t.push(o);let i=Zs(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=jm(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=qs(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 Km(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=Ro(n.enabled,"tools.enabled");r&&t.push(r);let o=Ro(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=Ro(n.disabled,"tools.disabled");i&&t.push(i)}function Ym(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=So(n.timeout,"network.timeout",Zt,qt);r&&t.push(r);let o=So(n.maxRetries,"network.maxRetries",en,tn);o&&t.push(o)}function Xm(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("telemetry: Must be an object");return}let r=Co(e.logging,"telemetry.logging");r&&t.push(r)}function Jm(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=qs(e.configPath,"lsp.configPath");r&&t.push(r)}function Zm(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=So(r.defaultCharLength,"output.pagination.defaultCharLength",nn,rn);o&&t.push(o)}}function To(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}`)),Vm(r.github,t),Wm(r.local,t),Km(r.tools,t),Ym(r.network,t),Xm(r.telemetry,t),Jm(r.lsp,t),Zm(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 qm="__octocodeRuntimeSurface__";function Po(){return globalThis[qm]??"mcp"}function ea(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 Eo(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function Xn(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function ta(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!=="")return!(t==="false"||t==="0")}function na(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||Wn.apiUrl}}function ra(e){let t=Po()==="cli",n=ea(process.env.ENABLE_LOCAL),r=ea(process.env.ENABLE_CLONE),o=Xn(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??(t?!0:gt.enabled),enableClone:r??e?.enableClone??(t?!0:gt.enableClone),allowedPaths:o??e?.allowedPaths??gt.allowedPaths,workspaceRoot:i??e?.workspaceRoot??gt.workspaceRoot}}function oa(e){let t=Xn(process.env.TOOLS_TO_RUN),n=Xn(process.env.ENABLE_TOOLS),r=Xn(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??kt.enabled,enableAdditional:n??e?.enableAdditional??kt.enableAdditional,disabled:r??e?.disabled??kt.disabled}}function ia(e){let t=Eo(process.env.REQUEST_TIMEOUT),n=Eo(process.env.MAX_RETRIES),r=t??e?.timeout??Jt.timeout;r=Math.max(Zt,Math.min(qt,r));let o=n??e?.maxRetries??Jt.maxRetries;return o=Math.max(en,Math.min(tn,o)),{timeout:r,maxRetries:o}}function sa(e){return{logging:ta(process.env.LOG)??e?.logging??Kn.logging}}function aa(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??Yn.configPath}}var ef=new Set(["yaml","json"]);function ca(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=Eo(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||rt.format,o=n??e?.pagination?.defaultCharLength??rt.pagination.defaultCharLength,i=Math.max(nn,Math.min(rn,o));return{format:ef.has(r)?r:rt.format,pagination:{defaultCharLength:i}}}var Jn=Xe("octocode-config");function wo(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??mo.version,github:na(e?.github),local:ra(e?.local),tools:oa(e?.tools),network:ia(e?.network),telemetry:sa(e?.telemetry),lsp:aa(e?.lsp),output:ca(e?.output),source:o,configPath:n?t:void 0}}function _o(){let e=yo();if(e.success&&e.config){let t=To(e.config);if(t.warnings.length>0)for(let n of t.warnings)Jn.warn(`Warning: ${n}`);if(!t.valid){for(let n of t.errors)Jn.warn(`Validation error: ${n}`);return Jn.warn("Config file has validation errors \u2014 falling back to defaults with env overrides"),wo(void 0)}return wo(e.config,e.path)}return e.error&&ho()&&Jn.warn(e.error),wo(void 0)}var Zn=null,ua=0,tf=6e4;function ge(){let e=Date.now();return Zn&&e-ua<tf||(Zn=_o(),ua=e),Zn}import{existsSync as cf,readdirSync as uf,lstatSync as lf}from"node:fs";import{join as df}from"node:path";function qn(e){if(!cf(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=uf(r)}catch{continue}for(let i of o){let s=df(r,i);try{let a=lf(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var ht="16.5.1";var xo={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},ot={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"}},it={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})`}},mf={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"}},Pe={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}`}},$e={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}`}},ff={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}`}},st={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"}},Ao={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}`}},$_={...xo,...ot,...it,...mf,...Pe,...$e,...ne,...ff,...st,...Ao};import{maskSensitiveData as gf}from"@octocodeai/octocode-engine/mask";var sn=null,on=null,hf=zn;var yf=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"]);async function da(){try{let e=await hf({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:yf.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function pa(){if(sn!==null)return;if(on!==null)return on;let e=(async()=>{let t=ge(),n=await da();sn={version:ht,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}})();on=e;try{await e}catch(t){throw on===e&&(sn=null,on=null),t}}function ma(){if(!sn){let e=gf(xo.NOT_INITIALIZED.message);throw new Error(e)}return sn}async function fa(){return(await da()).token}function er(){return"github"}function Lo(){let e=ge().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as lg}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as Rf}from"node:module";var bf=Rf(import.meta.url),ga="@octocodeai/octocode-engine",tr,Sf=()=>bf(ga),Oo=class extends Error{constructor(n){super(`Failed to load native dependency ${ga}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function V(){if(tr)return tr;try{return tr=Sf(),tr}catch(e){throw new Oo(e)}}var O={applyContentViewMinification(e,t){return V().applyContentViewMinification(e,t)},applyMinification(e,t){return V().applyMinification(e,t)},minifyContent(e,t){return V().minifyContent(e,t)},minifyContentSync(e,t){return V().minifyContentSync(e,t)},minifyContentResult(e,t){return V().minifyContentResult(e,t)},minifyMarkdownCore(e){return V().minifyMarkdownCore(e)},extractSignatures(e,t){return V().extractSignatures(e,t)},extractJsSymbols(e,t){return V().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return V().findInFileReferences(e,t,n,r)},getSupportedJsTsExtensions(){return V().getSupportedJsTsExtensions()},structuralSearch(e,t,n,r){return V().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return V().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return V().getSupportedStructuralExtensions()},inspectBinaryNative(e){return V().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return V().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return V().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return V().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return V().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return V().parseRipgrepJson(e,t)},searchRipgrep(e){return V().searchRipgrep(e)},queryFileSystem(e){return V().queryFileSystem(e)},extractMatchingLines(e,t,n){return V().extractMatchingLines(e,t,n)},filterPatch(e,t){return V().filterPatch(e,t)},charToByteOffset(e,t){return V().charToByteOffset(e,t)},byteToCharOffset(e,t){return V().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return V().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return V().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return V().SIGNATURES_ONLY_HINT}};import{Octokit as Pf}from"octokit";import{throttling as Ef}from"@octokit/plugin-throttling";import{createHash as wf}from"crypto";import{completeMetadata as Cf}from"@octocodeai/octocode-core";var Ee="lspGetSemantics",ha=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation"];function Ft(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Io(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 de=Cf.toolNames,nx=new Set([de.LOCAL_RIPGREP,de.LOCAL_FETCH_CONTENT,de.LOCAL_FIND_FILES,de.LOCAL_VIEW_STRUCTURE,de.LOCAL_BINARY_INSPECT,Ee]);var Tf=null;function ko(){return Tf}async function v(e,t){let n=ko();n&&await n.logError(e,t)}async function at(e){let t=ko();t&&await t.logRateLimit(e)}function ya(e){let t=ko();t&&t.logPackageRegistryFailure(e)}function _f(e){return wf("sha256").update(e).digest("hex").substring(0,16)}var xf=Pf.plugin(Ef),Af=300*1e3,vo=50,Lf=60*1e3;function Fo(e){return Date.now()-e.createdAt>Af}var Ge=new Map,an=null,cn=null;function Pa(){for(let[e,t]of Ge.entries())Fo(t)&&Ge.delete(e);if(Ge.size>vo){let e=[...Ge.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=Ge.size-vo;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ge.delete(r[0])}}}function Of(){cn||(cn=setInterval(Pa,Lf),typeof cn=="object"&&"unref"in cn&&cn.unref())}var Ra=3,ba=60;function Sa(e,t,n){at({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var If=()=>({onRateLimit:(e,t,n,r)=>(Sa("primary",e,t),r<Ra&&e<ba),onSecondaryRateLimit:(e,t,n,r)=>(Sa("secondary",e,t),r<Ra&&e<ba)});function Ca(e){let t=ma(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${ht}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:If(),log:r,...e&&{auth:e}};return new xf(o)}async function re(e){if(Of(),e?.token){let n=_f(e.token),r=Ge.get(n);if(r&&!Fo(r))return r.client;Ge.size>=vo&&Pa();let o=Ca(e.token);return Ge.set(n,{client:o,createdAt:Date.now()}),o}let t=Ge.get("DEFAULT");return t&&!Fo(t)?t.client:an||(an=(async()=>{try{let n=await fa(),r=Ca(n??void 0);return Ge.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{an=null}})(),an)}var kf=200,un=new Map;async function ke(e,t,n){let r=`${e}/${t}`,o=un.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 Ta(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}),Ta(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 Ta(e,t){if(un.size>=kf){let n=un.keys().next().value;n!==void 0&&un.delete(n)}un.set(e,t)}import{RequestError as _a}from"octokit";var N={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"},ae={[N.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."},[N.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."},[N.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},[N.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)."},[N.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."},[N.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."},[N.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."},[N.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."},[N.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."},[N.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Ea={401:N.AUTH_REQUIRED,403:N.FORBIDDEN_PERMISSIONS,404:N.NOT_FOUND,422:N.INVALID_REQUEST,502:N.SERVER_UNAVAILABLE,503:N.SERVER_UNAVAILABLE,504:N.SERVER_UNAVAILABLE},Mo={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},No={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},nr={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};function Se(e){return t=>{}}function wa(e,t){return n=>t}var vf=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function yt(e){if(!(e instanceof _a)||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 vf.some(o=>r.includes(o))})}function X(e){return e instanceof _a?Ff(e):e instanceof Error?zf(e):{error:typeof e=="string"?e:ae[N.UNKNOWN].message,type:"unknown"}}function Ff(e){let{status:t,message:n,response:r}=e;if(t===403)return Nf(n,r);if(t===429)return Mf(n,r);let o=Ea[t];return o?Bf(o,t):Mt(N.UNKNOWN,{error:n||ae[N.UNKNOWN].message,status:t})}function Do(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function Mf(e,t){let n=t?.headers,r=Do(n,"retry-after"),o=Do(n,"x-ratelimit-reset"),i=Do(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+nr.RESET_BUFFER_SECONDS,0):void 0);return at({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}).catch(Se("rate-limit logging")),Mt(N.RATE_LIMIT_PRIMARY,{error:e||ae[N.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ae[N.RATE_LIMIT_PRIMARY].suggestion})}function Nf(e,t){let n=t?.headers;if(No.SECONDARY.test(e))return Df(n);let r=n?.["x-ratelimit-remaining"],o=Uf(t);return r!==void 0&&String(r)==="0"||o?Hf(n):Gf(n)}function Df(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?nr.SECONDARY_FALLBACK_SECONDS:t;return at({limit_type:"secondary",retry_after_seconds:n,provider:"github"}).catch(Se("rate-limit logging")),Mt(N.RATE_LIMIT_SECONDARY,{error:ae[N.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ae[N.RATE_LIMIT_SECONDARY].suggestion})}function Hf(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)+nr.RESET_BUFFER_SECONDS,0):void 0,i=r?ae[N.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ae[N.RATE_LIMIT_PRIMARY].messageWithoutTime;return at({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}).catch(Se("rate-limit logging")),Mt(N.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ae[N.RATE_LIMIT_PRIMARY].suggestion})}function Gf(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ae[N.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Qf(String(t),String(n))),Mt(N.FORBIDDEN_PERMISSIONS,{error:ae[N.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Uf(e){return e?.data?.errors?.some(n=>n.type===No.GRAPHQL_TYPE)??!1}function Bf(e,t){let n=ae[e];return Mt(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function zf(e){return Mo.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ae[N.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ae[N.NETWORK_CONNECTION_FAILED].suggestion}:Mo.TIMEOUT.some(t=>e.message.includes(t))?{error:ae[N.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ae[N.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Mt(e,t){return{type:"http",...t}}function Qf(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?ae[N.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ae[N.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function $f(e){return`user:${e}`}var jf=/[@/]/,Vf=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Wf=/^[A-Za-z0-9_-]+$/;function xa(e){return e.startsWith('"')||Wf.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var ln=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($f(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=jf.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},Ho=class extends ln{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(xa))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Vf):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}},Go=class extends ln{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(xa)),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}},Uo=class extends ln{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 Aa(e){return new Ho().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function La(e){return new Go().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function Oa(e){return new Uo().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ia(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 Kf from"node-cache";import Yf from"crypto";var Xf="v1",Jf=300*1e3,Rt=new Kf({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Nt={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},ka={"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},dn=new Map;function Zf(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function qf(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function eg(e){let t=Zf(e);if(!(!t||!qf(t)))try{po(t,1)}catch{}}function tg(){let e=Date.now();for(let[t,n]of dn.entries())e-n.startedAt>Jf&&dn.delete(t)}var ng=new Set([]);function rg(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(ng.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function we(e,t,n){let r=Bo(rg(t)),o=n?`${n}:${r}`:r,i=Yf.createHash("sha256").update(o).digest("hex");return`${Xf}-${e}:${i}`}function Bo(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=>Bo(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Bo(i,t)}`}).join(",")}}`)}function og(e){return ka[e]||ka.default}function ig(e,t,n){try{return Rt.set(e,t,n),Nt.sets++,Nt.totalKeys=Rt.keys().length,!0}catch{try{let r=Rt.keys();for(let o of r)Rt.get(o);return Rt.set(e,t,n),Nt.sets++,Nt.totalKeys=Rt.keys().length,!0}catch{return!1}}}async function _e(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Rt.get(e);if(i!==void 0)return Nt.hits++,eg(e),i}catch{}tg();let r=dn.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Nt.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=og(u)}ig(e,i,a)}return i}finally{dn.delete(e)}})();return dn.set(e,{promise:o,startedAt:Date.now()}),o}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as kx,DISCOVERY_IGNORED_FILE_NAMES as vx,DISCOVERY_IGNORED_FOLDER_NAMES as Fx,getDiscoveryExtension as va,shouldIgnoreDiscoveryDir as pn,shouldIgnoreDiscoveryFile as Dt}from"@octocodeai/octocode-engine/security";import{completeMetadata as zo}from"@octocodeai/octocode-core";var S=new Proxy({},{get(e,t){return zo.toolNames[t]},ownKeys(){return Object.keys(zo.toolNames)},getOwnPropertyDescriptor(e,t){let n=zo.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as sg}from"@octocodeai/octocode-core";var Qo=new Proxy({},{get(e,t){return sg.tools[t]?.description??""}});import{completeMetadata as ag}from"@octocodeai/octocode-core";function $o(e){return Object.prototype.hasOwnProperty.call(ag.tools,e)}import{completeMetadata as cg}from"@octocodeai/octocode-core";function jo(){return cg.baseSchema}var ug=new Proxy({},{get(e,t){return jo()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(jo())]))},getOwnPropertyDescriptor(e,t){let n=jo();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});var Fa=Symbol.for("octocode.rawResponseChars");function F(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Ma(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function D(e,t){let n=typeof t=="number"?Ma(t):F(t);if(n===void 0)return e;try{Object.defineProperty(e,Fa,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ee(e){if(!(typeof e!="object"||e===null))return Ma(e[Fa])}function rr(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 Na=30;async function Da(e,t,n){let r=we("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await _e(r,async()=>await dg(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function dg(e,t){try{let n=await re(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(b=>b&&b.trim()).length===0)return await v(S.GITHUB_SEARCH_CODE,ne.QUERY_EMPTY.code),{error:ne.QUERY_EMPTY.message,type:"http",status:400};let r=Aa(e);if(!r.trim())return await v(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:Na,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 pg(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:rr(a.headers),rawResponseChars:F(a.data)}}catch(n){if(yt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Na,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 X(n)}}async function pg(e,t){let n=mg(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Dt(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 w=>{let T=w.fragment,A=lg.sanitizeContent(T||"",p.path);T=A.content,A.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${A.secretsDetected.join(", ")}`),A.warnings.length>0&&A.warnings.forEach(G=>r.add(`${p.path}: ${G}`));try{let G=await O.minifyContent(T||"",p.path);T=G.content,G.failed?o=!0:G.type!=="failed"&&(f.push(G.type),i.push(G.type))}catch{o=!0}return{context:T||"",positions:w.matches?.map(G=>Array.isArray(G.indices)&&G.indices.length>=2?[G.indices[0],G.indices[1]]:[0,0])||[]}})),h=g.filter(w=>w.status==="fulfilled").map(w=>w.value),b=g.filter(w=>w.status==="rejected").length;b>0&&(u+=b);let R=p,C=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},...R.last_modified_at&&{lastModifiedAt:R.last_modified_at},...C.length>0&&{minificationType:C.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 mg(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var Ha=30;function Ga(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 Ua(e,t,n){let r=we("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await _e(r,async()=>await gg(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function fg(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 X(p)}}let a=i.map(p=>{let g=p.full_name.split("/"),h=g[0]||"",b=g[1]||"";return{owner:h,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},...Ga(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:F(i)}}async function gg(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 fg({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=La(e);if(!i.trim())return await v(S.GITHUB_SEARCH_REPOSITORIES,ne.QUERY_EMPTY.code),{error:ne.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Ha,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(R=>{let w=R.full_name.split("/"),T=w[0]||"",A=w[1]||"";return{owner:T,repo:A,defaultBranch:R.default_branch,stars:R.stargazers_count||0,description:R.description?R.description.length>150?R.description.substring(0,150)+"...":R.description:"No description",url:R.html_url,createdAt:R.created_at,updatedAt:R.updated_at,pushedAt:R.pushed_at,visibility:R.visibility,...R.topics&&R.topics.length>0&&{topics:R.topics},...R.forks_count&&R.forks_count>0&&{forksCount:R.forks_count},...R.open_issues_count&&R.open_issues_count>0&&{openIssuesCount:R.open_issues_count},...R.language&&{language:R.language},...Ga(R)}}),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,b=Math.min(p,f*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:h,...h?{nextPage:g+1}:{}}},status:200,headers:rr(l.headers),rawResponseChars:F(l.data)}}catch(n){if(yt(n)){let r=Math.min(e.limit||Ha,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 X(n)}}function Ht(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function ce(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 hg(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 Ze(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:hg(e)}}function or(e){return yg(e)?Ze({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 yg(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||Rg(n)}function Rg(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Ba(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 bg(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,...Ba(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function Sg(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,...Ba(e.pagination)},nonExistentScope:e.nonExistentScope}}async function za(e,t,n=ce){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 Da(s,t);return Ht(a)?Ze(a):a.data?{data:bg(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??F(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Qa(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 Ua(n,t);return"error"in r?or(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:Sg(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??F(r.data)}}import{RequestError as $a}from"octokit";async function Tg(e,t,n,r,o,i,s,a){let c=await ke(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=X(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 Ka(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Wa(i,m)]),{...l,...d&&{scopesSuggestion:d}}}async function Pg(e,t,n,r,o,i){let s=X(t),a=await Ka(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Wa(o,a)]),s}async function ja(e,t){let n=e.replace(/\s/g,"");if(!n)return await v(S.GITHUB_FETCH_CONTENT,Pe.FILE_EMPTY.code),{error:Pe.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?(await v(S.GITHUB_FETCH_CONTENT,Pe.BINARY_FILE.code),{error:Pe.BINARY_FILE.message,type:"unknown",status:415}):{data:r.toString("utf-8"),status:200}}catch{return await v(S.GITHUB_FETCH_CONTENT,Pe.DECODE_FAILED.code),{error:Pe.DECODE_FAILED.message,type:"unknown",status:422}}}async function Va(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"?ja(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return X(i)}}async function Eg(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 ke(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 Va(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 X(s)}}async function ir(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,u=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof $a&&d.status===404)if(s){let m=await Tg(n,d,a,r,o,i,s,t);if("result"in m)c=m.result,u=m.actualBranch;else return m}else return await Pg(n,d,r,o,i,s);else{if(d instanceof $a&&d.status===413)return await Eg(n,r,o,i,s||u,t);throw d}}let l=c.data;if(Array.isArray(l))return await v(S.GITHUB_FETCH_CONTENT,Pe.PATH_IS_DIRECTORY.code),{error:Pe.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 ja(d,i);else if(m>0&&"sha"in l&&typeof l.sha=="string"&&l.sha)p=await Va(n,r,o,l.sha,i);else return await v(S.GITHUB_FETCH_CONTENT,Pe.FILE_EMPTY.code),{error:Pe.FILE_EMPTY.message,type:"unknown",status:404};if("error"in p)return p;if(!u&&!s)try{u=await ke(r,o,t)}catch{}return{data:{rawContent:p.data,branch:u||void 0,resolvedRef:u||s||"HEAD"},status:200,rawResponseChars:F(l)}}return await v(S.GITHUB_FETCH_CONTENT,Pe.UNSUPPORTED_TYPE.code),{error:Pe.UNSUPPORTED_TYPE.message(l.type),type:"unknown",status:415}}catch(n){return X(n)}}function Wa(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 Ka(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[]}}function Be(){try{return ge().output.pagination.defaultCharLength}catch{return rt.pagination.defaultCharLength}}import{ContentSanitizer as qa}from"@octocodeai/octocode-engine/contentSanitizer";function mn(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function bt(e){return mn(e).length}function Vo(e,t){return O.byteToCharOffset(e,t)}function Ya(e,t){return O.charToByteOffset(e,t)}function Xa(e){return O.charToByteOffset(e,e.length)}function Wo(e,t,n,r){return O.sliceContent(e,t,n,r)}function Gt(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Xa(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),b=Math.min(h+n,s);d=Vo(e,h),m=Vo(e,b),m<i&&Ya(e,m)<b&&(m+=1);let R=Wo(e,d,m-d);c=R.text,d=R.charOffset,m=R.charOffset+R.charLength,u=R.byteOffset,l=R.byteOffset+R.byteLength,p=l<s;let C=r.actualOffset??h;f=Math.floor(C/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let h=Wo(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 b=r.actualOffset??d;f=Math.floor(b/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 Ja(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}var wg=8e3,_g="__octocode_generic__.unknown";function xg(e){return e&&e.trim().length>0?e:_g}function Za(e,t){return O.getSemanticBoundaryOffsets(e,xg(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function Ag(e,t){let n=e.indexOf(`
|
|
11
|
+
`,t);return n===-1?void 0:n+1}function sr(e){let t=e.trimEnd().split(`
|
|
12
|
+
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function ar(e,t,n){let r=Ag(e,Math.max(0,t));if(r!==void 0)return Za(e,n).find(o=>o>=r&&o>t)}function cr(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=Za(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<=wg?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function ur(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(`
|
|
13
|
+
`),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 Og(){let e=Be();return Math.min(e,8e3)}function lr(e,t){return{sourceChars:e,sourceBytes:t}}function ec(e,t,n){let r=e.content??"",o=n??Og();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=cr(r,t,o,i),c=Gt(r,t,s),u;if(c.hasMore&&a==="char-limit"&&sr(c.paginatedContent)){let l=c.charOffset+c.charLength;u=ar(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 tc(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 nc(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",b;if(m==="symbols"){let Q=O.extractSignatures(e,o);if(Q===null&&(b=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),Q!==null){let M=qa.sanitizeContent(Q,o),fe=O.applyContentViewMinification(M.content,o),ie=[O.SIGNATURES_ONLY_HINT];return u&&ie.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),M.hasSecrets&&ie.push(`Secrets detected and redacted: ${M.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:fe,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:bt(e),...lr(p,f),isPartial:!1,signaturesExtracted:!0,hints:ie}}}let R=new Set,C=e,w=C.split(`
|
|
14
|
+
`),T=bt(C),A=e,G,$,x=!1,L;if(i)A=e;else if(u){let Q=d===!0,M;try{M=ur(w,u,c,l??!1,Q)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:T,...lr(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(M.matchCount===0){let j=l?[`Regex "${u}" matched no lines. Verify the pattern, check flags (case-${Q?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${u}" not found in file${Q?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:T,...lr(p,f),matchNotFound:!0,searchedFor:u,hints:j}}A=M.lines.join(`
|
|
15
|
+
`);let fe=M.matchRanges[0],ie=M.matchRanges[M.matchRanges.length-1];s=fe.start,a=ie.end,G=fe.start,$=ie.end,x=!0,M.matchRanges.length>1&&(L=M.matchRanges);let Ye=M.matchingLines.slice(0,5).join(", "),_t=M.matchingLines.length>5?` and ${M.matchingLines.length-5} more`:"";R.add(M.matchCount>1?`Found ${M.matchCount} occurrences of "${u}" on lines ${Ye}${_t} \u2014 all shown as ${M.matchRanges.length} slice${M.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${u}" on line ${M.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let Q=s||1,M=a||T;if(Q<1||Q>T)A=e;else if(M<Q)A=e;else{let fe=Math.max(1,Q),ie=Math.min(T,M),Ye=w.slice(fe-1,ie);G=fe,$=ie,x=!0,A=Ye.join(`
|
|
16
|
+
`),M>T&&R.add(`Requested endLine ${M} adjusted to ${T} (file end)`)}}let z=qa.sanitizeContent(A,o);if(A=g?O.applyContentViewMinification(z.content,o):z.content,z.hasSecrets&&R.add(`Secrets detected and redacted: ${z.secretsDetected.join(", ")}`),z.warnings.length>0&&z.warnings.forEach(Q=>R.add(Q)),T>2e3&&m!=="symbols"&&!u&&!s&&!a&&!i){let Q=Math.max(1,T-200);R.add(`Large file (${T} lines) \u2014 minify:"symbols" for an export index, or startLine=${Q} for the tail.`)}let se=Array.from(R);return{owner:t,repo:n,path:o,content:A,...h!=="standard"&&{contentView:h},branch:r,totalLines:T,...lr(p,f),...x&&{startLine:G,endLine:$,isPartial:x},...L&&{matchRanges:L},...se.length>0&&{matchLocations:se},...(se.length>0||b)&&{warnings:[...b?[b]:[],...se]}}}async function rc(e,t,n){let r=we("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await _e(r,async()=>await ir(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 nc(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:ec(c,u,l),m=(e.charOffset??0)>0;if(!e.noTimestamp&&!m)try{let p=await re(t),f=await _e(we("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>tc(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}}function Ig(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:kg(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function kg(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 oc(e,t,n=ce){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 rc(i,t);if(Ht(s))return Ze(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:Ig(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??F(s.data),...a?.length?{hints:a}:{}}}import{ContentSanitizer as ac}from"@octocodeai/octocode-engine/contentSanitizer";var Fg=2,Mg=20;function fn(e,t=Mg){let n=e?mn(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function ic(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 sc(e){return e?O.filterPatch(e,{trimContext:!0,contextLines:Fg}):""}function Ko(e){let t=ac.sanitizeContent(e.title??""),n=e.body?ac.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 Ng=Be(),Dg=Math.round(Be()/4),cc=3;function uc(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 gn(e,t={}){let n=t.charOffset??0,r=t.charLength??Ng,o=t.charLength??Dg,i=typeof e.body=="string"?O.minifyMarkdownCore(e.body):e.body,s=uc(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,g)=>{let h=f.commentType==="review_inline"?0:1,b=g.commentType==="review_inline"?0:1;return h-b}),c=a.filter(f=>f.commentType==="review_inline").length,u=a.length-c,l=t.includeFullCommentDetails?a:a.slice(0,cc),d=l.map(f=>{let g=uc(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 ${cc} 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 hn(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 dr(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?ic(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?sc(a.patch):a.patch}))}import{ContentSanitizer as Yo}from"@octocodeai/octocode-engine/contentSanitizer";function pr(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function lc(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function dc(e){let t=lc(e);return t?t.discussion!==!1:!1}function pc(e){let t=lc(e);return t?t.reviewInline!==!1:!1}function mc(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function fc(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function gc(e){return!!e.content?.comments?.includeBots}var Hg=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function hc(e){let t=e.toLowerCase();return t.endsWith("[bot]")||Hg.has(t.replace(/\[bot\]$/,""))}function Xo(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
|
|
16
17
|
|
|
17
|
-
`).trim()}async function ts(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=$(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!es(p.user?.login??"")),d=i.length-l.length,u=l.map(p=>{let f=U.minifyMarkdownCore(Br(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:$r.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return d>0&&m.push(`${d} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:D(u,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:D([],0)}}}async function ns(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Ur(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return D(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:$r.sanitizeContent(U.minifyMarkdownCore(Br(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return D([],0)}}async function rs(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=$(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!es(p.user?.login??"")),d=i.length-l.length,u=l.map(p=>{let f=U.minifyMarkdownCore(Br(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:$r.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return d>0&&m.push(`${d} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:D(u,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:D([],0)}}}async function os(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Gr(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:d}=Qt(t);if(l&&d){let u=await n.rest.pulls.get({owner:l,repo:d,pull_number:e.number});if(u.data&&(s+=$(u.data),o.head=u.data.head?.ref,o.head_sha=u.data.head?.sha,o.base=u.data.base?.ref,o.base_sha=u.data.base?.sha,o.draft=u.data.draft??!1,u.data.merged_at&&(o.merged_at=u.data.merged_at),o.additions=u.data.additions??0,o.deletions=u.data.deletions??0,Pn(t)||(o.file_changes={total_count:u.data.changed_files??0,files:[]}),Pn(t))){let m=await is(l,d,e.number);m&&(s+=q(m)??0,m.files=Cn(m.files,t),o.file_changes=m)}}}catch(l){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=Yi(t),c=Xi(t);if(a||c){let{owner:l,repo:d}=Qt(t);if(l&&d){let u=qi(t),m=()=>Promise.resolve({comments:D([],0)}),[{comments:p,note:f},{comments:h,note:R}]=await Promise.all([a?ts(n,l,d,e.number,u):m(),c?rs(n,l,d,e.number,u):m()]);o.comments=[...p,...h],s+=(q(p)??0)+(q(h)??0);let b=[f,R].filter(g=>typeof g=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(Ji(t))try{let{owner:l,repo:d}=Qt(t);if(l&&d){let u=await ns(n,l,d,e.number);s+=q(u)??0,o.reviews=u}}catch(l){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(Zi(t))try{let{owner:l,repo:d}=Qt(t);if(l&&d){let u=await ss(l,d,e.number,t);u&&(s+=q(u)??0,o.commits=u)}}catch(l){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(l)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return D(o,s)}async function Ur(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=$(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function is(e,t,n,r){let o=await ne(r),{items:i,rawResponseChars:s}=await Ur(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return D({total_count:i.length,files:i},s)}async function Sp(e,t,n,r){let o=await ne(r),{items:i,rawResponseChars:s}=await Ur(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return D(i,s)}async function Cp(e,t,n,r){try{let i=await(await ne(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return D(i.data.files||[],i.data)}catch{return null}}async function ss(e,t,n,r,o){let i=await Sp(e,t,n,o);if(!i)return null;let s=q(i)??0,a=[...i].sort((l,d)=>{let u=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(d.commit.author?.date?new Date(d.commit.author.date).getTime():0)-u}),c=await Promise.all(a.map(async l=>{let d=await Cp(e,t,l.sha,o),u=[];return d&&(s+=q(d)??0,u=Cn(d,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:u}}));return D(c,s)}async function En(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Gr(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Pn(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Pn(t))try{let u=await is(a,c,e.number,r);u&&(s+=q(u)??0,u.files=Cn(u.files,t),o.file_changes=u)}catch(u){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let l=Yi(t),d=Xi(t);if(l||d){let u=qi(t),m=()=>Promise.resolve({comments:D([],0)}),[{comments:p,note:f},{comments:h,note:R}]=await Promise.all([l?ts(n,a,c,e.number,u):m(),d?rs(n,a,c,e.number,u):m()]);o.comments=[...p,...h],s+=(q(p)??0)+(q(h)??0);let b=[f,R].filter(g=>typeof g=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(Ji(t))try{let u=await ns(n,a,c,e.number);s+=q(u)??0,o.reviews=u}catch(u){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(Zi(t))try{let u=await ss(a,c,e.number,t,r);u&&(s+=q(u)??0,o.commits=u)}catch(u){H(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return D(o,s)}function Pp(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function as(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PR_REQUIRED_PARAMS.code),{pull_requests:[],total_count:0,error:te.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PR_SINGLE_VALUES.code),{pull_requests:[],total_count:0,error:te.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ne(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await En(a,e,i,t);return{pull_requests:[zt(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:$(s.data)+(q(c)??0)}}catch(i){let s=Z(i);return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PULL_REQUEST_FETCH_FAILED.code),Pp(s,te.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}function cs(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function ls(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function us(e,t,n){let r=Pe("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await Ee(r,async()=>await Ep(e,t,n),{shouldCache:i=>!i.error})}async function Ep(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await as(e,t);let r=await ne(t);if(!mi(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Tp(r,e);let i=pi(e);if(!i)return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.NO_VALID_PARAMETERS.code),{pull_requests:[],total_count:0,error:te.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let s=e.sort&&e.sort!=="best-match"?e.sort:void 0,a=Math.min(e.limit||30,100),c=e.page||1,l=i,d=await r.rest.search.issuesAndPullRequests({q:i,sort:s,order:e.order||"desc",per_page:a,page:c}),u=d.data.items?.filter(L=>!!L.pull_request)||[],m=await Promise.all(u.map(async L=>await os(L,e,r))),p=m.reduce((L,I)=>L+(q(I)??0),0),f=m.map(L=>zt(L,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:e.charOffset,charLength:e.charLength})),h=d.data.total_count,R=Math.min(h,1e3),b=Math.min(Math.ceil(R/a),10),g=Math.min(c,Math.max(1,b)),C=g<b,E=Math.min(R,b*a);return{pull_requests:f,total_count:d.data.total_count,effectiveQuery:l,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:g,totalPages:b,perPage:a,totalMatches:R,reportedTotalMatches:h,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:h>R,hasMore:C},rawResponseChars:$(d.data)+p}}catch(r){if(lt(r))return ls(e);let o=Z(r);return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PULL_REQUEST_SEARCH_FAILED.code),cs(o,te.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function Tp(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await En(m,t,e))),c=a.reduce((m,p)=>m+(q(p)??0),0),l=a.map(m=>zt(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),d=s.data.length===o,u=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:d?i+1:i,perPage:o,totalMatches:u+(d?1:0),reachableTotalMatches:u,totalMatchesKind:d?"lowerBound":"exact",hasMore:d},rawResponseChars:$(s.data)+c}}catch(n){if(lt(n))return ls(t);let r=Z(n);return await H(S.GITHUB_SEARCH_PULL_REQUESTS,te.PULL_REQUEST_LIST_FAILED.code),cs(r,te.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}function wp(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function _p(e,t,n=de){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...wp(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function ds(e,t,n=de){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await us(s,t);return a.error?je({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:_p(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??$(a)}}import{RequestError as Ip}from"octokit";var dt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function Ap(e,t){return t?e>5e4?[`Response ~${e.toLocaleString()} tokens \u2014 exceeds typical context. Reduce charLength or refine the query.`]:e>3e4?[`Response ~${e.toLocaleString()} tokens \u2014 approaching context limit. Consider reducing charLength.`]:[]:[]}function Lp(e){if(e.hasMore&&e.nextCharOffset!==void 0){let t=e.charOffset+1,n=e.charOffset+e.charLength;return[`Page ${e.currentPage}/${e.totalPages} (chars ${t}-${n} of ${e.totalChars}). Next: charOffset=${e.nextCharOffset}`]}return[]}function ps(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...Ap(e.estimatedTokens,n)),o.push(...Lp(e)),o}function Tn(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function ms(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:P,...x}=e;return x}let r=t.itemsPerPage??dt.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),d=Object.create(null),u=e.path==="/"?"":e.path,m=P=>{let x=P;u&&P.startsWith(u)&&(x=P.slice(u.length),x.startsWith("/")&&(x=x.slice(1)));let A=x.lastIndexOf("/");return A===-1?".":x.slice(0,A)},p=P=>{let x=P.lastIndexOf("/");return x===-1?P:P.slice(x+1)};for(let P of l){let x=m(P.path);d[x]||(d[x]={files:[],folders:[]});let A=p(P.path);P.type==="file"?d[x].files.push(A):d[x].folders.push(A)}for(let P of Object.keys(d)){let x=d[P];x&&(x.files.sort(),x.folders.sort())}let f=Object.create(null),h=Object.keys(d).sort((P,x)=>P==="."?-1:x==="."?1:P.localeCompare(x));for(let P of h){let x=d[P];x&&(f[P]=x)}let R=l.filter(P=>P.type==="file").length,b=l.filter(P=>P.type==="dir").length,g=n.filter(P=>P.type==="file").length,C=n.filter(P=>P.type==="dir").length,E=o<s,L={currentPage:o,totalPages:s,hasMore:E,entriesPerPage:r,totalEntries:i},I=Tn(L,{owner:e.owner,repo:e.repo,branch:e.branch,path:u,depth:t.maxDepth??1,pageFiles:R,pageFolders:b,allFiles:g,allFolders:C}),k,j=e._cachedFileSizeMap;if(j){let P=new Set(l.filter(B=>B.type==="file").map(B=>B.path)),x=e.path==="/"?"":e.path,A=Object.create(null);for(let[B,N]of Object.entries(j))for(let[M,oe]of Object.entries(N)){let ae=B==="."?x?`${x}/${M}`:M:x?`${x}/${B}/${M}`:`${B}/${M}`;P.has(ae)&&(A[B]||(A[B]=Object.create(null)),A[B][M]=oe)}Object.keys(A).length>0&&(k=A)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:g,totalFolders:C,truncated:E,filtered:!0,originalCount:i},structure:f,...k!==void 0&&{fileSizeMap:k},...j!==void 0&&{_cachedFileSizeMap:j},pagination:L,hints:I,rawResponseChars:e.rawResponseChars}}async function zr(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return D([],0);a.add(o);try{let c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r}),l=$(c.data),u=(Array.isArray(c.data)?c.data:[c.data]).map(p=>({name:p.name,path:p.path,type:p.type,size:"size"in p?p.size:void 0,download_url:"download_url"in p?p.download_url:void 0,url:p.url,html_url:p.html_url,git_url:p.git_url,sha:p.sha})),m=[...u];if(i<s){let p=u.filter(h=>h.type==="dir"),f=3;for(let h=0;h<p.length;h+=f){let b=p.slice(h,h+f).map(async C=>{try{let E=await zr(e,t,n,r,C.path,i+1,s,a);return l+=q(E)??0,E}catch{return[]}});(await Promise.all(b)).forEach(C=>{m.push(...C)})}}return D(m,l)}catch{return D([],0)}}var wn=S.GITHUB_VIEW_REPO_STRUCTURE;async function Op(e,t,n,r,o,i){let s;try{s=o??await Oe(t,n,i)}catch(a){let c=Z(a);return await H(wn,Ge.NOT_FOUND.code),{error:Ge.NOT_FOUND.message(t,n,c.error),status:c.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s}}catch(a){if(!(a instanceof Ip&&a.status===404)){let l=Z(a);return await H(wn,Ge.ACCESS_FAILED.code),{error:Ge.ACCESS_FAILED.message(t,n,l.error),status:l.status,rateLimitRemaining:l.rateLimitRemaining,rateLimitReset:l.rateLimitReset,retryAfter:l.retryAfter}}let c=Z(a);return await H(wn,Ge.PATH_NOT_FOUND.code),{error:Ge.PATH_NOT_FOUND.message(r,t,n,s),status:c.status}}}function kp(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function vp(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function fs(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function hs(e,t,n){let r=Pe("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await Ee(r,async()=>await Fp({...e,itemsPerPage:e.itemsPerPage??dt.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?ms(o,e):o}async function Fp(e,t){try{let n=await ne(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await Op(n,r,o,c,i,t);if("error"in l)return l;let{data:d,workingBranch:u,repoDefaultBranch:m}=l,p=$(d),f=Array.isArray(d)?d:[d],h=kp(f);if(a>1){let Q=await zr(n,r,o,u,c,1,a);p+=q(Q)??0,h=[...h,...Q].filter((K,pe,Se)=>Se.findIndex(De=>De.path===K.path)===pe)}let R=h.filter(Q=>Q.type==="dir"?!Ut(Q.name):!Pt(Q.path));R.sort((Q,O)=>{if(Q.type!==O.type)return Q.type==="dir"?-1:1;let K=Q.path.split("/").length,pe=O.path.split("/").length;return K!==pe?K-pe:Q.path.localeCompare(O.path)});let b=e.itemsPerPage??dt.ENTRIES_PER_PAGE,g=e.page??1,C=R.length,E=Math.max(1,Math.ceil(C/b)),L=(g-1)*b,I=Math.min(L+b,C),k=R.slice(L,I),j=vp(k,c),P=e.includeSizes===!0?fs(R,c):void 0,x=P!==void 0?fs(k,c):void 0,A=k.filter(Q=>Q.type==="file").length,B=k.filter(Q=>Q.type==="dir").length,N=R.filter(Q=>Q.type==="file").length,M=R.filter(Q=>Q.type==="dir").length,oe=g<E,ae={currentPage:g,totalPages:E,hasMore:oe,entriesPerPage:b,totalEntries:C},ce=Tn(ae,{owner:r,repo:o,branch:u,path:c,depth:a,pageFiles:A,pageFolders:B,allFiles:N,allFolders:M});return{owner:r,repo:o,branch:u,...m!==void 0&&{defaultBranch:m},path:c||"/",apiSource:!0,summary:{totalFiles:N,totalFolders:M,truncated:oe,filtered:!0,originalCount:R.length},structure:j,...x!==void 0&&{fileSizeMap:x},...P!==void 0&&{_cachedFileSizeMap:P},pagination:ae,hints:ce,rawResponseChars:p,_cachedItems:R.map(Q=>({path:Q.path,type:Q.type}))}}catch(n){let r=Z(n);return await H(wn,Ge.STRUCTURE_EXPLORATION_FAILED.code),{error:Ge.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}function Mp(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function gs(e,t,n=de){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await hs(i,t);return"error"in s?hn(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:Mp(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??$(s)}}var ys={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};var _n=class{type="github";capabilities=ys.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await wi(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Ui(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await _i(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await ds(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await gs(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=de(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Oe(n,r,this.authInfo)}handleError(t){let n=Z(t);return je(n)}};import{createHash as Hp}from"crypto";var Dp=3600*1e3,Qr=20,Be=new Map;function Rs(e){return Date.now()-e.createdAt<Dp}function Gp(){for(let[e,t]of Be.entries())Rs(t)||Be.delete(e);if(Be.size>Qr){let e=[...Be.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Be.size-Qr;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Be.delete(r[0])}}}function $p(e){return e?Hp("sha256").update(e).digest("hex").slice(0,16):"default"}function Bp(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function Up(e,t){let n=Bp(t?.baseUrl||"default"),r=$p(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function jr(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=Up(e,t),r=Be.get(n);if(r&&Rs(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Be.delete(n),Be.size>=Qr&&Gp();let o=new _n({...t,type:e}),i=Date.now();return Be.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function bs(){try{return jr("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
|
|
18
|
-
`),[{provider:"github",ok:!1,error:t}]}}import{CloneRepoQuerySchema as Yp}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as Xp}from"@octocodeai/octocode-core/schemas/outputs";import{z as xn}from"zod";function F(e,t){return xn.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,xn.number().int().min(e).max(t))}var J=F(1,1e3).optional().default(1),_t=F(0,100).optional(),xt=F(1,1e9).optional(),Qp={responseCharOffset:F(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:F(1,5e4).optional().describe("Full-response char window.")};function Y(e,t={}){let{maxQueries:n=5}=t;return xn.object({queries:xn.array(e).min(1).max(n).describe("Parallel queries."),...Qp}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}import{z as jp}from"zod";function Vp(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Ss(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=Vp(e.shape[r],o);return n}function Wp(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function ee(e,t={},n={}){let r=Wp(e,Ss(e,t));return n.strict?r.strict():r}function ie(e,t={},n={}){let r=jp.object({...e.shape,...Ss(e,t)});return n.strict?r.strict():r}import{z as fe}from"zod";var Kp=fe.object({currentPage:fe.number(),totalPages:fe.number(),hasMore:fe.boolean(),charOffset:fe.number(),charLength:fe.number(),totalChars:fe.number(),nextCharOffset:fe.number().optional()}).optional(),Te={hints:fe.array(fe.string()).optional(),base:fe.string().optional(),shared:fe.record(fe.string(),fe.union([fe.string(),fe.number(),fe.boolean()])).optional(),responsePagination:Kp};var Wr=ee(Yp),Cs=Y(Wr),jT=Xp.extend(Te);import{z as w}from"zod";import{FileContentQuerySchema as Ps}from"@octocodeai/octocode-core/schemas";var Zp=w.enum(["none","standard","symbols"]).optional().default("standard"),Jp=w.object({currentPage:w.number(),totalPages:w.number(),hasMore:w.boolean(),charOffset:w.number().optional(),charLength:w.number().optional(),totalChars:w.number().optional(),nextCharOffset:w.number().optional(),filesPerPage:w.number().optional(),totalFiles:w.number().optional(),entriesPerPage:w.number().optional(),totalEntries:w.number().optional(),matchesPerPage:w.number().optional(),totalMatches:w.number().optional()}),qp=w.object({path:w.string(),content:w.string(),contentView:w.enum(["none","standard","symbols"]).optional(),isSkeleton:w.boolean().optional(),totalLines:w.number().optional(),sourceChars:w.number().optional(),sourceBytes:w.number().optional(),resolvedBranch:w.string().optional(),pagination:Jp.optional(),isPartial:w.boolean().optional(),startLine:w.number().optional(),endLine:w.number().optional(),matchRanges:w.array(w.object({start:w.number(),end:w.number()})).optional(),lastModified:w.string().optional(),lastModifiedBy:w.string().optional(),warnings:w.array(w.string()).optional(),matchNotFound:w.boolean().optional(),searchedFor:w.string().optional()}),em=w.object({path:w.string(),localPath:w.string(),fileCount:w.number(),totalSize:w.number(),files:w.array(w.object({path:w.string(),size:w.number(),type:w.string()})).optional(),cached:w.boolean().optional(),resolvedBranch:w.string().optional()}),Es={startLine:xt,endLine:xt,contextLines:_t,charOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional(),minify:Zp},tm=ie(Ps,Es),An=ee(Ps,Es),Ts=Y(tm),qT=w.object({base:w.string().optional(),shared:w.record(w.string(),w.union([w.string(),w.number(),w.boolean()])).optional(),responsePagination:Te.responsePagination,results:w.array(w.object({id:w.string(),owner:w.string(),repo:w.string(),files:w.array(qp).optional(),directories:w.array(em).optional()})),hints:w.array(w.string()).optional(),errors:w.array(w.object({id:w.string(),owner:w.string().optional(),repo:w.string().optional(),path:w.string().optional(),error:w.string(),hints:w.array(w.string()).optional()})).optional()});import{z as v}from"zod";import{GitHubCodeSearchQuerySchema as ws}from"@octocodeai/octocode-core/schemas";var _s={limit:F(1,100).optional(),page:J.default(1)},xs=ee(ws,_s),As=Y(ie(ws,_s)),aw=v.object({base:v.string().optional(),shared:v.record(v.string(),v.union([v.string(),v.number(),v.boolean()])).optional(),responsePagination:Te.responsePagination,results:v.array(v.object({id:v.string(),data:v.object({files:v.array(v.object({id:v.string(),owner:v.string(),repo:v.string(),path:v.string(),queryId:v.string().optional(),matches:v.array(v.object({value:v.string().optional(),pathOnly:v.boolean().optional(),matchIndices:v.array(v.object({start:v.number(),end:v.number()})).optional(),url:v.string().optional()}))})),pagination:v.object({currentPage:v.number(),totalPages:v.number(),perPage:v.number(),totalMatches:v.number(),reportedTotalMatches:v.number().optional(),reachableTotalMatches:v.number().optional(),totalMatchesKind:v.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:v.boolean().optional(),hasMore:v.boolean(),uniqueFileCount:v.number().optional()}).optional()})})),hints:v.array(v.string()).optional(),emptyQueries:v.array(v.object({id:v.string(),hints:v.array(v.string()).optional(),nonExistentScope:v.literal(!0).optional()})).optional(),errors:v.array(v.object({id:v.string(),error:v.string(),hints:v.array(v.string()).optional()})).optional()});import{z as pt}from"zod";import{GitHubPullRequestSearchQuerySchema as Ls}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as rm}from"@octocodeai/octocode-core/schemas/outputs";var Is={perPage:F(1,100).optional().default(30),prNumber:F(1,1e9).optional(),limit:F(1,100).optional().default(30),page:J.default(1),filePage:J.optional(),commentPage:J.optional(),commitPage:J.optional(),itemsPerPage:F(1,100).optional().default(20),charOffset:F(0,1e8).optional(),commentBodyOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional()},om=ie(Ls,Is),Ln=ee(Ls,Is),Os=Y(om),gw=rm.extend({results:pt.array(pt.object({id:pt.string().optional(),status:pt.string().optional(),data:pt.object({pull_requests:pt.array(pt.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Te});import{z as V}from"zod";import{GitHubReposSearchSingleQuerySchema as ks}from"@octocodeai/octocode-core/schemas";var vs={limit:F(1,100).optional(),page:J.default(1)},Fs=ee(ks,vs),Ms=Y(ie(ks,vs)),im=V.object({owner:V.string(),repo:V.string(),stars:V.number().optional(),forks:V.number().optional(),openIssuesCount:V.number().optional(),language:V.string().optional(),license:V.string().optional(),description:V.string().optional(),homepage:V.string().optional(),pushedAt:V.string().optional(),createdAt:V.string().optional(),defaultBranch:V.string().optional(),topics:V.array(V.string()).optional(),visibility:V.string().optional(),url:V.string().optional(),updatedAt:V.string().optional()}),sm=V.object({currentPage:V.number(),totalPages:V.number(),hasMore:V.boolean(),perPage:V.number().optional(),totalMatches:V.number().optional(),reportedTotalMatches:V.number().optional(),reachableTotalMatches:V.number().optional(),totalMatchesKind:V.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:V.boolean().optional()}).optional(),am=V.object({repositories:V.array(V.union([V.string(),im])).optional(),pagination:sm}).passthrough(),Tw=V.object({results:V.array(V.object({id:V.string().optional(),status:V.string().optional(),data:am.optional()}).passthrough()).optional()}).extend(Te);import{GitHubViewRepoStructureQuerySchema as Ns}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as lm}from"@octocodeai/octocode-core/schemas/outputs";var Hs={maxDepth:F(0,20).optional(),page:J.default(1),itemsPerPage:F(1,200).optional()},Ds=ee(Ns,Hs),Gs=Y(ie(Ns,Hs)),vw=lm.extend(Te);import{z as re}from"zod";import{NpmPackageQuerySchema as $s}from"@octocodeai/octocode-core/schemas";var Bs={page:J,mode:re.enum(["lean","full"]).optional()},Us=ee($s,Bs),zs=Y(ie($s,Bs,{strict:!0}),{maxQueries:5}),$w=re.object({results:re.array(re.looseObject({id:re.string(),data:re.looseObject({packages:re.array(re.object({name:re.string(),version:re.string().optional(),description:re.string().optional(),license:re.string().optional(),weeklyDownloads:re.number().optional(),repository:re.string().optional(),repositoryDirectory:re.string().optional()}).passthrough()).optional(),pagination:re.object({currentPage:re.number(),totalPages:re.number(),perPage:re.number(),totalFound:re.number(),returned:re.number(),hasMore:re.boolean()}).optional()}).optional(),status:re.string().optional()})).optional()}).extend(Te);import{z as um}from"zod";import{FetchContentQuerySchema as Qs}from"@octocodeai/octocode-core/schemas";var dm=um.enum(["none","standard","symbols"]).optional().default("standard"),js={startLine:xt,endLine:xt,contextLines:_t.default(5),charOffset:F(0,1e8).optional(),charLength:F(1,5e4).optional(),minify:dm},pm=ie(Qs,js),In=ee(Qs,js),Vs=Y(pm,{maxQueries:5});import{z as mm}from"zod";import{FindFilesQuerySchema as fm}from"@octocodeai/octocode-core/schemas";var Ws={maxDepth:F(0,100).optional(),minDepth:F(0,100).optional(),limit:F(1,1e4).optional(),page:J.default(1),itemsPerPage:F(1,50).optional()},Ks=mm.object(Object.fromEntries(Object.entries(fm.shape).filter(([e])=>e!=="regexType")));function hm(e,t){e.minDepth!==void 0&&e.maxDepth!==void 0&&e.minDepth>e.maxDepth&&t.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var gm=ie(Ks,Ws),On=ee(Ks,Ws).superRefine(hm),Ys=Y(gm,{maxQueries:5});import{RipgrepQuerySchema as Xs}from"@octocodeai/octocode-core/schemas";var Zs={contextLines:_t,matchContentLength:F(1,1e5).optional().default(500),maxMatchesPerFile:F(1,1e5).optional(),maxFiles:F(1,1e5).optional(),matchPage:J.optional(),itemsPerPage:F(1,1e3).optional(),page:J.default(1)},ym=ie(Xs,Zs),tt=ee(Xs,Zs,{strict:!0}),Js=Y(ym,{maxQueries:5});import{ViewStructureQuerySchema as qs}from"@octocodeai/octocode-core/schemas";var ea={maxDepth:F(0,20).optional(),limit:F(1,1e4).optional(),page:J.default(1),itemsPerPage:F(1,50).optional()},Rm=ie(qs,ea),kn=ee(qs,ea),ta=Y(Rm,{maxQueries:5});import{z as y}from"zod";import{LspGetSemanticsQuerySchema as oa}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as bm}from"@octocodeai/octocode-core/schemas/outputs";var Sm=F(1,1e9),Cm=F(0,1e5).optional(),Pm=["structured","compact"],ia={type:y.enum(qo).default("definition"),symbolName:y.string().min(1).optional(),lineHint:Sm.optional(),orderHint:Cm,depth:F(0,20).optional(),includeDeclaration:y.boolean().optional().default(!0),page:J,itemsPerPage:F(1,100).optional(),contextLines:F(0,100).optional(),format:y.enum(Pm).optional().default("structured")},Em=ie(oa,ia),sa=ee(oa,ia);var aa=Y(Em,{maxQueries:5}),na=y.object({line:y.number(),character:y.number()}),Tm=y.object({start:na,end:na}),wm=y.object({startLine:y.number(),endLine:y.number()}),vn=y.object({uri:y.string(),content:y.string().optional(),displayRange:wm.optional(),isDefinition:y.boolean().optional()}),Fn=y.string(),_m=y.object({name:y.string(),uri:y.string(),foundAtLine:y.number(),orderHint:y.number().optional()}),xm=y.object({serverAvailable:y.boolean().optional(),provider:y.string().optional(),source:y.string().optional()}),ca=y.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls"]),Xr=y.object({category:ca,reason:y.string()}),Am=y.object({currentPage:y.number(),totalPages:y.number(),totalResults:y.number(),hasMore:y.boolean(),itemsPerPage:y.number(),nextPage:y.number().optional()}),Lm=y.object({name:y.string(),kind:y.string(),line:y.number(),character:y.number(),endLine:y.number(),childCount:y.number(),containerName:y.string().optional()}),Im=y.string(),la=y.object({name:y.string(),kind:y.string(),uri:y.string(),line:y.number(),endLine:y.number(),selectionLine:y.number().optional()}),Om=y.string(),km=y.object({direction:y.enum(["incoming","outgoing"]),item:la,ranges:y.array(y.object({line:y.number(),character:y.number()})),rangeCount:y.number(),rangeSampleCount:y.number(),contentPreview:y.string().optional()}),vm=y.string(),Fm=y.object({complete:y.boolean(),truncatedByDepth:y.boolean(),cycleCount:y.number(),failedRequestCount:y.number(),dynamicCallsExcluded:y.literal(!0),stdlibCallsExcluded:y.number().optional()}),Mm=y.object({uri:y.string(),count:y.number(),firstLine:y.number(),firstCharacter:y.number(),lines:y.array(y.number()),hasDefinition:y.boolean().optional()}),Nm=y.string(),Hm=y.discriminatedUnion("kind",[y.object({kind:y.literal("definition"),locations:y.array(y.union([vn,Fn]))}),y.object({kind:y.literal("typeDefinition"),locations:y.array(y.union([vn,Fn]))}),y.object({kind:y.literal("implementation"),locations:y.array(y.union([vn,Fn]))}),y.object({kind:y.literal("references"),locations:y.array(y.union([vn,Fn])).optional(),byFile:y.array(y.union([Mm,Nm])).optional(),totalReferences:y.number(),totalFiles:y.number(),empty:Xr.optional()}),...["callers","callees","callHierarchy"].map(e=>y.object({kind:y.literal(e),root:y.union([la,Om]).optional(),direction:y.enum(["incoming","outgoing","both"]),calls:y.array(y.union([km,vm])),incomingCalls:y.number(),outgoingCalls:y.number(),completeness:Fm,empty:Xr.optional()})),y.object({kind:y.literal("hover"),markdown:y.string().optional(),text:y.string().optional(),range:Tm.optional()}),y.object({kind:y.literal("documentSymbols"),symbols:y.array(y.union([Lm,Im])),totalSymbols:y.number().optional(),topLevelSymbols:y.number().optional(),empty:Xr.optional()}),y.object({kind:y.literal("empty"),category:ca,reason:y.string()})]),ra=y.object({type:y.string(),uri:y.string(),format:y.enum(["structured","compact"]).optional(),resolvedSymbol:_m.optional(),lsp:xm,payload:Hm,pagination:Am.optional(),summary:y.record(y.string(),y.unknown()).optional(),warnings:y.array(y.string()).optional(),hints:y.array(y.string()).optional()}),y_=y.object({base:y.string().optional(),shared:y.record(y.string(),y.union([y.string(),y.number(),y.boolean()])).optional(),hints:y.array(y.string()).optional(),results:y.array(y.union([y.object({id:y.string().min(1),status:y.literal("empty"),data:ra}),y.object({id:y.string().min(1),status:y.literal("error"),data:bm}),y.object({id:y.string().min(1),data:ra})]))});import{z as Dm}from"zod";import{LocalBinaryInspectQuerySchema as Gm}from"@octocodeai/octocode-core/schemas";var $m={entryPageNumber:J.default(1),matchStringContextLines:F(0,50).default(3),charLength:F(1,5e4).optional(),page:J.default(1)},ua=Dm.object({...Gm.shape,...$m}),Mn=ua.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),da=Y(ua,{maxQueries:5});import{incrementToolCharSavings as Jm}from"octocode-shared";function He(e){return t=>{}}function pa(e,t){return n=>t}async function ma(e,t={}){if(!Array.isArray(e))throw H("promiseUtils",Ze.PROMISES_NOT_ARRAY.code).catch(He("promise utility session logging")),new Error(Ze.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw H("promiseUtils",Ze.TIMEOUT_NOT_POSITIVE.code).catch(He("promise utility session logging")),new Error(Ze.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw H("promiseUtils",Ze.CONCURRENCY_NOT_POSITIVE.code).catch(He("promise utility session logging")),new Error(Ze.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>(H("promiseUtils",qe.NOT_A_FUNCTION.code).catch(He("promise utility session logging")),Promise.reject(new Error(qe.NOT_A_FUNCTION.message(l)))));if(r<i.length)return Bm(i,r,n,o);let s=i.map((c,l)=>fa(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function fa(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{H("promiseUtils",qe.TIMEOUT.code).catch(()=>{}),l(new Error(qe.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function Bm(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){H("promiseUtils",qe.FUNCTION_UNDEFINED.code).catch(He("promise utility session logging")),o[c]={success:!1,error:new Error(qe.FUNCTION_UNDEFINED.message),index:c};continue}try{let d=await fa(l,c,n,r);o[c]=d}catch(d){o[c]={success:!1,error:d instanceof Error?d:new Error(String(d)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}import{maskSensitiveData as ha}from"octocode-security/mask";import{ContentSanitizer as ga}from"octocode-security/contentSanitizer";import{getConfigSync as Um}from"octocode-shared";function zm(){try{return Um().output.format}catch{return"yaml"}}function nt(e){if(e==null)return e;if(typeof e=="string"){let t=ga.sanitizeContent(e);return ha(t.content)}if(Array.isArray(e))return e.map(t=>nt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=nt(r);return t}return e}function Qm(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
|
|
18
|
+
`).trim()}async function yc(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+=F(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!hc(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=O.minifyMarkdownCore(Xo(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Yo.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:D(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:D([],0)}}}async function Rc(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Jo(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return D(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Yo.sanitizeContent(O.minifyMarkdownCore(Xo(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return D([],0)}}async function bc(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+=F(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!hc(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=O.minifyMarkdownCore(Xo(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Yo.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:D(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:D([],0)}}}async function Sc(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Ko(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:u,repo:l}=hn(t);if(u&&l){let d=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(d.data&&(s+=F(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,pr(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),pr(t))){let m=await Cc(u,l,e.number);m&&(s+=ee(m)??0,m.files=dr(m.files,t),o.file_changes=m)}}}catch(u){v(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=dc(t),c=pc(t);if(a||c){let{owner:u,repo:l}=hn(t);if(u&&l){let d=gc(t),m=()=>Promise.resolve({comments:D([],0)}),[{comments:p,note:f},{comments:g,note:h}]=await Promise.all([a?yc(n,u,l,e.number,d):m(),c?bc(n,u,l,e.number,d):m()]);o.comments=[...p,...g],s+=(ee(p)??0)+(ee(g)??0);let b=[f,h].filter(R=>typeof R=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(fc(t))try{let{owner:u,repo:l}=hn(t);if(u&&l){let d=await Rc(n,u,l,e.number);s+=ee(d)??0,o.reviews=d}}catch(u){v(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(mc(t))try{let{owner:u,repo:l}=hn(t);if(u&&l){let d=await Tc(u,l,e.number,t);d&&(s+=ee(d)??0,o.commits=d)}}catch(u){v(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return D(o,s)}async function Jo(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=F(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Cc(e,t,n,r){let o=await re(r),{items:i,rawResponseChars:s}=await Jo(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return D({total_count:i.length,files:i},s)}async function Gg(e,t,n,r){let o=await re(r),{items:i,rawResponseChars:s}=await Jo(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return D(i,s)}async function Ug(e,t,n,r){try{let i=await(await re(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return D(i.data.files||[],i.data)}catch{return null}}async function Tc(e,t,n,r,o){let i=await Gg(e,t,n,o);if(!i)return null;let s=ee(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 Ug(e,t,u.sha,o),d=[];return l&&(s+=ee(l)??0,d=dr(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:d}}));return D(c,s)}async function mr(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Ko(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,pr(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),pr(t))try{let d=await Cc(a,c,e.number,r);d&&(s+=ee(d)??0,d.files=dr(d.files,t),o.file_changes=d)}catch(d){v(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=dc(t),l=pc(t);if(u||l){let d=gc(t),m=()=>Promise.resolve({comments:D([],0)}),[{comments:p,note:f},{comments:g,note:h}]=await Promise.all([u?yc(n,a,c,e.number,d):m(),l?bc(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(ee(p)??0)+(ee(g)??0);let b=[f,h].filter(R=>typeof R=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(fc(t))try{let d=await Rc(n,a,c,e.number);s+=ee(d)??0,o.reviews=d}catch(d){v(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(mc(t))try{let d=await Tc(a,c,e.number,t,r);d&&(s+=ee(d)??0,o.commits=d)}catch(d){v(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 D(o,s)}function Bg(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 Pc(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return await v(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 v(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 mr(a,e,i,t);return{pull_requests:[gn(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:F(s.data)+(ee(c)??0)}}catch(i){let s=X(i);return await v(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PULL_REQUEST_FETCH_FAILED.code),Bg(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 Ec(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 wc(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 _c(e,t,n){let r=we("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"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 _e(r,async()=>await zg(e,t,n),{shouldCache:i=>!i.error})}async function zg(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Pc(e,t);let r=await re(t);if(!Ia(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Qg(r,e);let i=Oa(e);if(!i)return await v(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,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(T=>!!T.pull_request)||[],m=await Promise.all(d.map(async T=>await Sc(T,e,r))),p=m.reduce((T,A)=>T+(ee(A)??0),0),f=m.map(T=>gn(T,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:e.charOffset,charLength:e.charLength})),g=l.data.total_count,h=Math.min(g,1e3),b=Math.min(Math.ceil(h/a),10),R=Math.min(c,Math.max(1,b)),C=R<b,w=Math.min(h,b*a);return{pull_requests:f,total_count:l.data.total_count,effectiveQuery:u,...l.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:R,totalPages:b,perPage:a,totalMatches:h,reportedTotalMatches:g,reachableTotalMatches:w,totalMatchesKind:"reported",totalMatchesCapped:g>h,hasMore:C,...C?{nextPage:R+1}:{}},rawResponseChars:F(l.data)+p}}catch(r){if(yt(r))return wc(e);let o=X(r);return await v(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PULL_REQUEST_SEARCH_FAILED.code),Ec(o,ne.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function Qg(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 mr(m,t,e))),c=a.reduce((m,p)=>m+(ee(p)??0),0),u=a.map(m=>gn(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:F(s.data)+c}}catch(n){if(yt(n))return wc(t);let r=X(n);return await v(S.GITHUB_SEARCH_PULL_REQUESTS,ne.PULL_REQUEST_LIST_FAILED.code),Ec(r,ne.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}function $g(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 jg(e,t,n=ce){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,...$g(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function xc(e,t,n=ce){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 _c(s,t);return a.error?Ze({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:jg(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??F(a)}}import{RequestError as Yg}from"octokit";var St={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function fr(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function Ac(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:x,...L}=e;return L}let r=t.itemsPerPage??St.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=x=>{let L=x;d&&x.startsWith(d)&&(L=x.slice(d.length),L.startsWith("/")&&(L=L.slice(1)));let z=L.lastIndexOf("/");return z===-1?".":L.slice(0,z)},p=x=>{let L=x.lastIndexOf("/");return L===-1?x:x.slice(L+1)};for(let x of u){let L=m(x.path);l[L]||(l[L]={files:[],folders:[]});let z=p(x.path);x.type==="file"?l[L].files.push(z):l[L].folders.push(z)}for(let x of Object.keys(l)){let L=l[x];L&&(L.files.sort(),L.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((x,L)=>x==="."?-1:L==="."?1:x.localeCompare(L));for(let x of g){let L=l[x];L&&(f[x]=L)}let h=u.filter(x=>x.type==="file").length,b=u.filter(x=>x.type==="dir").length,R=n.filter(x=>x.type==="file").length,C=n.filter(x=>x.type==="dir").length,w=o<s,T={currentPage:o,totalPages:s,hasMore:w,...w?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},A=fr(T,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:h,pageFolders:b,allFiles:R,allFolders:C}),G,$=e._cachedFileSizeMap;if($){let x=new Set(u.filter(se=>se.type==="file").map(se=>se.path)),L=e.path==="/"?"":e.path,z=Object.create(null);for(let[se,Q]of Object.entries($))for(let[M,fe]of Object.entries(Q)){let ie=se==="."?L?`${L}/${M}`:M:L?`${L}/${se}/${M}`:`${se}/${M}`;x.has(ie)&&(z[se]||(z[se]=Object.create(null)),z[se][M]=fe)}Object.keys(z).length>0&&(G=z)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:R,totalFolders:C,truncated:w,filtered:!0,originalCount:i},structure:f,...G!==void 0&&{fileSizeMap:G},...$!==void 0&&{_cachedFileSizeMap:$},pagination:T,hints:A,rawResponseChars:e.rawResponseChars}}import{RequestError as Wg}from"octokit";var Oc=Symbol.for("octocode.recursiveFetchFailures"),Kg=new Set([401,403,429]);function Lc(e){return e instanceof Wg&&Kg.has(e.status)}function Zo(e,t){try{Object.defineProperty(e,Oc,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function qo(e){if(typeof e!="object"||e===null)return 0;let t=e[Oc];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function ei(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Zo(D([],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(Lc(f))throw f;return Zo(D([],0),1)}let u=F(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 b=f.slice(h,h+g),R=await Promise.allSettled(b.map(C=>ei(e,t,n,r,C.path,i+1,s,a)));for(let C of R)if(C.status==="fulfilled"){let w=C.value;u+=ee(w)??0,p+=qo(w),m.push(...w)}else{if(Lc(C.reason))throw C.reason;p+=1}}}return Zo(D(m,u),p)}var gr=S.GITHUB_VIEW_REPO_STRUCTURE;async function Xg(e,t,n,r,o,i){let s;try{s=o??await ke(t,n,i)}catch(a){let c=X(a);return await v(gr,$e.NOT_FOUND.code),{error:$e.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 Yg&&a.status===404)){let u=X(a);return await v(gr,$e.ACCESS_FAILED.code),{error:$e.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let c=X(a);return await v(gr,$e.PATH_NOT_FOUND.code),{error:$e.PATH_NOT_FOUND.message(r,t,n,s),status:c.status}}}function Jg(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 Zg(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 Ic(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 kc(e,t,n){let r=we("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await _e(r,async()=>await qg({...e,itemsPerPage:e.itemsPerPage??St.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Ac(o,e):o}async function qg(e,t){try{let n=await re(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),u=await Xg(n,r,o,c,i,t);if("error"in u)return u;let{data:l,workingBranch:d,repoDefaultBranch:m}=u,p=F(l),f=Array.isArray(l)?l:[l],g=Jg(f),h=0;if(a>1){let j=await ei(n,r,o,d,c,1,a);h=qo(j),p+=ee(j)??0,g=[...g,...j].filter((Wt,Dn,Up)=>Up.findIndex(Bp=>Bp.path===Wt.path)===Dn)}let b=g.filter(j=>j.type==="dir"?!pn(j.name):!Dt(j.path));b.sort((j,Qe)=>{if(j.type!==Qe.type)return j.type==="dir"?-1:1;let Wt=j.path.split("/").length,Dn=Qe.path.split("/").length;return Wt!==Dn?Wt-Dn:j.path.localeCompare(Qe.path)});let R=e.itemsPerPage??St.ENTRIES_PER_PAGE,C=e.page??1,w=b.length,T=Math.max(1,Math.ceil(w/R)),A=(C-1)*R,G=Math.min(A+R,w),$=b.slice(A,G),x=Zg($,c),L=e.includeSizes===!0?Ic(b,c):void 0,z=L!==void 0?Ic($,c):void 0,se=$.filter(j=>j.type==="file").length,Q=$.filter(j=>j.type==="dir").length,M=b.filter(j=>j.type==="file").length,fe=b.filter(j=>j.type==="dir").length,ie=C<T,Ye={currentPage:C,totalPages:T,hasMore:ie,...ie?{nextPage:C+1}:{},entriesPerPage:R,totalEntries:w},_t=fr(Ye,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:se,pageFolders:Q,allFiles:M,allFolders:fe});return h>0&&_t.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:M,totalFolders:fe,truncated:ie,filtered:!0,originalCount:b.length},structure:x,...z!==void 0&&{fileSizeMap:z},...L!==void 0&&{_cachedFileSizeMap:L},pagination:Ye,hints:_t,rawResponseChars:p,_cachedItems:b.map(j=>({path:j.path,type:j.type}))}}catch(n){let r=X(n);return await v(gr,$e.STRUCTURE_EXPLORATION_FAILED.code),{error:$e.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}function eh(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 vc(e,t,n=ce){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 kc(i,t);return"error"in s?or(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:eh(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??F(s)}}var Fc={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};var hr=class{type="github";capabilities=Fc.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await za(t,this.authInfo,ce)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await oc(t,this.authInfo,ce)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Qa(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await xc(t,this.authInfo,ce)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await vc(t,this.authInfo,ce)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=ce(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return ke(n,r,this.authInfo)}handleError(t){let n=X(t);return Ze(n)}};import{createHash as nh}from"crypto";var rh=3600*1e3,ti=20,je=new Map;function Mc(e){return Date.now()-e.createdAt<rh}function oh(){for(let[e,t]of je.entries())Mc(t)||je.delete(e);if(je.size>ti){let e=[...je.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=je.size-ti;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&je.delete(r[0])}}}function ih(e){return e?nh("sha256").update(e).digest("hex").slice(0,16):"default"}function sh(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 ah(e,t){let n=sh(t?.baseUrl||"default"),r=ih(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function ni(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=ah(e,t),r=je.get(n);if(r&&Mc(r))return r.lastAccessedAt=Date.now(),r.provider;r&&je.delete(n),je.size>=ti&&oh();let o=new hr({...t,type:e}),i=Date.now();return je.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function Nc(){try{return ni("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}
|
|
19
|
+
`),[{provider:"github",ok:!1,error:t}]}}import{CloneRepoQuerySchema as mh}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as fh}from"@octocodeai/octocode-core/schemas/outputs";import{z as yr}from"zod";function k(e,t){return yr.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,yr.number().int().min(e).max(t))}var J=k(1,1e3).optional().default(1),Ut=k(0,100).optional(),Bt=k(1,1e9).optional(),uh={responseCharOffset:k(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:k(1,5e4).optional().describe("Full-response char window.")};function K(e,t={}){let{maxQueries:n=5}=t;return yr.object({queries:yr.array(e).min(1).max(n).describe("Parallel queries."),...uh}).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 Dc}from"zod";function lh(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Hc(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=lh(e.shape[r],o);return n}function dh(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Gc(e,t){if(!t?.length)return e;let n=new Set(t);return Dc.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function te(e,t={},n={}){let r=Gc(e,n.omit),o=dh(r,Hc(r,t));return n.strict?o.strict():o}function oe(e,t={},n={}){let r=Gc(e,n.omit),o=Dc.object({...r.shape,...Hc(r,t)});return n.strict?o.strict():o}import{z as me}from"zod";var ph=me.object({currentPage:me.number(),totalPages:me.number(),hasMore:me.boolean(),charOffset:me.number(),charLength:me.number(),totalChars:me.number(),nextCharOffset:me.number().optional()}).optional(),xe={hints:me.array(me.string()).optional(),base:me.string().optional(),shared:me.record(me.string(),me.union([me.string(),me.number(),me.boolean()])).optional(),responsePagination:ph};var oi=te(mh),Uc=K(oi),eI=fh.extend(xe);import{z as P}from"zod";import{FileContentQuerySchema as Bc}from"@octocodeai/octocode-core/schemas";var gh=P.enum(["none","standard","symbols"]).optional().default("standard"),hh=P.object({currentPage:P.number(),totalPages:P.number(),hasMore:P.boolean(),nextPage:P.number().optional(),nextMatchPage:P.number().optional(),charOffset:P.number().optional(),charLength:P.number().optional(),totalChars:P.number().optional(),nextCharOffset:P.number().optional(),filesPerPage:P.number().optional(),totalFiles:P.number().optional(),entriesPerPage:P.number().optional(),totalEntries:P.number().optional(),matchesPerPage:P.number().optional(),totalMatches:P.number().optional()}),yh=P.object({path:P.string(),content:P.string(),localPath:P.string().optional(),repoRoot:P.string().optional(),contentView:P.enum(["none","standard","symbols"]).optional(),isSkeleton:P.boolean().optional(),totalLines:P.number().optional(),sourceChars:P.number().optional(),sourceBytes:P.number().optional(),resolvedBranch:P.string().optional(),pagination:hh.optional(),isPartial:P.boolean().optional(),startLine:P.number().optional(),endLine:P.number().optional(),matchRanges:P.array(P.object({start:P.number(),end:P.number()})).optional(),lastModified:P.string().optional(),lastModifiedBy:P.string().optional(),warnings:P.array(P.string()).optional(),matchNotFound:P.boolean().optional(),searchedFor:P.string().optional(),cached:P.boolean().optional()}),Rh=P.object({path:P.string(),localPath:P.string(),repoRoot:P.string().optional(),fileCount:P.number(),totalSize:P.number(),files:P.array(P.object({path:P.string(),size:P.number(),type:P.string()})).optional(),cached:P.boolean().optional(),resolvedBranch:P.string().optional()}),zc={startLine:Bt,endLine:Bt,contextLines:Ut,charOffset:k(0,1e8).optional(),charLength:k(1,5e4).optional(),minify:gh},bh=oe(Bc,zc),Rr=te(Bc,zc),Qc=K(bh),cI=P.object({base:P.string().optional(),shared:P.record(P.string(),P.union([P.string(),P.number(),P.boolean()])).optional(),responsePagination:xe.responsePagination,results:P.array(P.object({id:P.string(),owner:P.string(),repo:P.string(),files:P.array(yh).optional(),directories:P.array(Rh).optional()})),errors:P.array(P.object({id:P.string(),owner:P.string().optional(),repo:P.string().optional(),path:P.string().optional(),error:P.string()})).optional()});import{z as I}from"zod";import{GitHubCodeSearchQuerySchema as $c}from"@octocodeai/octocode-core/schemas";var jc={limit:k(1,100).optional(),page:J.default(1)},Vc=te($c,jc),Wc=K(oe($c,jc)),hI=I.object({base:I.string().optional(),shared:I.record(I.string(),I.union([I.string(),I.number(),I.boolean()])).optional(),responsePagination:xe.responsePagination,results:I.array(I.object({id:I.string(),data:I.object({files:I.array(I.object({owner:I.string(),repo:I.string(),path:I.string(),queryId:I.string().optional(),matches:I.array(I.object({value:I.string().optional(),pathOnly:I.boolean().optional(),matchIndices:I.array(I.object({start:I.number(),end:I.number(),lineOffset:I.number()})).optional(),url:I.string().optional()}))})),pagination:I.object({currentPage:I.number(),totalPages:I.number(),perPage:I.number(),totalMatches:I.number(),reportedTotalMatches:I.number().optional(),reachableTotalMatches:I.number().optional(),totalMatchesKind:I.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:I.boolean().optional(),hasMore:I.boolean(),nextPage:I.number().optional(),uniqueFileCount:I.number().optional()}).optional()})})),emptyQueries:I.array(I.object({id:I.string(),nonExistentScope:I.literal(!0).optional(),incompleteResults:I.literal(!0).optional()})).optional(),warnings:I.array(I.string()).optional(),errors:I.array(I.object({id:I.string(),error:I.string()})).optional()});import{z as Ct}from"zod";import{GitHubPullRequestSearchQuerySchema as Kc}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Ch}from"@octocodeai/octocode-core/schemas/outputs";var Yc={perPage:k(1,100).optional().default(30),prNumber:k(1,1e9).optional(),limit:k(1,100).optional().default(30),page:J.default(1),filePage:J.optional(),commentPage:J.optional(),commitPage:J.optional(),itemsPerPage:k(1,100).optional().default(20),charOffset:k(0,1e8).optional(),commentBodyOffset:k(0,1e8).optional(),charLength:k(1,5e4).optional()},Th=oe(Kc,Yc),br=te(Kc,Yc),Xc=K(Th),wI=Ch.extend({results:Ct.array(Ct.object({id:Ct.string().optional(),status:Ct.string().optional(),data:Ct.object({pull_requests:Ct.array(Ct.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...xe});import{z as U}from"zod";import{GitHubReposSearchSingleQuerySchema as Jc}from"@octocodeai/octocode-core/schemas";var Zc={limit:k(1,100).optional(),page:J.default(1)},qc=te(Jc,Zc),eu=K(oe(Jc,Zc)),Ph=U.object({owner:U.string(),repo:U.string(),stars:U.number().optional(),forks:U.number().optional(),openIssuesCount:U.number().optional(),language:U.string().optional(),license:U.string().optional(),description:U.string().optional(),homepage:U.string().optional(),pushedAt:U.string().optional(),createdAt:U.string().optional(),defaultBranch:U.string().optional(),topics:U.array(U.string()).optional(),visibility:U.string().optional(),url:U.string().optional(),updatedAt:U.string().optional()}),Eh=U.object({currentPage:U.number(),totalPages:U.number(),hasMore:U.boolean(),perPage:U.number().optional(),totalMatches:U.number().optional(),reportedTotalMatches:U.number().optional(),reachableTotalMatches:U.number().optional(),totalMatchesKind:U.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:U.boolean().optional(),nextPage:U.number().optional()}).optional(),wh=U.object({repositories:U.array(U.union([U.string(),Ph])).optional(),pagination:Eh}).passthrough(),vI=U.object({results:U.array(U.object({id:U.string().optional(),status:U.string().optional(),data:wh.optional()}).passthrough()).optional()}).extend(xe);import{GitHubViewRepoStructureQuerySchema as tu}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as xh}from"@octocodeai/octocode-core/schemas/outputs";var nu={maxDepth:k(0,20).optional(),page:J.default(1),itemsPerPage:k(1,200).optional()},ru=te(tu,nu),ou=K(oe(tu,nu)),zI=xh.extend(xe);import{z as W}from"zod";import{NpmPackageQuerySchema as iu}from"@octocodeai/octocode-core/schemas";var su={page:J,mode:W.enum(["lean","full"]).optional()},au=te(iu,su),cu=K(oe(iu,su,{strict:!0}),{maxQueries:5}),YI=W.object({results:W.array(W.looseObject({id:W.string(),data:W.looseObject({packages:W.array(W.object({name:W.string(),version:W.string().optional(),description:W.string().optional(),license:W.string().optional(),downloads:W.number().optional(),repository:W.string().optional(),repositoryDirectory:W.string().optional(),next:W.record(W.string(),W.unknown()).optional()}).passthrough()).optional(),pagination:W.object({currentPage:W.number(),totalPages:W.number(),perPage:W.number(),totalFound:W.number(),returned:W.number(),hasMore:W.boolean(),nextPage:W.number().optional()}).optional()}).optional(),status:W.string().optional()})).optional()}).extend(xe);import{z as Ah}from"zod";import{FetchContentQuerySchema as uu}from"@octocodeai/octocode-core/schemas";var Lh=Ah.enum(["none","standard","symbols"]).optional().default("standard"),lu={startLine:Bt,endLine:Bt,contextLines:Ut.default(5),charOffset:k(0,1e8).optional(),charLength:k(1,5e4).optional(),minify:Lh},Oh=oe(uu,lu),Sr=te(uu,lu),du=K(Oh,{maxQueries:5});import{z as Ih}from"zod";import{FindFilesQuerySchema as kh}from"@octocodeai/octocode-core/schemas";var pu={maxDepth:k(0,100).optional(),minDepth:k(0,100).optional(),limit:k(1,1e4).optional(),page:J.default(1),itemsPerPage:k(1,50).optional()},mu=Ih.object(Object.fromEntries(Object.entries(kh.shape).filter(([e])=>e!=="regexType")));function vh(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 Fh=oe(mu,pu),Cr=te(mu,pu).superRefine(vh),fu=K(Fh,{maxQueries:5});import{z as ai}from"zod";import{RipgrepQuerySchema as gu}from"@octocodeai/octocode-core/schemas";var Mh=["semanticRanking"],hu={contextLines:Ut,matchContentLength:k(1,1e5).optional().default(500),maxMatchesPerFile:k(1,1e5).optional(),maxFiles:k(1,1e5).optional(),matchPage:J.optional(),itemsPerPage:k(1,1e3).optional(),page:J.default(1),unique:ai.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:ai.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},Nh={...hu,semanticRanking:ai.never().optional()},Dh=oe(gu,Nh),Hh=te(gu,hu,{strict:!0,omit:Mh}),Qt=Hh.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"]})}),yu=K(Dh,{maxQueries:5});import{ViewStructureQuerySchema as Ru}from"@octocodeai/octocode-core/schemas";var bu={maxDepth:k(0,20).optional(),limit:k(1,1e4).optional(),page:J.default(1),itemsPerPage:k(1,50).optional()},Gh=oe(Ru,bu),Tr=te(Ru,bu),Su=K(Gh,{maxQueries:5});import{z as y}from"zod";import{LspGetSemanticsQuerySchema as Pu}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as Uh}from"@octocodeai/octocode-core/schemas/outputs";var Bh=k(1,1e9),zh=k(0,1e5).optional(),Qh=["structured","compact"],Eu={type:y.enum(ha).default("definition"),symbolName:y.string().min(1).optional(),lineHint:Bh.optional(),orderHint:zh,depth:k(0,20).optional(),includeDeclaration:y.boolean().optional().default(!0),page:J,itemsPerPage:k(1,100).optional(),contextLines:k(0,100).optional(),format:y.enum(Qh).optional().default("structured")},$h=oe(Pu,Eu),wu=te(Pu,Eu);var _u=K($h,{maxQueries:5}),Cu=y.object({line:y.number(),character:y.number()}),jh=y.object({start:Cu,end:Cu}),Vh=y.object({startLine:y.number(),endLine:y.number()}),Pr=y.object({uri:y.string(),content:y.string().optional(),displayRange:Vh.optional(),isDefinition:y.boolean().optional()}),Er=y.string(),Wh=y.object({name:y.string(),uri:y.string(),foundAtLine:y.number(),orderHint:y.number().optional()}),Kh=y.object({serverAvailable:y.boolean().optional(),provider:y.string().optional(),source:y.string().optional()}),xu=y.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls"]),ci=y.object({category:xu,reason:y.string()}),Yh=y.object({currentPage:y.number(),totalPages:y.number(),totalResults:y.number(),hasMore:y.boolean(),itemsPerPage:y.number(),nextPage:y.number().optional()}),Xh=y.object({name:y.string(),kind:y.string(),line:y.number(),character:y.number(),endLine:y.number(),childCount:y.number(),containerName:y.string().optional()}),Jh=y.string(),Au=y.object({name:y.string(),kind:y.string(),uri:y.string(),line:y.number(),endLine:y.number(),selectionLine:y.number().optional()}),Zh=y.string(),qh=y.object({direction:y.enum(["incoming","outgoing"]),item:Au,ranges:y.array(y.object({line:y.number(),character:y.number()})),rangeCount:y.number(),rangeSampleCount:y.number(),contentPreview:y.string().optional()}),ey=y.string(),ty=y.object({complete:y.boolean(),truncatedByDepth:y.boolean(),cycleCount:y.number(),failedRequestCount:y.number(),dynamicCallsExcluded:y.literal(!0),stdlibCallsExcluded:y.number().optional()}),ny=y.object({uri:y.string(),count:y.number(),firstLine:y.number(),firstCharacter:y.number(),lines:y.array(y.number()),hasDefinition:y.boolean().optional()}),ry=y.string(),oy=y.discriminatedUnion("kind",[y.object({kind:y.literal("definition"),locations:y.array(y.union([Pr,Er]))}),y.object({kind:y.literal("typeDefinition"),locations:y.array(y.union([Pr,Er]))}),y.object({kind:y.literal("implementation"),locations:y.array(y.union([Pr,Er]))}),y.object({kind:y.literal("references"),locations:y.array(y.union([Pr,Er])).optional(),byFile:y.array(y.union([ny,ry])).optional(),totalReferences:y.number(),totalFiles:y.number(),empty:ci.optional()}),...["callers","callees","callHierarchy"].map(e=>y.object({kind:y.literal(e),root:y.union([Au,Zh]).optional(),direction:y.enum(["incoming","outgoing","both"]),calls:y.array(y.union([qh,ey])),incomingCalls:y.number(),outgoingCalls:y.number(),completeness:ty,empty:ci.optional()})),y.object({kind:y.literal("hover"),markdown:y.string().optional(),text:y.string().optional(),range:jh.optional()}),y.object({kind:y.literal("documentSymbols"),symbols:y.array(y.union([Xh,Jh])),totalSymbols:y.number().optional(),topLevelSymbols:y.number().optional(),empty:ci.optional()}),y.object({kind:y.literal("empty"),category:xu,reason:y.string()})]),Tu=y.object({type:y.string(),uri:y.string(),format:y.enum(["structured","compact"]).optional(),resolvedSymbol:Wh.optional(),lsp:Kh,payload:oy,pagination:Yh.optional(),summary:y.record(y.string(),y.unknown()).optional(),warnings:y.array(y.string()).optional()}),xk=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:Tu}),y.object({id:y.string().min(1),status:y.literal("error"),data:Uh}),y.object({id:y.string().min(1),data:Tu})]))});import{z as Lu}from"zod";import{LocalBinaryInspectQuerySchema as iy}from"@octocodeai/octocode-core/schemas";var sy={entryPageNumber:J.default(1),matchStringContextLines:k(0,50).default(3),charLength:k(1,5e4).optional(),page:J.default(1),detailed:Lu.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Ou=Lu.object({...iy.shape,...sy}),wr=Ou.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".'})}),Iu=K(Ou,{maxQueries:5});async function ku(e,t={}){if(!Array.isArray(e))throw v("promiseUtils",ot.PROMISES_NOT_ARRAY.code).catch(Se("promise utility session logging")),new Error(ot.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw v("promiseUtils",ot.TIMEOUT_NOT_POSITIVE.code).catch(Se("promise utility session logging")),new Error(ot.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw v("promiseUtils",ot.CONCURRENCY_NOT_POSITIVE.code).catch(Se("promise utility session logging")),new Error(ot.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,u)=>typeof c=="function"?c:()=>(v("promiseUtils",st.NOT_A_FUNCTION.code).catch(Se("promise utility session logging")),Promise.reject(new Error(st.NOT_A_FUNCTION.message(u)))));if(r<i.length)return ay(i,r,n,o);let s=i.map((c,u)=>vu(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 vu(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,u)=>{o=setTimeout(()=>{v("promiseUtils",st.TIMEOUT.code).catch(()=>{}),u(new Error(st.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 ay(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){v("promiseUtils",st.FUNCTION_UNDEFINED.code).catch(Se("promise utility session logging")),o[c]={success:!1,error:new Error(st.FUNCTION_UNDEFINED.message),index:c};continue}try{let l=await vu(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}import{maskSensitiveData as Fu}from"@octocodeai/octocode-engine/mask";import{ContentSanitizer as Mu}from"@octocodeai/octocode-engine/contentSanitizer";function cy(){try{return ge().output.format}catch{return"yaml"}}function ct(e){if(e==null)return e;if(typeof e=="string"){let t=Mu.sanitizeContent(e);return Fu(t.content)}if(Array.isArray(e))return e.map(t=>ct(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ct(r);return t}return e}function uy(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
|
|
19
20
|
|
|
20
|
-
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function
|
|
21
|
-
`,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function
|
|
22
|
-
`:`# Response page ${
|
|
23
|
-
`}${u}`,pagination:{currentPage:l,totalPages:d,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Ca(e,t){if(!t)return e;let n=t.charOffset+1,r=t.charOffset+t.charLength;return{...e,responsePagination:t,hints:[...Array.isArray(e.hints)?e.hints.filter(o=>typeof o=="string"):[],t.hasMore?`Response page ${t.currentPage}/${t.totalPages} (chars ${n}-${r} of ${t.totalChars}). Next: responseCharOffset=${t.nextCharOffset}`:`Response page ${t.currentPage}/${t.totalPages} (chars ${n}-${r} of ${t.totalChars}).`]}}function Pa(e){let t=new Set,n=[];for(let r of e){let o=r.data,i=o&&Array.isArray(o.hints)?o.hints:[];for(let s of i)typeof s=="string"&&s.trim().length>0&&!t.has(s)&&(t.add(s),n.push(s));o&&"hints"in o&&delete o.hints}return n}function Ea(e,t,n,r){let o=t.reduce((i,s)=>i+(q(s.result)??$(s.result)),0)+n.reduce((i,s)=>i+$(s),0);try{Jm(e,o,r)}catch{}}async function af(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(d=>({result:d,queryIndex:l,originalQuery:c})));return(await ma(s,{timeout:nf(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data&&o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}),{results:o,errors:i}}function cf(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string"&&n.trim().length>0);return t.length>0?t:void 0}function lf(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))if(!t.has(r))if(r==="hints"){let i=cf(o);i&&(n[r]=i)}else n[r]=o;return n}function Ta(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var wa={empty:(e={})=>{let t=e;if(t.mode==="structural")return["No structural matches. The pattern must be a complete code fragment for the target language; use $X for a single node, $$$ARGS for a list.","For relational rules (inside/has/not), add `stopBy: end` so the sub-rule walks all ancestors/descendants \u2014 without it the rule silently matches nothing.","Verify the file extension is one the engine parses (ts/tsx/js/py/go/rs/java/c/cpp/cs/sh), and widen the path."];let n=typeof t.path=="string"?t.path:void 0,r=typeof t.langType=="string"?t.langType:typeof t.type=="string"?t.type:void 0,o=Array.isArray(t.include)?t.include:[],i=Array.isArray(t.excludeDir)?t.excludeDir:[],s=typeof t.keywords=="string"?t.keywords:void 0,a=r||o.length>0||i.length>0,c=typeof t.searchEngine=="string"?t.searchEngine:void 0;if(!s&&!n&&!a)return[];let l=a?["Remove include/exclude/langType first, then retry a shorter or literal term."]:["Try a shorter partial term, fixedString=true for literals, or search a parent directory."];return c==="grep"?["grep fallback active \u2014 perlRegex patterns (lookaheads, backreferences) unsupported; use fixedString:true or simplify the pattern.",...l]:l},error:(e={})=>e.errorType==="size_limit"?[`Too many results${e.matchCount?` (${e.matchCount} matches)`:""} \u2014 narrow, add a filter, or use fixedString=true.`]:e.errorType==="not_found"?["Path not found \u2014 verify with localViewStructure."]:[]};var _a={empty:(e={})=>{let t=e;return(typeof t.path=="string"?t.path:void 0)?["Confirm path with `localFindFiles`."]:[]},error:(e={})=>{if(e.errorType==="size_limit"){let t=e,n=typeof t.fileSize=="number"?` (~${Math.round(t.fileSize/1024)}KB)`:"",r=typeof t.totalLines=="number"?t.totalLines:void 0,o=r?Math.max(1,r-200):void 0,i=[`File${n} too large \u2014 use matchString or startLine+endLine for a slice.`,'Or minify="symbols" for a skeleton index, then startLine/endLine.'];return o&&r&&i.push(`Tail: startLine=${o}, endLine=${r}.`),i}if(e.errorType==="directory"){let t=e;return[`${typeof t.path=="string"?`'${t.path}'`:"Path"} is a directory \u2014 use \`localViewStructure\` to explore it.`]}return e.errorType==="not_found"?["Use `localFindFiles` to locate the correct path."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]}};var xa={empty:(e={})=>{let t=e,n=Array.isArray(t.extensions)?t.extensions.filter(i=>typeof i=="string"):[],r=typeof t.pattern=="string"?t.pattern:void 0,o=[...r?[`pattern="${r}"`]:[],...n.length>0?[`extensions=${n.join(",")}`]:[]];return o.length===0?[]:[`No entries matched ${o.join(" + ")} \u2014 remove filters or increase depth/recursive.`]},error:(e={})=>e.errorType==="not_found"?["Path must be absolute \u2014 use localFindFiles to discover the correct path."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]};var Aa={empty:(e={})=>{let t=e,n=Array.isArray(t.names)&&t.names.length>0?t.names:void 0,r=typeof t.modifiedWithin=="string"?t.modifiedWithin:void 0,o=typeof t.sizeGreater=="string"?t.sizeGreater:void 0,i=typeof t.sizeLess=="string"?t.sizeLess:void 0,s=[];return n&&s.push(`names=${JSON.stringify(n)}`),r&&s.push(`modifiedWithin="${r}"`),o&&s.push(`sizeGreater="${o}"`),i&&s.push(`sizeLess="${i}"`),s.length===0?[]:[`No metadata match for ${s.join(", ")} \u2014 remove one filter or broaden names.`,"For content text, switch to `localSearchCode`."]},error:(e={})=>e.errorType==="not_found"?["Verify path with `localViewStructure` at the parent directory."]:e.errorType==="permission"?["Permission denied \u2014 check ALLOWED_PATHS configuration."]:[]};var La={empty:(e={})=>{let t=e,n=Array.isArray(t.keywords)?t.keywords:void 0,r=typeof t.owner=="string"?t.owner:void 0,o=typeof t.repo=="string"?t.repo:void 0,i=typeof t.extension=="string"||typeof t.filename=="string"||typeof t.path=="string";if(t.nonExistentScope===!0)return[`"${r&&o?`${r}/${o}`:r||"target"}" doesn't exist or isn't accessible \u2014 check spelling.`];if(e.hasOwnerRepo&&r&&o)return[i?"Remove path/filename/extension first, then retry keywords.":`No results in ${r}/${o} \u2014 large or popular repos often require narrowing: add extension, filename, or path to reduce scope. Repo may also be unindexed (new/private/recently renamed). Fall back to ghGetFileContent with a known path, or ghViewRepoStructure to discover paths.`,"GitHub code search indexes the default branch only."];let s=[];return n&&n.length===1&&typeof n[0]=="string"&&/^@[\w-]+\/[\w.-]+$|^[a-z][\w]*[-.][\w.-]+$/.test(n[0])&&s.push(`"${n[0]}" looks like a package name \u2014 try \`npmSearch\`.`),s.length===0&&n&&n.length>0&&s.push('Scope to owner/repo, split into one-keyword queries, or try a shorter exact term. For large repos (react, webpack, electron), narrow with extension="ts" or path="src".'),s},error:(e={})=>{let t=[];return e.isRateLimited&&t.push(`Rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:""}`),e.status===401&&t.push("GITHUB_TOKEN missing/expired."),e.status===403&&!e.isRateLimited&&t.push("Token lacks `repo` scope."),t}};var Ia={empty:(e={})=>{let t=e;return(typeof t.path=="string"?t.path:void 0)?["Verify it's a file, not a directory \u2014 use `ghViewRepoStructure`."]:[]},error:(e={})=>{if(e.errorType==="size_limit"){let t=e,n=typeof t.fileSize=="number"?`${t.fileSize}KB `:"",r=typeof t.totalLines=="number"?t.totalLines:void 0,o=r?Math.max(1,r-200):void 0,i=[`Large file ${n}\u2014 use startLine+endLine or matchString for a slice.`,'Or minify="symbols" for a skeleton index, then startLine/endLine.'];return o&&r&&i.push(`Tail: startLine=${o}, endLine=${r}.`),i}if(e.errorType==="not_found"){let t=e;return["Verify path with `ghViewRepoStructure`.",...(typeof t.branch=="string"?t.branch:void 0)?["Omit `branch` to use the default branch."]:[]]}return e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks `repo` scope."]:[]}};var Oa={empty:(e={})=>{let t=e;return t.wasFilteredToEmpty===!0?["All entries were filtered by the ignored-paths list (node_modules, .git, dist, etc.). Path is valid \u2014 navigate to a specific subdirectory."]:(typeof t.path=="string"&&t.path?t.path:void 0)?["Try the parent path, or omit `path` to list from root."]:[]},error:(e={})=>{if(e.isRateLimited)return[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`];if(e.status===401)return["GITHUB_TOKEN is missing or expired."];if(e.status===403)return["Token lacks `repo` scope."];if(e.status===404){let t=e,n=typeof t.owner=="string"?t.owner:void 0,r=typeof t.repo=="string"?t.repo:void 0;return[`${n&&r?`'${n}/${r}'`:"the repository"} not found \u2014 check spelling or use \`ghSearchRepos\`.`]}return[]}};var ka={empty:(e={})=>{let t=e;if((typeof t.type=="string"?t.type:"prs")==="commits"){let p=typeof t.path=="string"?t.path:void 0;return p?p.endsWith("/")?[`No commits found under "${p}". Check the directory prefix or widen since/until.`]:[`No commits found for "${p}". Check path spelling or widen since/until.`,"File may have been renamed \u2014 re-query with its previous name."]:["No commits found. Try widening since/until or removing the author filter."]}let r=typeof t.state=="string"?t.state:void 0,o=typeof t.owner=="string"?t.owner:void 0,i=typeof t.repo=="string"?t.repo:void 0,s=typeof t.author=="string"?t.author:void 0,a=typeof t.query=="string"?t.query:void 0,c=typeof t.prNumber=="number"?t.prNumber:void 0,d=(Array.isArray(t.prMatch)?t.prMatch:void 0)?.includes("title")??!1,u=o&&i?`${o}/${i}`:void 0;if(c!==void 0&&u)return[`PR #${c} not found in ${u}. Verify the PR number, or search by title using keywordsToSearch with match:["title"].`];let m=[];return r&&m.push(`state=${r}`),s&&m.push(`author=${s}`),a&&m.push(`query="${a}"`),m.length===0?[]:[r==="merged"?"No merged PRs matched \u2014 widen the date range or remove author/label filters.":"Remove filters one at a time to find what is too narrow.",...a&&!d?['For title-only matching use match:["title"] with sort:"best-match".']:a?[]:["Add a keyword (keywordsToSearch) to narrow by title or body text."]]},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks repo scope \u2014 check GITHUB_TOKEN permissions."]:[]};var va={empty:(e={})=>{let t=e,n=typeof t.query=="string"?t.query:void 0,r=Array.isArray(t.keywords)?t.keywords:void 0,o=typeof t.language=="string"?t.language:void 0,i=typeof t.owner=="string"?t.owner:void 0,s=typeof t.topic=="string"?t.topic:void 0,a=o||i||s,c=n??(r&&r.length>0?String(r[0]):void 0);if(!c&&!a)return[];let l=[a?"Remove owner/language/topic first, then retry fewer keywords.":'Try fewer/simpler keywords, or use match:["name"] for exact-name lookup.'];return c&&/^@[\w-]+\/[\w.-]+$|^[a-z][\w]*[-.][\w.-]+$/.test(c)&&l.push(`"${c}" looks like a package \u2014 use \`npmSearch\` instead.`),l},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.status===401?["GITHUB_TOKEN is missing or expired."]:e.status===403?["Token lacks `public_repo` scope."]:[]};var Fa={empty:(e={})=>{let t=e;return(typeof t.sparsePath=="string"?t.sparsePath:typeof t.path=="string"?t.path:void 0)?["Omit `sparsePath` to check out the full repo.","Confirm path with `ghViewRepoStructure` before cloning sparse."]:[]},error:(e={})=>e.isRateLimited?[`GitHub API rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`,"Use `ghViewRepoStructure` to inspect the tree without cloning."]:e.errorType==="permission"?["Token lacks read access \u2014 verify GITHUB_TOKEN has `repo` scope."]:e.errorType==="not_found"?["Check spelling or omit `branch` to use the default branch."]:e.errorType==="timeout"?["Clone timed out \u2014 use `sparsePath` for a subdirectory only."]:[]};function uf(e){let t=[];if(e.includes("-")&&(t.push(e.replace(/-/g,"_")),t.push(e.replace(/-/g,""))),e.includes("_")&&t.push(e.replace(/_/g,"-")),e.startsWith("@")){let n=e.split("/").pop();n&&t.push(n)}return e.endsWith("js")||t.push(e+"js"),[...new Set(t)].filter(n=>n!==e).slice(0,3)}var Ma={empty:(e={})=>{let t=e,n=typeof t.name=="string"?t.name:void 0;if(!n)return[];let r=uf(n);return["Check spelling and remove any version suffix.","Not on npm? Use `ghSearchRepos` instead.",...r.length?[`Try: ${r.join(", ")}`]:[]]},error:(e={})=>e.isRateLimited?[`npm registry rate limited.${e.retryAfter?` Retry after ${e.retryAfter}s.`:" Wait before retrying."}`]:e.originalError?["npm registry unreachable \u2014 use `ghSearchRepos` instead."]:[]};var Na={empty:(e={})=>{let t=typeof e.symbolName=="string"?e.symbolName:"",n=e,r=typeof n.type=="string"?n.type:void 0;return!t&&!r?[]:r==="documentSymbols"?["Verify uri with localFindFiles/localSearchCode, then retry."]:r==="references"?["references is bounded to the current package (open TS server files) \u2014 cross-package calls will not appear.",'Use type="callers" for cross-package incoming calls.']:["Re-anchor with localSearchCode to get uri+symbolName+lineHint; use documentSymbols if the symbol is ambiguous."]},error:(e={})=>e.errorType==="lsp_unavailable"?["Language server unavailable \u2014 use localSearchCode for references and localGetFileContent for source slices."]:e.errorType==="symbol_not_found"?["Run localSearchCode for the exact symbol line, then retry with updated uri+lineHint."]:[]};function rt(e,t){return t?[...{documentSymbols:["Use returned line values as lineHint for definition, references, or callers."],hover:['type="definition" to jump to source, type="callers" for cross-package usage.'],definition:['localGetFileContent for context, type="callers" for cross-package impact, type="references" for same-package usages.'],typeDefinition:['localGetFileContent for the type, type="implementation" for concrete implementations.'],implementation:['localGetFileContent for implementation, type="callers" for call sites.'],references:["groupByFile=true for compact summary, localGetFileContent for context.","Scope: bounded by files open in the TS server (current package). Use callers/callHierarchy for cross-package blast radius."],callers:["Increase depth for a wider tree, localGetFileContent for context."],callees:['Increase depth, type="definition" on returned calls for source.'],callHierarchy:["Increase depth, localGetFileContent on call sites for context."]}[e]??[]]:[...{definition:["Re-anchor with localSearchCode and retry."],hover:['Try type="definition" instead.'],typeDefinition:['Try type="hover" for the inferred type.'],references:["references is bounded to the current package (open TS server files) \u2014 cross-package calls will not appear.",'Use type="callers" for cross-package incoming calls.'],callers:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" for same-package usages instead.',"Use localSearchCode for dynamic references."],callees:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" or localSearchCode instead.',"Use localSearchCode for dynamic calls."],callHierarchy:['callHierarchyProvider unsupported by this language server (e.g. Python, C++). Use type="references" for same-package usages instead.',"Use localSearchCode for dynamic references."],documentSymbols:['Use localSearchCode with "export|function|class|const" as a fallback.'],implementation:["symbolName must be a method/property of an interface or abstract class \u2014 not the class name.",'Use type="documentSymbols" to list members, then retry with a member name.']}[e]??[]]}var Ha={[W.LOCAL_RIPGREP]:wa,[W.LOCAL_FETCH_CONTENT]:_a,[W.LOCAL_VIEW_STRUCTURE]:xa,[W.LOCAL_FIND_FILES]:Aa,[W.GITHUB_SEARCH_CODE]:La,[W.GITHUB_FETCH_CONTENT]:Ia,[W.GITHUB_VIEW_REPO_STRUCTURE]:Oa,[W.GITHUB_SEARCH_PULL_REQUESTS]:ka,[W.GITHUB_SEARCH_REPOSITORIES]:va,[W.GITHUB_CLONE_REPO]:Fa,[W.PACKAGE_SEARCH]:Ma,[ge]:Na};function Da(e){return e in Ha}function Ga(e,t,n){let r=Ha[e]?.[t];return r?r(n||{}).filter(i=>typeof i=="string"):[]}function se(e,t,n){if(!Da(e))return[];let r=Ga(e,t,n);return[...new Set(r)]}var G={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed"};var $a={[G.PATH_VALIDATION_FAILED]:{code:G.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[G.FILE_ACCESS_FAILED]:{code:G.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[G.FILE_READ_FAILED]:{code:G.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[G.FILE_TOO_LARGE]:{code:G.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[G.BINARY_FILE_UNSUPPORTED]:{code:G.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[G.NO_MATCHES]:{code:G.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[G.OUTPUT_TOO_LARGE]:{code:G.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[G.COMMAND_NOT_AVAILABLE]:{code:G.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[G.COMMAND_EXECUTION_FAILED]:{code:G.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[G.COMMAND_TIMEOUT]:{code:G.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[G.TOOL_EXECUTION_FAILED]:{code:G.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"}};var be=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=$a[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
|
|
24
|
-
Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function to(e){return e instanceof be}function Ba(e,t=G.TOOL_EXECUTION_FAILED,n){if(to(e))return e;if(e instanceof Error)return new be(t,e.message,n,e);let r=String(e);return new be(t,r,n)}function Ua(e){let t=[];if(e.scopesSuggestion&&t.push(e.scopesSuggestion),e.rateLimitRemaining!==void 0&&e.rateLimitReset!==void 0){let n=e.rateLimitReset;if(!isNaN(n)){let r=new Date(n);t.push(`Rate limit: ${e.rateLimitRemaining} remaining, resets at ${r.toISOString()}`)}}return e.retryAfter!==void 0&&t.push(`Retry after ${e.retryAfter} seconds`),t}function df(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function _(e,t,n={}){let{toolName:r,hintContext:o,extra:i,customHints:s,hintSourceError:a}=n,c={status:"error"},l=[];if(a&&l.push(...Ua(a)),df(e))c.error=e,a||l.push(...Ua(e));else if(to(e)){if(c.error=e.message,c.errorCode=e.errorCode,r){let u=se(r,"error",{originalError:e.message,errorType:pf(e),...o});l.push(...u)}}else if(typeof e=="string")c.error=e;else if(e instanceof Error){let u=Ba(e);if(c.error=u.message,c.errorCode=u.errorCode,r){let m=se(r,"error",{originalError:u.message,...o});l.push(...m)}}else c.error="Unknown error occurred";s&&s.length>0&&l.push(...s),i?.hints&&Array.isArray(i.hints)&&l.push(...i.hints);let d=l.filter(u=>typeof u=="string"&&u.trim().length>0);if(d.length>0&&(c.hints=d),i){let{hints:u,...m}=i;Object.assign(c,m)}return n.rawResponse===void 0?c:D(c,n.rawResponse)}function pf(e){switch(e.errorCode){case"fileTooLarge":case"outputTooLarge":return"size_limit";case"fileAccessFailed":case"fileReadFailed":return mf(e)?"directory":"not_found";case"pathValidationFailed":return"permission";default:return}}function mf(e){if(e.context?.errorCode==="EISDIR")return!0;let t=e.cause;return typeof t=="object"&&t!==null&&t.code==="EISDIR"}function ye(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t},a=i==="empty"?se(r,"empty",o?.hintContext):[],c=o?.prefixHints||[],l=o?.extraHints||[],d=[...new Set([...c,...a,...l])].filter(u=>typeof u=="string"&&u.trim().length>0);return d.length>0&&(s.hints=d),o?.rawResponse===void 0?s:D(s,o.rawResponse)}function Dn(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter},r=Array.isArray(e.hints)?e.hints:[];return _(n,t,{hintSourceError:n,customHints:r,rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function he(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return H(r||n||"unknown_tool",Rr.EXECUTION_FAILED.code).catch(()=>{}),_(i,t)}async function we({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return he(o,t,r,e)}}import{promises as Lf}from"fs";import{securityRegistry as If}from"octocode-security/registry";import za from"path";import{pathValidator as ff}from"octocode-security/pathValidator";import{redactPath as Kt}from"octocode-security/pathUtils";var ke={pathValidationFailed:(e,t,n)=>new be(G.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Kt(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Kt(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new be(G.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new be(G.FILE_READ_FAILED,`Failed to read file: ${Kt(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new be(G.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new be(G.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Kt(e)}`,{path:e}),outputTooLarge:(e,t)=>new be(G.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new be(G.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new be(G.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new be(G.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{getConfigSync as hf}from"octocode-shared";function gf(e,t,n,r){let o=[],i=e!==r?` (resolved to: ${r})`:"";return o.push(`CWD: ${n}`),t?.includes("outside allowed")?o.push(`Fix: Use absolute path within workspace, e.g. path="${n}/..."${i}`):t?.includes("Permission denied")?o.push("Fix: Check file/directory permissions"):t?.includes("Symlink")||t?.includes("symlink")?o.push("Fix: Symlink target may be outside allowed directories"):(t?.includes("ENOENT")||t?.includes("not found"))&&o.push(`Fix: Path not found. Use absolute path, e.g. path="${n}/..."${i}`),o}function Re(e,t){if(!e.path?.trim()){let s=ke.pathValidationFailed("","path is required");return{isValid:!1,errorResult:_(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||hf().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=za.isAbsolute(r)?r:za.resolve(n,r),i=ff.validate(o);if(!i.isValid){let s=ke.pathValidationFailed(e.path,i.error),a=gf(e.path,i.error,n,o);return{isValid:!1,errorResult:_(s,e,{toolName:t,hintContext:{errorType:"permission",path:e.path,originalError:i.error},extra:{cwd:n,resolvedPath:o},customHints:a})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}import{validateCommand as Rf}from"octocode-security/commandValidator";import{spawn as Qa}from"child_process";var Gn=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],$n=[...Gn,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],ja=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],yf=10*1024*1024,Va=5e3;function Wa(e={},t=Gn){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function mt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Gn,maxOutputSize:a=yf}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},d=()=>l.stdoutChunks.join(""),u=()=>l.stderrChunks.join(""),m={cwd:o,env:Wa(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=Qa(e,t,m)}catch(g){c({stdout:"",stderr:"",exitCode:null,success:!1,error:g instanceof Error?g:new Error(`Failed to spawn command '${e}'`)});return}let f,h=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Va),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),R=()=>{clearTimeout(h),f!==void 0&&(clearTimeout(f),f=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}R(),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",g=>{if(l.killed)return;let C=g.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stdoutChunks.push(C)}),p.stderr?.on("data",g=>{if(l.killed)return;let C=g.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stderrChunks.push(C)}),p.on("close",g=>{l.killed||(R(),c({stdout:d(),stderr:u(),exitCode:g,success:g===0}))}),p.on("error",g=>{l.killed||(l.killed=!0,R(),c({stdout:d(),stderr:u(),exitCode:null,success:!1,error:g}))})})}function no(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Gn}=r,a;try{a=Qa(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Wa({},s)})}catch{o(!1);return}let c,l=()=>{clearTimeout(d),c!==void 0&&(clearTimeout(c),c=void 0)},d=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Va),o(!1)}},n);a.on("close",u=>{l(),i||o(u===0)}),a.on("error",()=>{l(),i||o(!1)})})}var Yx=1*1024*1024;function Bn(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}async function _e(e,t=[],n={}){let r=Rf(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Bn(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024}=n,l=await mt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(l.error)throw l.error;return{success:l.success,code:l.exitCode,stdout:l.stdout,stderr:l.stderr}}var Ka=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Ya=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Xa=[".dmg",".rar",".cpgz"],bf=[".aar",".yaa"];function ft(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function Sf(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},d={command:"7z",args:i},u={command:"7zz",args:i},m={command:"aa",args:s};return ft(bf,e)?[m]:ft(Xa,e)?[d,u,l,c,a]:ft(Ya,e)?[l,d,u,c,a]:ft(Ka,e)?[a,c,l,d,u]:[c,a,l,d,u]}function Cf(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return ft(Xa,e)?[s,a,o,r,n]:ft(Ya,e)?[o,s,a,r,n]:ft(Ka,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Za(e){let t=[];for(let n of e){let r=await _e(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function Pf(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
|
|
21
|
+
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function xr(e,t){let n=ui(e)??{},r=cy(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;r==="json"?i=JSON.stringify(_r(n,t||o),null,2):i=O.jsonToYamlString(n,{keysPriority:t||o});let s=Mu.sanitizeContent(i);return Fu(s.content)}function _r(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>_r(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=_r(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=_r(n[o],t));return r}var ly=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 dy(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=>ly.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 ui(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=>ui(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(dy(a))continue;let c=(s==="files"||s==="repositories")&&!n,u=ui(a,{inFilesObject:n||c,depth:c?0:r+1});u!==void 0&&(o[s]=u,i=!0)}return i?o:void 0}return e}function py(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 di=["path","uri"];function li(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)li(o,t,n+1);return}let r=e;for(let o of di){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"&&li(o,t,n+1)}function Nu(e){let t=[];for(let i of e)li(i?.data,t,0);if(t.length===0)return;let n=py(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 my(e,r),n}function my(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"?!di.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function fy(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 gy(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var hy=new Set([...di,"owner","repo","name","id"]);function Du(e){let t=fy(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(hy.has(i))continue;let s=n[i];gy(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 yy=3,Hu=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,Ry=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,by=5e3;function Sy(e,t,n){if(e<=1)return Hu;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(Ry/o),s=Math.max(by,Math.min(i,Hu));return n?Math.max(s,n):s}async function Y(e,t,n,r){let o=n.concurrency??yy,{results:i,errors:s}=await Ey(e,t,o,n.minQueryTimeoutMs);return Cy(n,i,s,e,r)}function Cy(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:zu(g.originalQuery,g.queryIndex),...h!==void 0?{status:h}:{},data:wy(g.result)}}),n.forEach(g=>{let h=r[g.queryIndex];h&&(c[g.queryIndex]={id:zu(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=Gu(g.text,o),b=Uu(g.structuredContent,h.pagination);return Bu(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:b,isError:g.isError??(u.length>0&&u.every(C=>C.status==="error"))}}let l={results:u};if(Array.isArray(l.results)){let g=Nu(l.results);g&&(l.base=g);let h=Du(l.results);h&&(l.shared=h)}let d=xr(l,a),m=Gu(d,o),p=Uu(ct(l),m.pagination);return Bu(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 pi(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(`
|
|
22
|
+
`,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 Ty(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=pi(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function Py(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=pi(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 Gu(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=pi(e,s,i),c=a<o,u=Ty(e,s,i),l=Py(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${u}/${l}. Next: responseCharOffset=${a}
|
|
23
|
+
`:`# Response page ${u}/${l}.
|
|
24
|
+
`}${d}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Uu(e,t){return t?{...e,responsePagination:t}:e}function Bu(e,t,n,r){let o=t.reduce((i,s)=>i+(ee(s.result)??F(s.result)),0)+n.reduce((i,s)=>i+F(s),0);try{lo(e,o,r)}catch{}}async function Ey(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 ku(s,{timeout:Sy(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 wy(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 zu(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var 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"};var Qu={[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 Ce=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Qu[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}
|
|
25
|
+
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 mi(e){return e instanceof Ce}function $u(e,t=H.TOOL_EXECUTION_FAILED,n){if(mi(e))return e;if(e instanceof Error)return new Ce(t,e.message,n,e);let r=String(e);return new Ce(t,r,n)}function _y(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function _(e,t,n={}){let{extra:r}=n,o={status:"error"};if(_y(e))o.error=e;else if(mi(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=$u(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:D(o,n.rawResponse)}function Te(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:_(i,t,{toolName:n.toolName})}}function he(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:D(s,o.rawResponse)}function Ar(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return _(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ye(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return v(r||n||"unknown_tool",Ao.EXECUTION_FAILED.code).catch(()=>{}),_(i,t)}async function Ae({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ye(o,t,r,e)}}import{promises as jt}from"fs";import{join as bi,basename as Ir,dirname as Qy,resolve as el,sep as $y}from"node:path";import{securityRegistry as jy}from"@octocodeai/octocode-engine/registry";import ju from"path";import{pathValidator as xy}from"@octocodeai/octocode-engine/pathValidator";import{redactPath as Sn}from"@octocodeai/octocode-engine/pathUtils";var Fe={pathValidationFailed:(e,t,n)=>new Ce(H.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Sn(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Sn(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 Ce(H.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Ce(H.FILE_READ_FAILED,`Failed to read file: ${Sn(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Ce(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 Ce(H.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Sn(e)}`,{path:e}),outputTooLarge:(e,t)=>new Ce(H.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Ce(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 Ce(H.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Ce(H.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};function Le(e,t){if(!e.path?.trim()){let s=Fe.pathValidationFailed("","path is required");return{isValid:!1,errorResult:_(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||ge().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=ju.isAbsolute(r)?r:ju.resolve(n,r),i=xy.validate(o);if(!i.isValid){let s=Fe.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:_(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}import{validateCommand as ky}from"@octocodeai/octocode-engine/commandValidator";import{spawn as Ay}from"child_process";var fi=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Lr=[...fi,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Vu=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],Ly=10*1024*1024,Oy=5e3;function Iy(e={},t=fi){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 Tt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=fi,maxOutputSize:a=Ly}=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:Iy(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=Ay(e,t,m)}catch(R){c({stdout:"",stderr:"",exitCode:null,success:!1,error:R instanceof Error?R: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{}},Oy),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)},b=()=>{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",R=>{if(u.killed)return;let C=R.toString();u.totalOutputSize+=Buffer.byteLength(C),!b()&&u.stdoutChunks.push(C)}),p.stderr?.on("data",R=>{if(u.killed)return;let C=R.toString();u.totalOutputSize+=Buffer.byteLength(C),!b()&&u.stderrChunks.push(C)}),p.on("close",R=>{u.killed||(h(),c({stdout:l(),stderr:d(),exitCode:R,success:R===0}))}),p.on("error",R=>{u.killed||(u.killed=!0,h(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:R}))})})}var xv=1*1024*1024;function Or(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}async function $t(e,t=[],n={}){let r=ky(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Or(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 Tt(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 gi=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],hi=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],yi=[".dmg",".rar",".cpgz"],Wu=[".aar",".yaa"];function ze(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function vy(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(Wu,e)?[m]:ze(yi,e)?[l,d,u,c,a]:ze(hi,e)?[u,l,d,c,a]:ze(gi,e)?[a,c,u,l,d]:[c,a,u,l,d]}function Fy(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(yi,e)?[s,a,o,r,n]:ze(hi,e)?[o,s,a,r,n]:ze(gi,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Ri(e){let t=[];for(let n of e){let r=await $t(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 My(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
|
|
25
26
|
`).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
|
|
26
|
-
`)}async function
|
|
27
|
-
`).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function
|
|
28
|
-
`)
|
|
29
|
-
`),o=new RegExp(t,"i"),i=new Set;for(let a=0;a<r.length;a++)if(o.test(r[a]??""))for(let c=Math.max(0,a-n);c<=Math.min(r.length-1,a+n);c++)i.add(c);let s=Array.from(i).sort((a,c)=>a-c).map(a=>r[a]??"");return s.length?s.join(`
|
|
30
|
-
`):null}function ic(e,t,n,r){let s=wt(e,t??0,n??r);return{content:s.paginatedContent,isPartial:s.hasMore,nextCharOffset:s.hasMore?s.nextCharOffset:void 0}}async function Hf(e,t){let n=await tc(e);return n.success?{status:"success",mode:"identify",path:e,fileType:n.fileType,magicBytes:n.magicBytes}:_(n.error??"identify failed",t)}async function Df(e,t){let n=t.verbose??!1,r=await Ja(e,n);if(!r.success){let m=r.missingCommands?.length?[`Install a missing backend: ${r.missingCommands.join(", ")}`]:[];return _(r.stderr||"All archive backends failed",t,{customHints:[...m,'Run mode="identify" first to confirm this is an archive.']})}let o=r.entries??[],i=Math.min(t.maxEntries??Ff,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,d=a?Math.ceil(s.length/a):1,u=a?c<d:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:d,hasMore:u,entriesPerPage:a,totalEntries:s.length}}}}async function Gf(e,t){let n=t.archiveFile,r=await qa(e,n);if(!r.success){let a=r.missingCommands?.length?[`Install a missing backend: ${r.missingCommands.join(", ")}`]:[];return _(r.stderr||"Extraction failed",t,{customHints:[...a,'Run mode="list" first \u2014 entry names are case-sensitive.']})}let o=r.stdout;if(!o)return _("Entry is empty",t);if(t.matchString){let a=oc(o,t.matchString,t.matchStringContextLines??3);if(!a)return _(`No lines match "${t.matchString}" in the extracted entry`,t);o=a}let i=$e(),s=ic(o,t.charOffset,t.charLength,i);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,content:s.content,contentLength:o.length,isPartial:s.isPartial,...s.nextCharOffset!==void 0&&{hints:[`charOffset=${s.nextCharOffset}`]}}}async function $f(e,t){let n=await ec(e,t.format??"auto");if(!n.success)return _(n.error??"Decompression failed",t,{customHints:['For multi-entry archives (.tar.gz, .zip etc.) use mode="list" or mode="extract".',"Set format explicitly: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse"]});let r=n.content??"";if(!r)return _("Decompressed file is empty",t);if(t.matchString){let s=oc(r,t.matchString,t.matchStringContextLines??3);if(!s)return _(`No lines match "${t.matchString}" in the decompressed content`,t);r=s}let o=$e(),i=ic(r,t.charOffset,t.charLength,o);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,content:i.content,contentLength:r.length,isPartial:i.isPartial,...i.nextCharOffset!==void 0&&{hints:[`charOffset=${i.nextCharOffset}`]}}}async function Bf(e,t){let n=t.minLength??Mf,r=t.includeOffsets??!1,o=await nc(e,n,r);if(!o.success)return _(o.error??"strings extraction failed",t,{customHints:['Ensure the "strings" CLI is installed (binutils on Linux, available via brew on macOS).']});let s=(o.strings??[]).slice(0,Nf);return{status:"success",mode:"strings",path:e,strings:s,totalFound:o.totalFound??0,returned:s.length}}async function sc(e){vf();let t=Re(e,Of);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await Lf.stat(n)).isFile())return _(`Path is not a regular file: ${n}`,e)}catch{return _(`File not found: ${n}`,e)}switch(e.mode){case"identify":return Hf(n,e);case"list":return Df(n,e);case"extract":return Gf(n,e);case"decompress":return $f(n,e);case"strings":return Bf(n,e);default:return _(`Unknown mode: ${String(e.mode)}`,e)}}async function ac(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Mn.safeParse(n);if(!r.success){let a=r.error.issues.map(c=>c.message).join("; ");return _(`Validation error: ${a}`,n)}let o=await sc(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return D(o,s),o}}),{toolName:S.LOCAL_BINARY_INSPECT,peerHints:!0},e)}import{getDirectorySizeBytes as Rh}from"octocode-shared";function ro(e){return e.data!==void 0&&!e.error}import{maskSensitiveData as cc}from"octocode-security/mask";var oo=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function Uf(){return Sr().provider??dn()}function zf(e){let t=Sr(),n=t.provider??dn(),{baseUrl:r,token:o}=t;try{let i=jr(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=cc(s);throw new oo(n,`Failed to initialize ${n} provider: ${a}`)}}function ve(e){let t;return()=>t??=zf(e)}function Un(e,t){return e.capabilities[t]}async function ot(e,t){let n=await t();return ro(n)?{ok:!0,response:n}:{ok:!1,result:Dn(n,e)}}async function lc(e,t){let n=t??Uf(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:cc(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)ro(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}import{existsSync as lh}from"fs";import{join as uh}from"path";import{getOctocodeDir as dh}from"octocode-shared";import{existsSync as Zt,readFileSync as Qf,writeFileSync as jf,mkdirSync as Vf,rmSync as Xt,readdirSync as Wf,statSync as Kf}from"node:fs";import{join as Ue}from"node:path";import{createHash as Yf}from"node:crypto";import{getDirectorySizeBytes as Xf}from"octocode-shared";var Zf=1440*60*1e3,MA=600*1e3,Jf=2*1024*1024*1024,qf=50,dc=".octocode-clone-meta.json";function pc(e){return Ue(e,"repos")}function eh(e){return e?`__sp_${Yf("sha256").update(e).digest("hex").substring(0,6)}`:""}function zn(e,t,n,r,o){let i=`${r}${eh(o)}`;return Ue(pc(e),t,n,i)}function th(e){return typeof e=="object"&&e!==null}function nh(e){if(!th(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),t}function io(e){let t=Ue(e,dc);if(!Zt(t))return null;try{return nh(JSON.parse(Qf(t,"utf-8")))}catch{return null}}function Qn(e,t){try{jf(Ue(e,dc),JSON.stringify(t,null,2),"utf-8")}catch{}}function mc(e){return Date.now()<new Date(e.expiresAt).getTime()}function jn(e){let t=io(e);return t?mc(t)?Zt(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function rh(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Zf}function oh(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Jf}function ih(){let e=process.env.OCTOCODE_MAX_CLONES;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return Math.floor(t)}return qf}function Vn(e,t,n,r,o,i){let s=new Date;return{clonedAt:s.toISOString(),expiresAt:new Date(s.getTime()+rh()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{}}}function Wn(e){let t=Ue(e,"..");try{Zt(t)||Vf(t,{recursive:!0,mode:448})}catch(n){throw new Error(`Failed to create clone parent directory '${t}': ${n instanceof Error?n.message:String(n)}`)}}function so(e){try{Zt(e)&&Xt(e,{recursive:!0,force:!0})}catch{}}function Yt(e){try{return Kf(e).isDirectory()}catch{return!1}}function ht(e){try{return Wf(e)}catch{return[]}}function*fc(e){for(let t of ht(e)){let n=Ue(e,t);if(Yt(n))for(let r of ht(n)){let o=Ue(n,r);if(Yt(o))for(let i of ht(o)){let s=Ue(o,i);Yt(s)&&(yield s)}}}}function uc(e){for(let t of[...ht(e)]){let n=Ue(e,t);if(Yt(n)){for(let r of[...ht(n)]){let o=Ue(n,r);if(Yt(o)&&ht(o).length===0)try{Xt(o,{recursive:!0,force:!0})}catch{}}if(ht(n).length===0)try{Xt(n,{recursive:!0,force:!0})}catch{}}}}function sh(e){let t=0;for(let n of fc(e))try{let r=io(n);(!r||!mc(r))&&(Xt(n,{recursive:!0,force:!0}),t++)}catch{}return t}function ah(e){let t=[];for(let n of fc(e)){let r=io(n);if(!r)continue;let o=Number.isNaN(Date.parse(r.clonedAt))?0:Date.parse(r.clonedAt);t.push({branchDir:n,clonedAtMs:o,sizeBytes:r.sizeBytes??Xf(n)})}return t}function ch(e,t,n){let r=e.reduce((s,a)=>s+a.sizeBytes,0),o=e.length;if(r<=t&&o<=n)return 0;e.sort((s,a)=>s.clonedAtMs-a.clonedAtMs);let i=0;for(let s of e){if(r<=t&&o<=n)break;try{Xt(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Kn(e){let t=pc(e);if(!Zt(t))return 0;let n=0;try{n+=sh(t)}catch{return n}uc(t);let r=ch(ah(t),oh(),ih());return n+=r,r>0&&uc(t),n}var hc=120*1e3,ph=30*1e3,gc=[...$n,"GIT_TERMINAL_PROMPT"];async function yc(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await gh();let a=e.branch??await Oe(r,o,t),c=dh(),l=zn(c,r,o,a,i),d=jn(l);if(!s&&d.hit&&d.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Kn(c),so(l),Wn(l);let u=hh(t,n);if(i){if(await fh(r,o,a,l,i,u),!lh(uh(l,i)))throw so(l),new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the directory path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await mh(r,o,a,l,u);let m=Vn(r,o,a,"clone",i);return Qn(l,m),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}async function mh(e,t,n,r,o){let i=bc(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Rc(e,t),r),await ao(i,hc,`full clone of ${e}/${t}`,o)}async function fh(e,t,n,r,o,i){let s=bc(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Rc(e,t),r),await ao(s,hc,`sparse clone of ${e}/${t}`,i),await ao(["-C",r,"sparse-checkout","set","--",o],ph,`sparse-checkout set ${o}`,void 0)}function Rc(e,t){return`https://github.com/${e}/${t}.git`}function bc(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function hh(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function gh(){try{if(!(await mt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:gc,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function yh(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function ao(e,t,n,r){let o=await mt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:gc,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=yh(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var bh="Served from 24-hour cache.",Sh=["Verify the owner/repo (and branch) exist \u2014 use ghSearchRepos to confirm the repository name.","For private repositories, ensure the GitHub token is set and has repo read access."];async function Sc(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>we({toolName:S.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Un(s,"cloneRepo"))return he(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",S.GITHUB_CLONE_REPO);let a;try{a=await yc(o,n,s.token)}catch(d){let u=d instanceof Error?d.message:String(d);return _(`Clone failed for ${o.owner}/${o.repo}: ${u}`,o,{customHints:Sh})}let c={owner:o.owner,repo:o.repo,localPath:a.localPath,...a.cached?{cached:!0}:{},...o.branch!==a.branch?{resolvedBranch:a.branch}:{}},l=[];return a.cached&&l.push(bh),l.push(`Use localViewStructure with path="${a.localPath}" to explore, then localGetFileContent to read files.`),ye(o,c,!0,S.GITHUB_CLONE_REPO,{extraHints:l,rawResponse:Rh(a.localPath)})}}),{toolName:S.GITHUB_CLONE_REPO,keysPriority:["resolvedBranch","localPath","cached","error"],peerHints:!0},e)}import{writeFileSync as Ch,mkdirSync as Cc,existsSync as Yn,rmSync as Ph,readdirSync as Eh,statSync as Th}from"node:fs";import{join as co,dirname as wh,resolve as Pc,sep as Ec}from"node:path";import{getOctocodeDir as _h}from"octocode-shared";var xh=50,Ah=5*1024*1024,Lh=300*1024,Ih=5,Oh=1e4,kh=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".eot",".otf",".pyc",".class",".o",".obj",".lock",".min.js",".min.css"]);async function wc(e,t,n,r,o,i=!1){let s=_h(),a=zn(s,e,t,r),c=Pc(co(a,n));if(!c.startsWith(a+Ec)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=jn(a);if(l.hit){if(l.meta.source==="clone"){if(Yn(c)){let E=Tc(c,a);return{localPath:c,files:E.files,fileCount:E.fileCount,totalSize:E.totalSize,cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}throw new Error(`Path "${n}" not found in the cloned repository (${e}/${t}@${r}). To refresh the clone, use ghCloneRepo with forceRefresh: true.`)}if(!i&&Yn(c)){let E=Tc(c,a);return{localPath:c,files:E.files,fileCount:E.fileCount,totalSize:E.totalSize,cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}}let d=await ne(o),{data:u}=await d.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(u))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let m=u.filter(C=>{if(C.type!=="file"||!C.download_url||C.size>Lh)return!1;let E=Nh(C.name);return!kh.has(E)}).slice(0,xh),p=o?.token,f=await vh(m,Ih,p),h=0,R=[];for(let{entry:C,content:E}of f){if(h+E.length>Ah)break;h+=E.length,R.push({entry:C,content:E})}Kn(s),Wn(a),Yn(c)&&Ph(c,{recursive:!0,force:!0}),Cc(c,{recursive:!0,mode:448});let b=[];for(let{entry:C,content:E}of R){let L=Pc(co(a,C.path));if(!L.startsWith(a+Ec))continue;let I=wh(L);Yn(I)||Cc(I,{recursive:!0,mode:448}),Ch(L,E,"utf-8"),b.push({path:C.path,size:E.length,type:"file"})}let g=Vn(e,t,r,"directoryFetch");return Qn(a,g),{localPath:c,files:b,fileCount:b.length,totalSize:h,cached:!1,expiresAt:g.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function vh(e,t,n){let r=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),s=await Promise.allSettled(i.map(async a=>{let c=await Mh(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var Fh=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function Mh(e,t){try{let o=new URL(e);if(!Fh.has(o.hostname))throw new Error(`Blocked fetch to unexpected host: ${o.hostname}. Only GitHub download URLs are allowed.`)}catch(o){throw o instanceof TypeError?new Error(`Invalid download URL: ${e}`):o}let n=new AbortController,r=setTimeout(()=>n.abort(),Oh);try{let o={"User-Agent":"octocode-mcp"};t&&(o.Authorization=`token ${t}`);let i=await fetch(e,{signal:n.signal,headers:o});if(!i.ok)throw new Error(`HTTP ${i.status} fetching ${e}`);return await i.text()}finally{clearTimeout(r)}}function Tc(e,t){let n=[],r=0;function o(i){let s;try{s=Eh(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=co(i,a);try{let l=Th(c);if(l.isDirectory())o(c);else if(l.isFile()){let d=c.substring(t.length+1);r+=l.size,n.push({path:d,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function Nh(e){let t=e.lastIndexOf(".");return t===-1?"":e.substring(t).toLowerCase()}function _c(e,t){return e&&t?`${e}/${t}`:void 0}function Lt(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,l=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${l} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function xc(e){return{keywords:e.keywords??[],projectId:_c(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Ac(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Hh(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Lc(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=Hh(a),d=`${c}/${l}`,u=s,m=o.get(d);if(m||(m={id:d,owner:c,repo:l,matches:[]},o.set(d,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&u.url?{url:u.url}:{}});continue}let p=!0,f=!1;for(let h of s.matches){if(!h.context)continue;let R={path:s.path,value:h.context};h.positions?.length>0&&(R.matchIndices=h.positions.map(([b,g])=>({start:b,end:g,lineOffset:(h.context??"").substring(0,b).split(`
|
|
31
|
-
`).length-1}))),r&&p&&u.url&&(R.url=u.url,p=!1),m.matches.push(R),f=!0}f||m.matches.push({path:s.path,pathOnly:!0,...r&&u.url?{url:u.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Ac(e.pagination),hasMore:e.pagination.hasMore}),i}function Ic(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Oc(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function Dh(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function kc(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Dh),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:_c(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Gh(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function $h(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function Bh(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:$h(e)}}function vc(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=Gh(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=Bh(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(d=>({...d,...d.bodyPagination&&{bodyPagination:d.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...Ac(e.pagination),hasMore:e.pagination.hasMore}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function Fc(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Mc(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function Nc(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??dt.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Hc(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([u],[m])=>u==="."?-1:m==="."?1:u.localeCompare(m)).map(([u,m])=>({dir:u,files:m.files,folders:m.folders})),c=e.fileSizeMap,l={};if(c){for(let[u,m]of Object.entries(c))if(n[u]){let p=new Set(n[u].files);for(let[f,h]of Object.entries(m))p.has(f)&&(l[f]=h)}}let d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}function gt(e){let t=new Set,n=[];for(let r of e)typeof r=="string"&&r.trim().length>0&&!t.has(r)&&(t.add(r),n.push(r));return n}function Uh(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function Xn(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=Uh(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r,s=Array.isArray(n.data.hints)?n.data.hints.filter(a=>typeof a=="string"&&a.trim().length>0):void 0;t.push({id:n.id,error:i,...s&&s.length>0?{hints:s}:{}})}return t}function Zn(e,t,n){let r=Hn(e,[...t]);return{structuredContent:nt(e),text:r,isError:n}}function Gc(e){return typeof e=="object"&&e!==null}function Ve(e){return typeof e=="string"&&e.length>0?e:void 0}function ze(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function zh(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function Qh(e){return gt(e.flatMap(t=>{let n=t.data.hints;return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}))}var jh=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function Vh(e){if(!Gc(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of jh){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Wh(e,t){return`${e}/${t}`}function Kh(e,t,n){let r=Wh(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function Yh(e,t){return{path:Ve(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",...ze(e.fileSize)!==void 0?{fileSize:ze(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:ze(e.totalLines),sourceChars:ze(e.sourceChars),sourceBytes:ze(e.sourceBytes),resolvedBranch:Ve(e.resolvedBranch),pagination:Vh(e.pagination),...e.isPartial===!0?{isPartial:!0}:{},startLine:ze(e.startLine),endLine:ze(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:Ve(e.lastModified),lastModifiedBy:Ve(e.lastModifiedBy),warnings:zh(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Ve(e.searchedFor)}}function Dc(e,t){let n=t.pagination,r=n?.charOffset??0,o=n?.charLength??0,i=r+o,s=n?.currentPage&&n.totalPages?`Page ${n.currentPage}/${n.totalPages}`:"Content page",a=typeof n?.totalChars=="number"&&o>0?` (chars ${r+1}-${i} of ${n.totalChars})`:"";return`${s}${a}. Next: charOffset=${i} for ${e}:${t.path}`}function Xh(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Gc).map(o=>({path:Ve(o.path)??"",size:ze(o.size)??0,type:Ve(o.type)??"file"}));return{path:String(t.path??""),localPath:Ve(e.localPath)??"",fileCount:ze(e.fileCount)??r.length,totalSize:ze(e.totalSize)??0,...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Ve(e.resolvedBranch)}}function Zh(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=Kh(n,s,a),l=r.data;if(i.type==="directory"){let u=c.directories??[];u.push(Xh(l,i)),c.directories=u;return}let d=c.files??[];d.push(Yh(l,i)),c.files=d}),Array.from(n.values())}function Jh(e){let t=[];for(let n of e){for(let r of n.files??[]){if(r.pagination?.hasMore&&typeof r.pagination.charOffset=="number"){let o=r.pagination.charLength??0,i=r.pagination.charOffset+o,s=r.pagination.nextBlockChar;if(typeof s=="number"){let a=s-i;t.push(`${Dc(n.id,r)}. Page cut mid-block at char ${i}. Next top-level definition starts at char ${s}. Re-request with charLength=${o+a} to extend this page to the next boundary, or use charOffset=${i} to continue page-by-page.`)}else t.push(Dc(n.id,r))}r.isPartial&&!r.matchRanges?.length&&typeof r.endLine=="number"&&typeof r.totalLines=="number"&&r.endLine<r.totalLines&&t.push(`File content is partial (lines ${r.startLine??1}\u2013${r.endLine} of ${r.totalLines}). Use startLine=${r.endLine+1} to read the next section of ${n.id}:${r.path}.`)}for(let r of n.directories??[])r.cached&&t.push(`Directory ${n.id}:${r.path} served from cache.`)}return gt(t)}function qh(e,t){let n=e.toLowerCase();if(t===404||n.includes("not found")||n.includes("404"))return["Verify owner/repo/path/branch.","Use ghViewRepoStructure to confirm the path."];if(t===403||n.includes("forbidden")||n.includes("403"))return["Check token permissions or repository visibility."];if(t===429||n.includes("rate limit"))return["Retry after reset or authenticate with a higher-limit token."]}function eg(e,t){return Xn(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error,hints:qh(r.error)}})}function $c(){return({queries:e,results:t,config:n})=>{let r=Zh(t,e),o=eg(t,e),i=gt([...n.peerHints?Qh(t):[],...Jh(r)]),s={results:r};return i.length>0&&(s.hints=i),o&&o.length>0&&(s.errors=o),Zn(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","hints","errors"],r.length===0&&!!(o&&o.length>0))}}async function Bc(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{let s=An.safeParse(o);if(!s.success){let l=s.error.issues.map(d=>d.message).join("; ");return _(l,o)}let a=s.data,c=r();return a.type==="directory"?tg(a,n,c):ng(a,c)}catch(s){return he(s,o)}},{toolName:S.GITHUB_FETCH_CONTENT,peerHints:!0,finalize:$c()},e)}async function tg(e,t,n){if(!un())return he(new Error("Directory fetch requires ENABLE_LOCAL=true and ENABLE_CLONE=true. Directory mode saves files to disk using the same cache as ghCloneRepo."),e,"Clone not enabled",S.GITHUB_FETCH_CONTENT);if(!Un(n,"fetchDirectoryToDisk"))return he(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",S.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return _("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Oe(e.owner,e.repo,t),o=await wc(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i={localPath:o.localPath,fileCount:o.fileCount,totalSize:o.totalSize,files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{}};return ye(e,i,!0,S.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??$(o)})}async function ng(e,t){let n=await ot(e,()=>t.provider.getFileContent(Fc(e)));if(n.ok===!1)return n.result;let r=n.response.hints,o={...Mc(n.response.data,e),...r?.length?{hints:r}:{}},i=!!(n.response.data.matchNotFound===!0||n.response.data.content&&n.response.data.content.length>0);return ye(e,o,i,S.GITHUB_FETCH_CONTENT,{rawResponse:n.response.rawResponseChars,hintContext:{path:e.path,branch:e.branch,isPartial:n.response.data.isPartial,endLine:n.response.data.endLine}})}function rg(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{}}}function og(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function ig(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function sg(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{id:`${n.owner}/${n.repo}:${r.path}`,owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function ag(e,t,n){return t.length===0?[]:[{id:e.length===1&&typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",data:{files:sg(t),...n?{pagination:n}:{}}}]}function cg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lg(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${cg(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function ug(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?ig(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:lg(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:dg(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function dg(e,t){return{...e,matches:t}}function pg(e){return gt(e.flatMap(t=>{let n=t.data.hints;return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}))}function mg(e){return e.some(t=>t.matches.some(n=>n.pathOnly))}function Uc(){return({queries:e,results:t,config:n})=>{let r=[],o,i=0,s=[];t.forEach((b,g)=>{if(b.status==="error")return;let C=rg(b);if(C.results.reduce((I,k)=>I+k.matches.length,0)===0){let I=b.data.hints,k=Array.isArray(I)?I.filter(j=>typeof j=="string"&&j.trim().length>0):[];s.push({id:b.id,hints:k,...C.nonExistentScope?{nonExistentScope:!0}:{}})}let L=C.results;r.push({id:b.id,groups:L}),C.pagination&&(o=C.pagination,i+=1)});let a=Array.from(new Set(e.flatMap(b=>{let g=b.keywords;return Array.isArray(g)?g.filter(C=>typeof C=="string"):[]}))),c=ug(og(r),a),l=o&&i===1?Lt(o,"matches"):[],d=Xn(t),u=mg(c)?['Some match="file" results are path-only because GitHub did not return text matches; use ghGetFileContent with matchString or startLine/endLine to inspect content.']:[],m=gt([...n.peerHints?pg(t):[],...l,...u]),p=o&&i===1?o:void 0,f=e.some(b=>b.concise===!0),h=ag(e,c,p);if(f)for(let b of h)b.data.files=b.data.files.map(g=>`${g.owner}/${g.repo}:${g.path}`);let R={results:h};if(m.length>0&&(R.hints=m),s.length>0){let b=new Set(m);R.emptyQueries=s.map(({id:g,hints:C,nonExistentScope:E})=>{let L=C.filter(I=>!b.has(I));return{id:g,...L.length>0?{hints:L}:{},...E?{nonExistentScope:E}:{}}})}return d.length>0&&(R.errors=d),Zn(R,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","hints","emptyQueries","errors"],c.length===0&&d.length>0)}}function fg(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function hg(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search.",hints:['Use owner="<org-or-user>" with repo="<repository>" \u2014 GitHub code search cannot scope to a bare repository name.','If you only know the repo name, first use ghSearchRepos with keywords=["<repo>"] to find its owner.']}}async function zc(e){let{queries:t}=e,n=ve(e.authInfo);return X(t,async(r,o)=>{try{let i=hg(r);if(i)return _(i.error,r,{customHints:i.hints});if(!fg(r))return _("At least one search term or scope filter is required.",r);let s=n(),a=await ot(r,()=>s.provider.searchCode(xc(r)));if(a.ok===!1)return a.result;let c=Lc(a.response.data,r),l={hasOwnerRepo:!!(r.owner&&r.repo),owner:r.owner,repo:r.repo,nonExistentScope:c.nonExistentScope,match:r.match,extension:r.extension,filename:r.filename,path:r.path,keywords:r.keywords,totalMatches:c.pagination?.totalMatches,hasMore:c.pagination?.hasMore,currentPage:c.pagination?.currentPage??1,totalPages:c.pagination?.totalPages??1,matchedPaths:c.results.flatMap(p=>p.matches.map(f=>f.path))},d=new Set(c.results.flatMap(p=>p.matches.map(f=>`${p.owner}/${p.repo}:${f.path}`))).size,u=[];if(c.results.length>0){let p=Array.isArray(r.keywords)&&typeof r.keywords[0]=="string"?r.keywords[0]:"<keyword>";u.push(`Found matches in ${d} file${d===1?"":"s"} \u2014 matchIndices[].lineOffset is the 0-based line within the snippet; use ghGetFileContent(path, matchString="${p}") to land on the matched region (returns lineHint for lspGetSemantics).`)}if(c.pagination){let{totalPages:p,perPage:f,totalMatches:h,reportedTotalMatches:R,reachableTotalMatches:b}=c.pagination,g=R??h,C=b??Math.min(h,p*f);g>C&&u.push(`GitHub caps code-search at ${C} results \u2014 ${g-C} of ${g} reported matches are unreachable; narrow with path/extension/filename to see the rest.`)}if(typeof r.path=="string"&&!r.filename&&/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/.test(r.path)){let p=r.path.match(/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/),f=p?p[1]:r.path;u.push(`path="${r.path}" looks like a file path \u2014 auto-extracted filename="${f}" for the query. Use explicit filename="${f}" + path="<dir>" for clarity.`)}return ye(r,c,c.results.length>0,S.GITHUB_SEARCH_CODE,{hintContext:l,rawResponse:a.response.rawResponseChars,extraHints:u})}catch(i){return he(i,r)}},{toolName:S.GITHUB_SEARCH_CODE,peerHints:!0,finalize:Uc()},e)}function gg(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function yg(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function Rg(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Qc(e){let{content:t,reviewMode:n}=e,r=gg(t,n),o=yg(t,n),i=Rg(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}function jc(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function po(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function qn(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function mo(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function tr(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Wc(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Kc(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function bg(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function er(e,t,n){return bg({...Kc(e,t),...n})}function Vc(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return er(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function lo(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return er(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Sg(e,t,n){return{target:Kc(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function Jn(e){return String(e.path??e.filename??"")}function Cg(e,t){return{path:Jn(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function Pg(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function Eg(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=Pg(r,n.comments),i=po(t),s=i?o.filter(l=>qn(l.body,i)):o,{items:a,pagination:c}=mo(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let d=tr(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...d?{body:d.content,bodyPagination:d.pagination}:{bodyPreview:Wc(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function Tg(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=po(t);return{reviews:(o?r.filter(s=>qn(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=tr(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function wg(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=mo(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function _g(e){return e.split(`
|
|
27
|
+
`)}async function Ku(e,t){let n=await Ri(vy(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?My(n.stdout,n.commandUsed):n.stdout).split(`
|
|
28
|
+
`).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function Yu(e,t){return Ri(Fy(e,t))}function Ny(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(Wu,e)?[c]:ze(yi,e)?[s,a,o,n,r]:ze(hi,e)?[o,s,a,n,r]:ze(gi,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Xu(e,t){return Ri(Ny(e,t))}var Dy={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"]}},Hy=[{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"}],Gy={"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 Uy(e){let t=e.toLowerCase();for(let{ext:n,format:r}of Hy)if(t.endsWith(n))return r}async function By(e){let t=await $t("file",["--mime-type","-b",e]);if(t.success)return Gy[t.stdout.trim().toLowerCase()]}async function zy(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 $t(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 $t(r.command,r.args)).stderr,commandUsed:r.command}}async function Ju(e,t){let n;if(t!=="auto"?n=t:n=Uy(e)??await By(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=Dy[n],o=await zy(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 Zu(e){try{return{success:!0,info:O.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function qu(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 Vy=S.LOCAL_BINARY_INSPECT;function nl(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function Wy(e){return bi(be.unzip,`${Ir(e)}-${nl()}`)}function Ky(e,t){return bi(be.binary,`${Ir(e)}-${t}-${nl()}`)}function Yy(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function Si(e,t,n,r){let o=el(Ky(e,t)),i=el(bi(o,Yy(n)));if(!i.startsWith(o+$y)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await jt.mkdir(Qy(i),{recursive:!0}),await jt.writeFile(i,r,"utf-8"),i}var Xy=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],tl=!1;function Jy(){if(!tl){try{jy.addAllowedCommands(Xy)}catch{}tl=!0}}var Zy=1e3,qy=8;function rl(e,t,n){let r=O.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
|
|
29
|
+
`):null}function Ci(e,t,n,r){let s=Gt(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 eR(e,t){let n=Zu(e);if(!n.success||!n.info)return _(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 tR(e,t){let n=t.verbose??!1,r=await Ku(e,n);if(!r.success)return _(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??Zy,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 nR(e,t){let n=t.archiveFile,r=await Yu(e,n);if(!r.success)return _(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return _("Entry is empty",t);let i=await Si(e,"extract",n,o);if(t.matchString){let c=rl(o,t.matchString,t.matchStringContextLines??3);if(!c)return _(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=Be(),a=Ci(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 rR(e,t){let n=await Ju(e,t.format??"auto");if(!n.success)return _(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return _("Decompressed file is empty",t);let o=await Si(e,"decompress",`${Ir(e)}.decompressed.txt`,r);if(t.matchString){let a=rl(r,t.matchString,t.matchStringContextLines??3);if(!a)return _(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=Be(),s=Ci(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 oR(e,t){let n=t.minLength??qy,r=t.includeOffsets??!1,o=t.scanOffset??0,i=qu(e,n,r,o);if(!i.success)return _(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
|
|
30
|
+
`),a=s?await Si(e,"strings",`${Ir(e)}.strings.txt`,s):void 0,c=Be(),u=Ci(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 iR(e,t){try{await jt.stat(e)}catch{return _(`File not found: ${e}`,t)}let n=Wy(e);await jt.mkdir(n,{recursive:!0});let r=await Xu(e,n);if(!r.success)return _(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await jt.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function ol(e){Jy();let t=Le(e,Vy);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await jt.stat(n)).isFile())return _(`Path is not a regular file: ${n}`,e)}catch{return _(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return eR(n,e);case"list":return tR(n,e);case"extract":return nR(n,e);case"decompress":return rR(n,e);case"strings":return oR(n,e);case"unpack":return iR(n,e);default:return _(`Unknown mode: ${String(e.mode)}`,e)}}async function il(e){let{queries:t}=e;return Y(t||[],async n=>Ae({toolName:S.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Te(wr,n);if(r.ok===!1)return r.error;let o=await ol(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return D(o,s),o}}),{toolName:S.LOCAL_BINARY_INSPECT},e)}function Ti(e){return e.data!==void 0&&!e.error}import{maskSensitiveData as sl}from"@octocodeai/octocode-engine/mask";var Pi=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function sR(){return Lo().provider??er()}function aR(e){let t=Lo(),n=t.provider??er(),{baseUrl:r,token:o}=t;try{let i=ni(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=sl(s);throw new Pi(n,`Failed to initialize ${n} provider: ${a}`)}}function Me(e){let t;return()=>t??=aR(e)}function kr(e,t){return e.capabilities[t]}async function ut(e,t){let n=await t();return Ti(n)?{ok:!0,response:n}:{ok:!1,result:Ar(n,e)}}async function al(e,t){let n=t??sR(),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:sl(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Ti(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}import{existsSync as _R}from"fs";import{join as xR}from"path";import{existsSync as Pn,readFileSync as cR,writeFileSync as uR,mkdirSync as lR,rmSync as Tn,readdirSync as dR,statSync as pR}from"node:fs";import{join as Ne}from"node:path";import{createHash as mR}from"node:crypto";var fR=1440*60*1e3,h0=600*1e3,gR=2*1024*1024*1024,hR=50,ul=".octocode-clone-meta.json";function ll(e){return Ne(e,"tmp","clone")}function dl(e){return Ne(e,"tmp","tree")}function yR(e){return e?`__sp_${mR("sha256").update(e).digest("hex").substring(0,6)}`:""}function pl(e,t,n,r,o){let i=`${r}${yR(o)}`;return Ne(ll(e),t,n,i)}function Ei(e,t,n,r){return Ne(dl(e),t,n,r)}function RR(e){return typeof e=="object"&&e!==null}function bR(e){if(!RR(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 wi(e){let t=Ne(e,ul);if(!Pn(t))return null;try{return bR(JSON.parse(cR(t,"utf-8")))}catch{return null}}function En(e,t){try{uR(Ne(e,ul),JSON.stringify(t,null,2),"utf-8")}catch{}}function ml(e){return Date.now()<new Date(e.expiresAt).getTime()}function wn(e){let t=wi(e);return t?ml(t)?Pn(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function SR(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return fR}function CR(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return gR}function TR(){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 hR}function _n(e,t,n,r,o,i){let s=new Date;return{clonedAt:s.toISOString(),expiresAt:new Date(s.getTime()+SR()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{}}}function xn(e){let t=Ne(e,"..");try{Pn(t)||lR(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 _i(e){try{Pn(e)&&Tn(e,{recursive:!0,force:!0})}catch{}}function Cn(e){try{return pR(e).isDirectory()}catch{return!1}}function Pt(e){try{return dR(e)}catch{return[]}}function*fl(e){for(let t of Pt(e)){let n=Ne(e,t);if(Cn(n))for(let r of Pt(n)){let o=Ne(n,r);if(Cn(o))for(let i of Pt(o)){let s=Ne(o,i);Cn(s)&&(yield s)}}}}function cl(e){for(let t of[...Pt(e)]){let n=Ne(e,t);if(Cn(n)){for(let r of[...Pt(n)]){let o=Ne(n,r);if(Cn(o)&&Pt(o).length===0)try{Tn(o,{recursive:!0,force:!0})}catch{}}if(Pt(n).length===0)try{Tn(n,{recursive:!0,force:!0})}catch{}}}}function PR(e){let t=0;for(let n of fl(e))try{let r=wi(n);(!r||!ml(r))&&(Tn(n,{recursive:!0,force:!0}),t++)}catch{}return t}function ER(e){let t=[];for(let n of fl(e)){let r=wi(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??qn(n)})}return t}function wR(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{Tn(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function gl(e){if(!Pn(e))return 0;let t=0;try{t+=PR(e)}catch{return t}cl(e);let n=wR(ER(e),CR(),TR());return t+=n,n>0&&cl(e),t}function hl(e){return gl(ll(e))}function xi(e){return gl(dl(e))}var yl=120*1e3,AR=30*1e3,Rl=[...Lr,"GIT_TERMINAL_PROMPT"];async function bl(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await kR();let a=e.branch??await ke(r,o,t),c=vt(),u=pl(c,r,o,a,i),l=wn(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};hl(c),_i(u),xn(u);let d=IR(t,n);if(i){if(await OR(r,o,a,u,i,d),!_R(xR(u,i)))throw _i(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 LR(r,o,a,u,d);let m=_n(r,o,a,"clone",i);return En(u,m),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}async function LR(e,t,n,r,o){let i=Cl(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Sl(e,t),r),await Ai(i,yl,`full clone of ${e}/${t}`,o)}async function OR(e,t,n,r,o,i){let s=Cl(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Sl(e,t),r),await Ai(s,yl,`sparse clone of ${e}/${t}`,i),await Ai(["-C",r,"sparse-checkout","set","--skip-checks","--",o],AR,`sparse-checkout set ${o}`,void 0)}function Sl(e,t){return`https://github.com/${e}/${t}.git`}function Cl(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function IR(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function kR(){try{if(!(await Tt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Rl,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 Ai(e,t,n,r){let o=await Tt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Rl,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 Tl(e){let{queries:t,authInfo:n}=e,r=Me(n);return Y(t,async(o,i)=>Ae({toolName:S.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!kr(s,"cloneRepo"))return ye(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",S.GITHUB_CLONE_REPO);let a;try{a=await bl(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return _(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=qn(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 he(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{writeFileSync as Pl,mkdirSync as Li,existsSync as An,rmSync as FR,readdirSync as MR,statSync as El}from"node:fs";import{join as vr,dirname as wl,resolve as Oi,sep as Ii}from"node:path";var NR=50,DR=5*1024*1024,HR=300*1024,GR=5,UR=1e4,BR=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 _l(e,t,n,r,o,i=!1){let s=vt(),a=Ei(s,e,t,r),c=Oi(vr(a,n));if(!c.startsWith(a+Ii)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=wn(a);if(u.hit&&!i&&An(c)){let C=jR(c,a);return{localPath:c,repoRoot:a,files:C.files,fileCount:C.fileCount,totalSize:C.totalSize,cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await re(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(C=>{if(C.type!=="file"||!C.download_url||C.size>HR)return!1;let w=va(C.name,{lowercase:!0,leadingDot:!0});return!BR.has(w)}).slice(0,NR),p=o?.token,f=await zR(m,GR,p),g=0,h=[];for(let{entry:C,content:w}of f){if(g+w.length>DR)break;g+=w.length,h.push({entry:C,content:w})}xi(s),xn(a),An(c)&&FR(c,{recursive:!0,force:!0}),Li(c,{recursive:!0,mode:448});let b=[];for(let{entry:C,content:w}of h){let T=Oi(vr(a,C.path));if(!T.startsWith(a+Ii))continue;let A=wl(T);An(A)||Li(A,{recursive:!0,mode:448}),Pl(T,w,"utf-8"),b.push({path:C.path,size:w.length,type:"file"})}let R=_n(e,t,r,"treeFetch");return En(a,R),{localPath:c,repoRoot:a,files:b,fileCount:b.length,totalSize:g,cached:!1,expiresAt:R.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function xl(e,t,n,r,o,i=!1){let s=vt(),a=Ei(s,e,t,r),c=Oi(vr(a,n));if(!c.startsWith(a+Ii)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=wn(a);if(!i&&u.hit&&An(c))return{localPath:c,repoRoot:a,path:n,size:VR(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await ir({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}`)}xi(s),xn(a);let d=wl(c);An(d)||Li(d,{recursive:!0,mode:448}),Pl(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,p=_n(e,t,m,"treeFetch");return En(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 zR(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 $R(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var QR=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function $R(e,t){try{let o=new URL(e);if(!QR.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(),UR);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 jR(e,t){let n=[],r=0;function o(i){let s;try{s=MR(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=vr(i,a);try{let u=El(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 VR(e){try{return El(e).size}catch{return 0}}function KR(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 Al(e,t){return e&&t?`${e}/${t}`:void 0}function Ll(e){return{keywords:e.keywords??[],projectId:Al(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 Ol(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 YR(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Il(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}=YR(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:KR(g.context)};g.positions?.length>0&&(h.matchIndices=g.positions.map(([b,R])=>({start:b,end:R,lineOffset:(g.context??"").substring(0,b).split(`
|
|
31
|
+
`).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,...Ol(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function kl(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 vl(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 XR(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Fl(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(XR),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Al(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 JR(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function ZR(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 qR(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:ZR(e)}}function Ml(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=JR(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,u=qR(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}:{},...Ol(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 Nl(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 Dl(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 Hl(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??St.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 Gl(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 eb(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 Fr(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=eb(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function Mr(e,t,n){let r=xr(e,[...t]);return{structuredContent:ct(e),text:r,isError:n}}function Ul(e){return typeof e=="object"&&e!==null}function De(e){return typeof e=="string"&&e.length>0?e:void 0}function Ve(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function tb(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}var nb=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function rb(e){if(!Ul(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 nb){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function ob(e,t){return`${e}/${t}`}function ib(e,t,n){let r=ob(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 sb(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 ab(e,t){let n=rb(e.pagination),r=sb(n,t);return{path:De(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:De(e.localPath),repoRoot:De(e.repoRoot),...Ve(e.fileSize)!==void 0?{fileSize:Ve(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:Ve(e.totalLines),sourceChars:Ve(e.sourceChars),sourceBytes:Ve(e.sourceBytes),resolvedBranch:De(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:Ve(e.startLine),endLine:Ve(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:De(e.lastModified),lastModifiedBy:De(e.lastModifiedBy),warnings:tb(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:De(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function cb(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Ul).map(o=>({path:De(o.path)??"",size:Ve(o.size)??0,type:De(o.type)??"file"}));return{path:String(t.path??""),localPath:De(e.localPath)??"",repoRoot:De(e.repoRoot),fileCount:Ve(e.fileCount)??r.length,totalSize:Ve(e.totalSize)??0,...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:De(e.resolvedBranch)}}function ub(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=ib(n,s,a),u=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(cb(u,i)),c.directories=d;return}let l=c.files??[];l.push(ab(u,i)),c.files=l}),Array.from(n.values())}function lb(e,t){return Fr(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 Bl(){return({queries:e,results:t})=>{let n=ub(t,e),r=lb(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),Mr(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}async function zl(e){let{queries:t,authInfo:n}=e,r=Me(n);return Y(t,async(o,i)=>{try{let s=Te(Rr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?db(a,n,c):pb(a,n,c)}catch(s){return ye(s,o,void 0,S.GITHUB_FETCH_CONTENT)}},{toolName:S.GITHUB_FETCH_CONTENT,finalize:Bl()},e)}async function db(e,t,n){let r=ge();if(!(r.local.enabled&&r.local.enableClone))return _("Directory fetch requires local clone support. Set ENABLE_LOCAL=true and ENABLE_CLONE=true.",e);if(!kr(n,"fetchDirectoryToDisk"))return ye(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",S.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return _("Directory fetch requires both owner and repo.",e,{rawResponse:0});let o=e.branch??await ke(e.owner,e.repo,t),i=await _l(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 he(e,s,!0,S.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??F(i)})}async function pb(e,t,n){let r=await ut(e,()=>n.provider.getFileContent(Nl(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await mb(e,t):void 0,i={...Dl(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 he(e,i,s,S.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function mb(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await ke(e.owner,e.repo,t);return xl(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function fb(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 gb(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 hb(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function yb(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 Rb(e,t,n){return t.length===0?[]:[{id:e.length===1&&typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",data:{files:yb(t),...n?{pagination:n}:{}}}]}function bb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sb(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${bb(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function Cb(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?hb(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:Sb(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:Tb(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 Tb(e,t){return{...e,matches:t}}function Ql(){return({queries:e,results:t})=>{let n=[],r,o=0,i=[],s=!1;t.forEach((f,g)=>{if(f.status==="error")return;let h=fb(f);h.incompleteResults&&(s=!0),h.results.reduce((C,w)=>C+w.matches.length,0)===0&&i.push({id:f.id,...h.nonExistentScope?{nonExistentScope:!0}:{},...h.incompleteResults?{incompleteResults:!0}:{}});let R=h.results;n.push({id:f.id,groups:R}),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=Cb(gb(n),a),u=Fr(t),l=r&&o===1?r:void 0,d=e.some(f=>f.concise===!0),m=Rb(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."]),Mr(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 Pb(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function Eb(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 $l(e){let{queries:t}=e,n=Me(e.authInfo);return Y(t,async(r,o)=>{try{let i=Eb(r);if(i)return _(i.error,r);if(!Pb(r))return _("At least one search term or scope filter is required.",r);let s=n(),a=await ut(r,()=>s.provider.searchCode(Ll(r)));if(a.ok===!1)return a.result;let c=Il(a.response.data,r);return he(r,c,c.results.length>0,S.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ye(i,r,void 0,S.GITHUB_SEARCH_CODE)}},{toolName:S.GITHUB_SEARCH_CODE,finalize:Ql()},e)}function wb(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 _b(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 xb(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function jl(e){let{content:t,reviewMode:n}=e,r=wb(t,n),o=_b(t,n),i=xb(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 Fi(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Dr(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Mi(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 Gr(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 Wl(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Kl(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function Ab(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Hr(e,t,n){return Ab({...Kl(e,t),...n})}function Vl(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Hr(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function ki(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Hr(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Lb(e,t,n){return{target:Kl(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 Nr(e){return String(e.path??e.filename??"")}function Ob(e,t){return{path:Nr(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function Ib(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 kb(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=Ib(r,n.comments),i=Fi(t),s=i?o.filter(u=>Dr(u.body,i)):o,{items:a,pagination:c}=Mi(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(u=>{let l=Gr(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:Wl(typeof u.body=="string"?u.body:"")},createdAt:u.createdAt,updatedAt:u.updatedAt}}),commentPagination:c}}function vb(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Fi(t);return{reviews:(o?r.filter(s=>Dr(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Gr(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 Fb(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Mi(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 Mb(e){return e.split(`
|
|
32
32
|
`).filter(t=>{if(!t.startsWith("+"))return!0;let n=t.slice(1).trim();return n!==""&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")}).map(t=>t.startsWith("+")?"+"+t.slice(1).replace(/\s*\/\/.*$/,"").trimEnd():t).join(`
|
|
33
|
-
`)}function
|
|
33
|
+
`)}function Nb(e){return e.replace(/\n{3,}/g,`
|
|
34
34
|
|
|
35
|
-
`)}function
|
|
36
|
-
`)[0]??f;return{sha:d.sha,date:p,message:f,messageHeadline:h,url:d.html_url,author:{name:u?.name??"unknown",email:u?.email??"",...d.author?.login?{login:d.author.login}:{}},...m?{committer:{name:m.name??"unknown",email:m.email??"",...d.committer?.login?{login:d.committer.login}:{}}}:{}}}),c={page:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await Promise.all(a.map(async(d,u)=>{try{let m=o.data[u]?.sha??d.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let f=e.path,h=p.data.files?.find(R=>R.filename===f||R.previous_filename===f);if(h)return{...d,additions:h.additions,deletions:h.deletions,status:h.status,...h.patch!==void 0?{patch:Zc(h.patch,e.charLength)}:{},...h.previous_filename?{previousFilename:h.previous_filename}:{}}}else{let f=e.path,h=(p.data.files??[]).filter(R=>!f||R.filename.startsWith(f)).map(R=>({filename:R.filename,status:R.status,additions:R.additions,deletions:R.deletions,...R.patch!==void 0?{patch:Zc(R.patch,e.charLength)}:{},...R.previous_filename?{previousFilename:R.previous_filename}:{}}));return{...d,files:h}}}catch{}return d}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return Z(n)}}async function qc(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{let s=Ln.safeParse(o);if(!s.success){let O=s.error.issues.map(K=>K.message).join("; ");return _(`Validation error: ${O}`,o)}if(s.data.type==="commits"){let O=s.data;if(!O.owner||!O.repo)return _("owner and repo are required for commits mode.",o);let K=O.path,pe=K&&!K.endsWith("/")?"file":"repo";if(pe==="file"&&!K)return _("path is required when querying a specific file in commits mode.",o);let Se=await Jc({type:pe,owner:O.owner,repo:O.repo,path:K,branch:O.branch,since:O.since,until:O.until,author:O.author,page:Number(O.page)||1,perPage:Number(O.perPage)||30,includeDiff:!!O.includeDiff,charLength:typeof O.charLength=="number"?O.charLength:void 0},n);if(Tt(Se)){let cn=Se.status===429||Se.error?.toString().toLowerCase().includes("rate limit")||!1;return _(Se,o,{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,hintContext:{type:"commits",path:K,isRateLimited:cn,status:Se.status,retryAfter:Se.retryAfter},hintSourceError:Se})}let{commits:De,pagination:vt}=Se.data,Vo=De.length>0,hr=[];vt.hasMore&&vt.nextPage&&hr.push(`${De.length} commit${De.length===1?"":"s"} returned \u2014 re-call with page:${vt.nextPage} for more.`);let Wo=/#(\d+)/;if(Vo){let cn=De.find(ln=>{let Ft=ln.messageHeadline;return typeof Ft=="string"&&Wo.test(Ft)});if(cn){let ln=cn.messageHeadline,Ft=Wo.exec(ln);Ft&&hr.push(`Merge commits embed PR refs \u2014 e.g. "${ln}" \u2192 use ghHistoryResearch(owner:"${O.owner}", repo:"${O.repo}", prNumber:${Ft[1]}) to read that PR's body, diffs, comments, and reviews.`)}}return ye(o,Se.data,Vo,S.GITHUB_SEARCH_PULL_REQUESTS,{hintContext:{type:"commits",path:K,matchCount:De.length,hasMorePages:vt.hasMore},extraHints:hr,rawResponse:Se.rawResponseChars})}let a=r(),c={...s.data},l=Qc(c),d=[],u=c.prNumber!==void 0;!u&&jc(l)&&d.push('Broad PR search returns metadata only. Re-call with prNumber and content selectors (body, changedFiles, patches, comments, commits) or reviewMode="full" to fetch PR content.'),u||(c.content=void 0,c.reviewMode=void 0);let m=!u&&((c.keywordsToSearch?.length??0)>0||!!c.query);if(m&&!c.created&&(c.state==="merged"||c.merged===!0)&&!c.sort&&!c.order?d.push(`To find the PR that first introduced a feature: sort:"created" order:"asc". Use match:["title"] for title-only and query:'"exact phrase"' for phrase matching.`):m&&!c.created&&!c.sort&&!c.order&&d.push('Archaeology tip: add state:"merged" sort:"created" order:"asc" to find the oldest matching merged PR. Use match:["title"] for title-only matching.'),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return _("At least one valid search parameter, filter, or PR number is required.",o);let h=await ot(c,()=>a.provider.searchPullRequests(kc(c)));if(h.ok===!1)return h.result;let R=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:b,resultData:g,pagination:C}=vc(h.response.data,{includeFileChanges:R}),E=c.prNumber!==void 0?void 0:C;c.prNumber!==void 0&&delete g.pagination;let L=!u&&(!!o.content||!!o.reviewMode),I={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},k=c.minify==="standard",j=u,P=b.map(O=>Yc(O,c,L?I:l,k,j));g.pull_requests=P,!u&&c.concise===!0&&(g.pull_requests=P.map(O=>{let K=O;return`#${K.number} ${K.title}`}));let x=P.length>0,A=E?Lt({currentPage:E.currentPage,totalPages:E.totalPages,hasMore:E.hasMore,totalMatches:E.totalMatches,entriesPerPage:E.perPage},"PRs"):[],B=x?[`Found ${P.length} PR${P.length===1?"":"s"}.`,...j?Xc(P,l):[]]:[],N=[],M=b.filter(O=>(typeof O.changedFilesCount=="number"?O.changedFilesCount:Array.isArray(O.fileChanges)?O.fileChanges.length:0)>30);if(M.length>0){let O=M.map(pe=>`#${pe.number}`).join(", "),K=Math.max(...M.map(pe=>typeof pe.changedFilesCount=="number"?pe.changedFilesCount:Array.isArray(pe.fileChanges)?pe.fileChanges.length:0));N.push(`Large PR(s) ${O} have ${K}+ file changes.`)}let oe=l.body||l.changedFiles||l.patches.mode!=="none"||!!l.comments||l.reviews||!!l.commits;!R&&!(u&&oe)&&b.filter(K=>typeof K.changedFilesCount=="number"&&K.changedFilesCount>0).length>0&&N.push('Metadata mode: changedFiles details omitted (changedFilesCount available). Re-call with prNumber + content.changedFiles=true for file paths, content.patches={mode:"selected",files:["src/foo.ts"]} for targeted diffs, or reviewMode="full" for all content in one call.');let ce=u&&typeof c.matchString=="string"&&c.matchString.trim()?[`matchString filter active \u2014 pagination totals count only items matching "${c.matchString.trim()}"; drop matchString for the full set.`]:[],Q=Mg({data:g,pullRequests:b,extraHints:[...B,...A,...d,...N,...ce]},c);return ye(c,Q.data,x,S.GITHUB_SEARCH_PULL_REQUESTS,{hintContext:{matchCount:P.length,state:c.state,owner:c.owner,repo:c.repo,author:c.author,keywords:c.keywordsToSearch,prNumber:c.prNumber,prMatch:c.match},extraHints:Q.extraHints,rawResponse:h.response.rawResponseChars})}catch(s){return he(s,o)}},{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"],peerHints:!0},e)}function Mg(e,t){return{data:e.data,extraHints:e.extraHints}}function el(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}function Ng(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function Hg(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(Ng)},extraHints:n?["Minimal owner/repo list \u2014 re-run without concise (or ghViewRepoStructure) to dive into a chosen repo."]:[]}}function go(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function yo(e){return!!(e.keywords&&e.keywords.length>0)}function Dg(e){return!!(yo(e)||go(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function tl(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Gg(e){let t=go(e),n=yo(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:tl(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:tl(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function $g(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function Bg(e,t){return[...e].sort((n,r)=>{let o=Ug(n,r,t.sort);if(o!==0)return o;let i=nl(r,t)-nl(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:ho(n).localeCompare(ho(r))})}function Ug(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return el(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function nl(e,t){let n=zg(t),r=ho(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(d=>d.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((d,u)=>o===u||r===u?d+80:o.includes(u)||r.includes(u)?d+40:s.includes(u)?d+35:i.includes(u)?d+10:d,0)+(c&&a===c?20:0)}function zg(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function ho(e){return`${e.owner}/${e.repo}`}function Qg(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore}}function jg(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function Vg(e){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages} for merged topic+keyword results (~${e.totalMatches??0} upper-bound total). Next: page=${e.currentPage+1}.`]:[]}function rl(e){return e.flatMap(t=>{let n=t.label==="topics"?"Topic search":t.label==="keywords"?"Keyword search":"Search",r=t.response.error||"Provider error";return`${n} failed: ${r}`})}function Wg(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??$(n.response.data??n.response)),0)}var Kg=100;function Yg(e,t,n=!1,r=0){if(t)return n&&r>Kg&&!e.owner&&!e.language&&!e.stars?['Large result set with no owner/language/stars filter \u2014 add owner="<org>" to scope to a specific org, language="<lang>" to restrict by language, or stars=">100" to surface established repos.']:void 0;let o=go(e),i=yo(e),s=typeof e.stars=="string"?e.stars:void 0,a=typeof e.created=="string"?e.created:void 0,c=typeof e.updated=="string"?e.updated:void 0,l=[];o&&i?l.push("No match for topics AND keywords. Drop topics, then keywords."):o?l.push("No topic match. Drop one, try synonyms, or use keywords."):i&&l.push("No keyword match. Drop the rarest, try synonyms, or use topics.");let d=[];if(s&&d.push(`stars="${s}"`),a&&d.push(`created="${a}"`),c&&d.push(`updated="${c}"`),d.length>0&&l.push(`Filters (${d.join(", ")}) \u2014 try widening/removing.`),l.length!==0)return l}async function ol(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{if(!Dg(o))return _("At least one repository search term or filter is required.",o);let s=r(),a=Gg(o),{successes:c,failures:l}=await lc(a.map(O=>({meta:{label:O.label,query:O.query},operation:()=>s.provider.searchRepos(Ic(O.query))}))),d=c.map(O=>({label:O.meta.label,query:O.meta.query,response:O.response})),u=l.map(O=>({label:O.meta.label,query:O.meta.query,response:O.response}));if(d.length===0){let O=u[0];return O?Dn(O.response,o):he(new Error("Repository search produced no provider results"),o)}let m=o.limit,p=Bg($g(d.flatMap(O=>Oc(O.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,h=d.some(O=>O.response.data.nonExistentScope),R=f.length===0&&h?[`Owner "${o.owner??"?"}" doesn't exist or isn't searchable \u2014 verify spelling/access, not filters.`]:[],b=d.length===1?d[0]:void 0,g=d.length>1,C=g?jg(d):b?.response.data.pagination,E=C?g?Vg(C):Lt(C,"repos"):[],L=C?Qg(C):void 0,I=o.page,k=C?.totalPages??0,j=typeof I=="number"&&k>0&&I>k&&f.length===0,P=j?[`page ${I} exceeds totalPages ${k} \u2014 last page is ${k}.`]:[],x=f.length>0,A=!!C?.hasMore,B=C?.totalMatches??C?.reachableTotalMatches??0,N=j?void 0:Yg(o,x,A,B),M=a.length>1&&d.length===1?[`Only ${b?.label??"one"} search succeeded; pagination reflects that subset.`,...rl(u)]:rl(u),oe=Hg({repositories:f,pagination:L},o),ae=[];if(x){let O=f[0];O?.owner&&O?.repo&&ae.push(`Top result: ${O.owner}/${O.repo} \u2014 use ghViewRepoStructure to browse or ghSearchCode to search within it.`),f.length>=3&&ae.push("Use multiple ghViewRepoStructure queries in parallel to compare the layouts of top results.")}let Q=[...P,...R,...oe.extraHints,...M,...E,...N||[],...ae];return ye(o,oe.data,x,S.GITHUB_SEARCH_REPOSITORIES,{extraHints:Q,hintContext:j?{}:{keywords:o.keywords,owner:o.owner,language:o.language,topic:o.topicsToSearch?.[0]},rawResponse:Wg([...d,...u])})}catch(s){return he(s,o)}},{toolName:S.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"],peerHints:!0},e)}var Xg=5;function Zg(e){if(!e||typeof e!="object")return[];let t=[],n=[];for(let r of Object.values(e)){let o=r;if(Array.isArray(o.folders))for(let i of o.folders)typeof i=="string"&&t.push(`${i}/`);if(Array.isArray(o.files))for(let i of o.files)typeof i=="string"&&n.push(i)}return[...t,...n]}function Jg(e,t){return Zg(e).slice(0,t)}function qg(e){return!e.owner||!e.repo?void 0:`${e.truncated||e.hasMore?"Structure page is partial":"Structure complete"} - use ghSearchCode(owner="${e.owner}", repo="${e.repo}") to find patterns, or ghGetFileContent to read specific files.`}function ey(e,t,n){if(!n)return[];let r=Jg(e,Xg);if(r.length===0)return[];let o=t>r.length?` (+${t-r.length} more)`:"";return[`Next paths: ${r.join(", ")}${o}`]}function ty(e){let t=e.currentPage??1,n=e.totalPages??t+1,r=e.totalEntries,o=e.entriesPerPage,i=typeof r=="number"&&typeof o=="number"?` (showing ${Math.min(t*o,r)} of ${r})`:"";return`Page ${t}/${n}${i}. Next: page=${t+1}`}function ny(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...Array.isArray(e.hints)?{hints:e.hints}:{}}}function ry(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Ut(o))continue;let i=r.files.filter(a=>!Pt(a)),s=r.folders.filter(a=>!Ut(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function il(e){let{queries:t,authInfo:n}=e,r=ve(n);return X(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await ot(o,()=>s.provider.getRepoStructure(Nc(o,c)));if(l.ok===!1)return ny(l.result,o);let d=Object.keys(l.response.data.structure??{}).length>0,u=ry(l.response.data.structure),m=Object.keys(u).length>0,p=d&&!m,f=!!l.response.data.summary?.truncated,h=Hc(l.response.data,o,u,c),R="branchFallback"in h?h.branchFallback:void 0,b=l.response.data.hints||[],g=R?[`WARNING: Branch '${String(R.requestedBranch)}' not found. Showing '${String(R.actualBranch)}' (default branch). Re-query with the correct branch name if branch-specific results are required.`]:[],C=Object.values(u).reduce((x,A)=>x+A.files.length+A.folders.length,0),E=h.pagination,L=!!E?.hasMore,I=m&&!L?qg({owner:o.owner,repo:o.repo,truncated:f,hasMore:!1}):void 0,k=L?[ty(E??{})]:[...b,...I?[I]:[]],j=[];if(L){let x=E?.currentPage??1,A=E?.totalPages;j.push(`Tree paginated (page ${x}${A?` of ${A}`:""}); use page=${x+1} to fetch the remaining entries.`)}else f&&j.push(`Tree truncated at maxDepth=${o.maxDepth??"default"}; re-query with a deeper maxDepth or a more specific path to see the rest.`);let P=oy({data:h,entryCount:C,wasTruncated:f,extraHints:k},o);return ye(o,P.data,m,S.GITHUB_VIEW_REPO_STRUCTURE,{hintContext:{entryCount:C,path:o.path,depth:o.maxDepth,branch:o.branch,wasFilteredToEmpty:p,flagFiles:Object.values(u).flatMap(x=>x.files.filter(A=>/(Mode|Config|Flag|Feature)\.[A-Za-z0-9]+$/.test(A)))},prefixHints:g,extraHints:[...j,...P.extraHints],rawResponse:l.response.rawResponseChars})}catch(s){return he(s,o,"Failed to explore repository structure")}},{toolName:S.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"],peerHints:!0},e)}function oy(e,t){let n=ey(e.data.structure,e.entryCount,e.wasTruncated);return{data:e.data,extraHints:[...n,...e.extraHints]}}import{existsSync as sl}from"fs";import{delimiter as iy,dirname as sy,join as al}from"path";function cl(){return process.platform==="win32"?"npm.cmd":"npm"}function ay(){let e=sy(process.execPath);return al(e,cl())}function cy(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function ly(){let e=(process.env.PATH??"").split(iy).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...cy()])]}function uy(){let e=ay();if(sl(e))return{command:process.execPath,argsPrefix:[e]};let t=cl();for(let n of ly()){let r=al(n,t);if(sl(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var dy=["view","search","ping","config","whoami"],py=[...$n,...ja];async function Jt(e,t,n={}){if(!dy.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Bn(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=uy(),c=await mt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:py});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var qt=new Map,my=5,Ro=3e4;function en(e){try{return new URL(e).host||e}catch{return e}}var bo=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}};function ll(e,t=Date.now()){let n=qt.get(en(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Ro)throw new bo(en(e),Ro-r);n.state="half-open"}}function So(e){let t=qt.get(en(e));t&&(t.failures=0,t.state="closed")}function ul(e,t=Date.now()){let n=en(e),r=qt.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=my&&(r.state="open",r.openedAt=t)),qt.set(n,r)}function dl(e,t=Date.now()){let n=qt.get(en(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Ro:!1}var fy=6e4;function pl(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function hy(e,t,n,r){e&&et({limit_type:"primary",retry_after_seconds:pl(r),api_method:t,api_url:n,provider:e}).catch(He("fetch rate-limit session logging"))}function gy(e,t,n,r,o){e.body?.cancel?.().catch(He("response body cancellation")),H("fetchWithRetries",Je.FETCH_HTTP_ERROR.code).catch(He("fetch retry session logging"));let i=new Error(Je.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&ei(r),e.status===429&&hy(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function yy(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=pl(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function st(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=fy,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:d}=t,u=e;if(a){let R=e.includes("?")?"&":"?";u=`${e}${R}version=${encodeURIComponent(ct)}`}let m={"User-Agent":`Octocode-MCP/${ct}`,...i},p=globalThis.fetch;if(!p)throw H("fetchWithRetries",Je.FETCH_NOT_AVAILABLE.code).catch(He("fetch retry session logging")),new Error(Je.FETCH_NOT_AVAILABLE.message);ll(u);let f,h=n+1;for(let R=1;R<=h;R++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(u,{method:s,headers:m,signal:c});if(!b.ok)throw gy(b,s,u,d,l);if(b.status===204)return So(u),null;let g=await b.json();return So(u),g}catch(b){let g=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(g&&g.retryable===!1)throw b;if(f=b instanceof Error?b:new Error(String(b)),R===h)break;let C=yy(R,r,o,g);await new Promise(E=>setTimeout(E,C))}}throw ul(u),await H("fetchWithRetries",Je.FETCH_FAILED_AFTER_RETRIES.code),new Error(Je.FETCH_FAILED_AFTER_RETRIES.message(h,f?.message||""))}import{z as T}from"zod";var nr=T.looseObject({name:T.string(),version:T.string(),repository:T.union([T.string(),T.object({url:T.string().optional(),type:T.string().optional(),directory:T.string().optional()})]).optional(),main:T.string().optional(),module:T.string().optional(),type:T.string().optional(),exports:T.unknown().optional(),types:T.string().optional(),typings:T.string().optional(),description:T.string().optional(),keywords:T.array(T.string()).optional(),license:T.union([T.string(),T.object({type:T.string().optional()})]).optional(),homepage:T.string().optional(),author:T.union([T.string(),T.object({name:T.string().optional(),email:T.string().optional(),url:T.string().optional()})]).optional(),maintainers:T.array(T.object({name:T.string().optional(),email:T.string().optional()})).optional(),engines:T.record(T.string(),T.string()).optional(),dependencies:T.record(T.string(),T.string()).optional(),devDependencies:T.record(T.string(),T.string()).optional(),peerDependencies:T.record(T.string(),T.string()).optional(),time:T.record(T.string(),T.string().optional()).optional()}),Ry=T.looseObject({package:T.looseObject({name:T.string().nullish(),version:T.string().nullish(),description:T.string().nullish(),links:T.looseObject({npm:T.string().nullish(),homepage:T.string().nullish(),repository:T.string().nullish()}).nullish()}),score:T.looseObject({final:T.number().nullish(),detail:T.looseObject({quality:T.number().nullish(),popularity:T.number().nullish(),maintenance:T.number().nullish()}).nullish()}).nullish()}),ml=T.looseObject({objects:T.array(Ry),total:T.union([T.number(),T.string()]).optional()}),fl=T.union([T.string(),T.boolean(),T.number(),T.null(),T.record(T.string(),T.unknown())]);var or="https://registry.npmjs.org",by=3e3,rr=null;async function Sl(){if(rr)return rr;try{let e=await Jt("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return rr=t,t}}catch{}return rr=or,or}function yt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var Sy="https://api.npmjs.org/downloads/point/last-week";function Le(e){return e===void 0?0:$(e)}async function Cl(e){try{let t=`${Sy}/${encodeURIComponent(e)}`,n=await st(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Le(n)}}catch{return{rawResponseChars:0}}}function ir(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Pl(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function Cy(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function Py(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function hl(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function gl(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function Ey(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Co(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=yt(e.repository):(e.repository.url&&(r=yt(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:Ey(e),...o?{repositoryDirectory:o}:{},...hl(e.exports)?{exports:hl(e.exports)}:{},...gl(e.bin,e.name)?{bin:gl(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function Ty(e){return typeof e.links?.repository=="string"?yt(e.links.repository):typeof e.repository=="string"?yt(e.repository):typeof e.repository?.url=="string"?yt(e.repository.url):null}function wy(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:Ty(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function El(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function Tl(e){try{let t=await Sl(),n=El(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await st(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Le(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await st(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Le(i)}}catch{return{rawResponseChars:0}}}async function Po(e,t,n){let[r,o]=await Promise.all([Cl(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Tl(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function sr(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function _y(e,t){try{let n=await Jt("view",[e,"--json"],{timeout:by});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...sr(c)?{}:{errorDetail:c},rawResponseChars:Le(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Le(o),s=nr.safeParse(o);return s.success?{pkg:Co(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...sr(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function xy(e,t){try{let n=await Sl(),r=El(e),o=`${n}/${r}/latest`,i;try{i=await st(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let d=l instanceof Error?l.message:String(l);return d.includes("404")||d.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:d,rawResponseChars:0}}let s=Le(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=nr.safeParse(i);return a.success?{pkg:Co(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...sr(r)?{}:{errorDetail:r},rawResponseChars:0}}}function Ay(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function wl(e,t){let n=0,r;for(let o of Ay(e)){let i;try{i=await st(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);sr(l)||(r=l);continue}if(n+=Le(i),!i||typeof i!="object")continue;let s=nr.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Co(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Eo(e,t=!1){let[n,r]=await Promise.allSettled([_y(e,t),xy(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?Po(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function Ly(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Eo(e,t);if(!r){if(o){let s=Pl(o);if(s&&n){let a=await wl(e,t);if(a.pkg){let c=await Po(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function Iy(e,t,n,r=0){let o=Math.max(t+r,t),i=await Jt("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Le(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Le(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let d=[...a].sort((f,h)=>{let R=f?.score?.final??0;return(h?.score?.final??0)-R}).slice(r,r+t),u=await Promise.all(d.map(async f=>{if(!f||typeof f!="object")return null;let h=f;if(!h.name)return null;if(n){let R=await Eo(h.name,!0);if(R.pkg)return R}return{pkg:wy(h),rawResponseChars:0}})),m=u.map(f=>f?.pkg).filter(f=>!!f),p=u.reduce((f,h)=>f+(h?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function Oy(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${or}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await st(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`NPM registry search failed: ${f instanceof Error?f.message:String(f)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Le(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=ml.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(h=>h.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let d=[...c.data.objects].sort((f,h)=>{let R=f.score?.final??0;return(h.score?.final??0)-R}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),u=await Promise.all(d.map(async f=>{if(n){let h=await Eo(f.name,!0);if(h.pkg)return h}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?yt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=u.map(f=>f.pkg).filter(f=>!!f),p=u.reduce((f,h)=>f+h.rawResponseChars,0);return{packages:m,totalFound:Py(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function yl(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await st(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Le(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Le(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?yt(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Le(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Rl(e,t,n,r=0){try{let o=await Iy(e,t,n,r);if(!("error"in o))return o}catch{}return Oy(e,t,n,r)}async function bl(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):Cl(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Tl(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function _l(e,t,n,r=0){let o=Pe("npm-search",{name:e,limit:t,metadata:n,from:r});return Ee(o,async()=>{if(dl(or)){if(r===0&&t===1&&ir(e)){let d=await wl(e,n);if(d.pkg){let u=await Po(e,d.pkg,d.rawResponseChars);return{packages:u.pkg?[u.pkg]:[],totalFound:u.pkg?1:0,rawResponseChars:u.rawResponseChars}}}let l=await yl(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&ir(e)){let l=await Ly(e,n,t===1);if("error"in l){if(!Pl(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Rl(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return bl(s);let a=Cy(e);if(a!==e){let l=await Rl(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return bl(l)}let c=await yl(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function To(e){try{let t=await Jt("view",[e,"deprecated","--json"]);if(t.error||t.exitCode!==0)return null;let n=t.stdout.trim();if(!n||n==="undefined"||n==="")return{deprecated:!1};try{let r=JSON.parse(n),o=fl.safeParse(r),i=o.success?o.data:n;return{deprecated:!0,message:typeof i=="string"?i:"This package is deprecated"}}catch{return{deprecated:!0,message:n}}}catch{return null}}async function xl(e){let t=ir(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return _l(e.name,n,!0,r)}function ky(e){return"error"in e}function It(e){return"npmUrl"in e}function wo(e){return It(e)&&e.path?e.path:e.name}function Al(e){return It(e)?e.repoUrl:e.repository}function vy(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function Fy(e){if(!e)return{};let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);return t?.[1]&&t[2]?{owner:t[1],repo:t[2].replace(/\.git$/,"").replace(/\/$/,"")}:{}}function My(e){let t=wo(e),n=Al(e),r={name:t};It(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.weeklyDownloads=e.weeklyDownloads)),n&&(r.repository=n);let o=vy(It(e)?e.repositoryDirectory:void 0);return o&&(r.repositoryDirectory=o),r}function Ny(e,t){let n=[],r=wo(e);t?.deprecated&&n.push(`DEPRECATED: ${r} \u2014 ${t.message??"use an alternative"}`);let o=It(e)?e.source:void 0;o==="cdn"?n.push("Metadata from npm CDN cache \u2014 verify version when registry access is restored."):o==="web"&&n.push("Metadata from npms.io fallback \u2014 verify version when registry access is restored."),n.push(`Install: npm install ${r}`);let i=Al(e),{owner:s,repo:a}=Fy(i);return s&&a?n.push(`Browse source: use ghViewRepoStructure owner=${s} repo=${a}`):i?n.push(`Repository: ${i} \u2014 use ghSearchRepos to find on GitHub.`):n.push(`No repository URL for "${r}" \u2014 use ghSearchRepos to find the source repo.`),n}function Hy(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=Math.max(1,Math.ceil(t/i));return{currentPage:o,totalPages:s,perPage:i,totalFound:t,returned:n,hasMore:o<s}}function Dy(e){if(e.totalFound===0||e.totalPages<=1)return[];if(e.currentPage>e.totalPages)return[`Requested page ${e.currentPage}/${e.totalPages} is past the end. Retry page=${e.totalPages}.`];let t=(e.currentPage-1)*e.perPage+1,n=Math.min(t+e.returned-1,e.totalFound);return e.hasMore?[`Page ${e.currentPage}/${e.totalPages} (showing ${t}-${n} of ${e.totalFound} packages). Next: page=${e.currentPage+1}`]:[]}function Gy(e,t){return[`Found ${e}${t>e?` of ${t}`:""} packages. Re-run with an exact name for source details, install command, and repo navigation.`]}async function Ll(e){return X(e.queries,async t=>{try{if(!t.packageName)return _("Package name is required for package search",t);let n=await xl({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(ky(n))return _(n.error,t,{rawResponse:n,customHints:[...n.hints??[],...se(S.PACKAGE_SEARCH,"error",{originalError:n.error})]});let r=n.packages,o=r.map(My),i=o.length>0,s=r.length>1||n.totalFound>1,a=Hy(t,n.totalFound,o.length,s),c=null;if(!s&&i&&r[0]){let u=It(r[0])?r[0].source:void 0;u!=="cdn"&&u!=="web"&&(c=await To(wo(r[0])))}let l=[...Dy(a),...i?s?Gy(o.length,n.totalFound):Ny(r[0],c):se(S.PACKAGE_SEARCH,"empty",{name:t.packageName})];return ye(t,{packages:o,pagination:a},i,S.PACKAGE_SEARCH,{extraHints:l,rawResponse:n.rawResponseChars??n})}catch(n){return _(n,t,{customHints:se(S.PACKAGE_SEARCH,"error",{originalError:n instanceof Error?n.message:String(n)})})}},{toolName:S.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"],peerHints:!0},e)}import{open as $y,readFile as By,stat as Uy}from"fs/promises";import{ContentSanitizer as zy}from"octocode-security/contentSanitizer";var Ie={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500};function Ol(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Il(e,t,n){return{...e,...Ol(t,n)}}function Qy(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range.",hints:["fullContent and matchString are mutually exclusive. Pick one \u2014 matchString is more token-efficient when you know what to look for."]};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections.",hints:["fullContent and startLine/endLine are mutually exclusive. Pick one extraction mode so line ranges are never silently ignored."]};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file.",hints:["matchString and startLine/endLine are mutually exclusive. Use matchString for search-driven extraction or startLine/endLine for a known range."]};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`,hints:[`Add endLine to complete the range, e.g. endLine=${e.startLine+50}.`,"Use matchString for search-driven extraction when you do not know the exact end line."]}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`,hints:["Add startLine to complete the range, e.g. startLine=1.","Use matchString for search-driven extraction when you do not know the exact start line."]}:null}async function jy(e,t){try{return{fileStats:await Uy(t)}}catch(n){let r=ke.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:_(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t},hintContext:{path:e.path}})}}}function Vy(e,t){return t>Ie.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function Wy(e,t,n){let r=ke.fileTooLarge(e.path,n,Ie.LARGE_FILE_THRESHOLD_KB);return _(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t},hintContext:{fileSize:n*1024,isLarge:!0}})}function Ky(e,t){let n=ke.binaryFileUnsupported(e.path);return _(n,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t},customHints:["Binary or non-UTF-8 content."]})}async function Yy(e){let n=Buffer.alloc(8192),r;try{r=await $y(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let d=l===9||l===10||l===13;l<32&&!d&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(pa("binary sample handle close",void 0))}}async function Xy(e,t){try{return{content:await By(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?ke.fileAccessFailed(e.path,r):ke.fileReadFailed(e.path,r);return{errorResult:_(i,e,{toolName:S.LOCAL_FETCH_CONTENT,hintContext:{path:e.path},extra:{resolvedPath:t}})}}}function Zy(e,t){let n=[`No matches for "${e.matchString}" in ${e.path} (${t} line${t===1?"":"s"} scanned).`];return e.matchStringIsRegex?n.push("Regex is per-line only \u2014 verify the pattern fits on one line."):n.push('Try matchStringIsRegex=true for pattern matching (e.g. "export.*function").'),e.matchStringCaseSensitive&&n.push("caseSensitive=true is active \u2014 disable for fuzzier matching."),{status:"empty",errorCode:G.NO_MATCHES,totalLines:t,hints:n}}function Jy(e,t,n){let r=bn(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Zy(e,n)};let o=r.lines.join(`
|
|
37
|
-
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,d
|
|
38
|
-
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function
|
|
39
|
-
`),o=r.length;return e.matchString?Jy(e,r,o):qy(e)?eR(e,r,o):{resultContent:t,isPartial:!1}}function nR(e){if(e.isPartial===!0&&e.matchRanges===void 0&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.totalLines=="number"&&e.endLine<e.totalLines){let t=e.totalLines-e.endLine;return[`More content: use startLine=${e.endLine+1} to continue (${t} line${t===1?"":"s"} remaining)`]}return[]}function rR(e,t){return t.matchRanges!==void 0?["Use the matched line numbers as lineHint anchors for lspGetSemantics, or increase contextLines for more surrounding code."]:e.minify==="symbols"?[]:["Use localSearchCode to find related occurrences, or lspGetSemantics with a symbolName + lineHint from this file."]}function oR(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r,hints:se(S.LOCAL_FETCH_CONTENT,"empty")};let a=[...t.warnings??[]],c=String(e.path),l=i?U.applyContentViewMinification(t.resultContent,c):t.resultContent,d=e.charLength,u=e.charOffset??0,m=d,p=!1,f=u;m===void 0&&l.length>o&&(m=o,p=!0,a.push(`Auto-paginated: Content (${l.length} chars) exceeds ${o} char limit`));let h="char-limit",R=m;if(m!==void 0){let P=Rn(l,f,m,c);h=P.chunkMode,R=P.length}let b=wt(l,f,R,m!==void 0?{pageSize:m}:void 0),g=t.isPartial||b.hasMore,C=nR({isPartial:g,startLine:t.actualStartLine,endLine:t.actualEndLine,totalLines:r,matchRanges:t.matchRanges}),E=rR(e,t),L=m||p?ps(b,{toolName:S.LOCAL_FETCH_CONTENT}):[],I,k=[];if(b.hasMore&&h==="char-limit"&&gn(b.paginatedContent)){let P=b.charOffset+b.charLength;if(I=yn(l,P,c),I!==void 0){let x=I-P;k.push(`Page cut mid-block at char ${P}. Next top-level definition at char ${I}. Re-request with charLength=${(R??b.charLength)+x} to extend this page to the next boundary, or use charOffset=${P} to continue page-by-page.`)}}let j=[];if(r>2e3&&e.minify!=="symbols"&&!e.matchString&&!e.startLine&&!e.endLine&&!e.fullContent&&b.hasMore){let P=Math.max(1,r-200);j.push(`Large file (${r} lines) \u2014 minify:"symbols" for an export index, or startLine=${P} for the tail.`)}return e.minify!=="none"&&r>300&&!e.matchString&&j.push('If you need exact comment text (// \u2026 or /* \u2026 */), test assertions, or doc-strings, re-fetch with minify:"none" and add matchString to anchor on the relevant section.'),{path:c,content:b.paginatedContent,...s!=="standard"&&{contentView:s},...g&&{isPartial:g},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...(m!==void 0||u>0||p)&&{pagination:{...Mi(b),chunkMode:h,...I!==void 0&&{nextBlockChar:I}}},...a.length>0&&{warnings:a},hints:[...C,...k,...L,...j,...E]}}function iR(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function kl(e){let t=$e();try{let n=Re(e,S.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=Qy(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await jy(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await Yy(o))return D(Ky(e,o),c);if(Vy(e,l))return D(Wy(e,o,l),c);let{content:d,errorResult:u}=await Xy(e,o);if(u||d===void 0)return u;let m=zy.sanitizeContent(d,i),p=m.content,f=p.length,h=Buffer.byteLength(p,"utf-8"),R=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,b=e.minify,g=b==="standard"||b==="symbols",C=g?"standard":"none",E;if(b==="symbols"){let P=U.extractSignatures(p,i);if(P===null&&(E=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),P!==null){let x=p.split(`
|
|
40
|
-
`)
|
|
41
|
-
`).length,I=tR(e,p,t),k=P=>{let x=[...E?[E]:[],...R?[R]:[]];if(x.length===0)return P;let A=P.warnings??[];return{...P,warnings:[...A,...x]}};if(I.earlyResult){let P=I.earlyResult.content,x=g&&typeof P=="string"?{...I.earlyResult,content:U.applyContentViewMinification(P,i)}:I.earlyResult;return D(Il(k(_o(iR(x,C),e,L)),f,h),f)}let j=oR(e,I,s,L,t,g,C);return D(Il(k(_o(j,e,L)),f,h),f)}catch(n){return _(n,e,{toolName:S.LOCAL_FETCH_CONTENT})}}function _o(e,t,n){return e}async function vl(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=In.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await kl(r.data)}}),{toolName:S.LOCAL_FETCH_CONTENT,peerHints:!0},e)}function Ot(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function tn(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var aR=["node_modules","dist",".git","coverage","build",".next",".nuxt",".svelte-kit",".turbo",".cache",".parcel-cache","out","target",".octocode",".cursor",".vscode",".idea",".claude",".context"];function cR(e,t){let n=t??aR,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}function lR(e){let{query:t,currentPage:n,totalPages:r,shownCount:o,totalFiles:i,wasFileCapped:s,maxFiles:a,discoveredFileCount:c,hasConfigFiles:l,extraHints:d=[]}=e,u=t,m=[];Array.isArray(u.names)&&u.names.length>0&&m.push(`names: ${u.names.join(", ")}`),u.entryType&&m.push(`entryType: ${u.entryType==="f"?"files":u.entryType==="d"?"directories":String(u.entryType)}`);let p=f=>typeof f=="string"&&!Nl.test(f)?" (skipped: invalid format)":"";return u.modifiedBefore&&m.push(`modified before: ${u.modifiedBefore}${p(u.modifiedBefore)}`),u.modifiedWithin&&m.push(`modified within: ${u.modifiedWithin}${p(u.modifiedWithin)}`),u.sizeGreater&&m.push(`size > ${u.sizeGreater}`),u.sizeLess&&m.push(`size < ${u.sizeLess}`),Array.isArray(u.excludeDir)&&u.excludeDir.length>0&&m.push(`excluding: ${u.excludeDir.join(", ")}`),[...d,...m.length>0?[`Active filters \u2014 ${m.join(" | ")}`]:[],...n<r?[`Page ${n}/${r} (${o} of ${i}). Next: page=${n+1}`]:[],...r>0&&n>r?[`Requested page ${n} is outside available range (1-${r}). Use page=${r} for the last page.`]:[],...s?[`Results capped at ${a} of ${c} discovered. All ${a} are reachable via page; to see the rest, narrow with names/entryType/time filters. Note: sorting applies only within the capped set \u2014 limit is a pre-sort discovery cap.`]:[],...i===0?se(S.LOCAL_FIND_FILES,"empty",{fileCount:i,hasConfigFiles:l,path:t.path,names:t.names,modifiedWithin:t.modifiedWithin,sizeGreater:t.sizeGreater,sizeLess:t.sizeLess}):[u.entryType==="f"?`Found ${i} file${i===1?"":"s"}. Use localSearchCode to search or localGetFileContent to read.`:u.entryType==="d"?`Found ${i} director${i===1?"y":"ies"}. Use localViewStructure to browse or localSearchCode to search.`:`Found ${i} entr${i===1?"y":"ies"} \u2014 pass entryType="f" for files, entryType="d" for directories. Use localSearchCode or localGetFileContent.`]]}async function Fl(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Re(e,S.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:cR(i.path,i.excludeDir)},a=mR(s),c=e.limit??1e4,l=U.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),d=l.totalDiscovered,u=l.wasCapped,m=l.entries.map(N=>uR(N,r)),p=e.sortBy||"modified";dR(m,p,r);let f=[],h=pR(m,t,n),R=h.length,b=e.itemsPerPage||20,g=e.page||1,C=Math.max(1,Math.ceil(R/b)),E=(g-1)*b,L=Math.min(E+b,R),k=h.slice(E,L),j=/\.(config|rc|env|json|ya?ml|toml|ini)$|^(\..*rc|config\.|\.env)/i,P=k.some(N=>j.test(N.path.split("/").pop()||"")),x=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],A=[...a,...x],B={...R===0?{status:"empty"}:{},path:i.path,files:k,pagination:{currentPage:g,totalPages:C,filesPerPage:b,totalFiles:R,hasMore:g<C,...u?{totalFilesFound:d}:{}},...A.length>0&&{warnings:A},hints:lR({query:e,currentPage:g,totalPages:C,shownCount:k.length,totalFiles:R,wasFileCapped:u,maxFiles:c,discoveredFileCount:d,hasConfigFiles:P,extraHints:f})};return D(Ml(B,e,{totalFiles:R}),l.entries.reduce((N,M)=>N+M.path.length,0))}catch(o){return _(o,e,{toolName:S.LOCAL_FIND_FILES})}}function uR(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function Ml(e,t,n){return e}function dR(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function pR(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=Ot(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var Nl=/^\d+[hdwm]$/;function mR(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!Nl.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}async function Hl(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=On.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await Fl(r.data)}}),{toolName:S.LOCAL_FIND_FILES,peerHints:!0},e)}import{existsSync as Ke,readFileSync as fR}from"node:fs";import{dirname as xo,join as We}from"node:path";import{spawnSync as hR}from"node:child_process";import{fileURLToPath as gR}from"node:url";import{securityRegistry as yR}from"octocode-security/registry";import{normalizeCommandName as RR}from"octocode-security/commandValidator";var rn=xo(gR(import.meta.url)),nn=null;function ar(){return nn!==null||(nn=CR(),SR(nn)),nn}var bR=/^rg(-[a-z0-9-]+)?$/i;function SR(e){let t=RR(e);if(!(t==="rg"||!bR.test(t)))try{yR.addAllowedCommands([t])}catch{}}function CR(){let e=PR();if(e)return e;let t=ER();if(t)return t;let n=wR();if(n)return n;let r=_R();if(r)return r;let o=xR();if(o)return o;throw new Error("ripgrep (rg) is unavailable. Install it via: npm i -g octocode-mcp OR brew install ripgrep OR apt install ripgrep")}function PR(){let e=process.env.OCTOCODE_RG_PATH;return e&&Ke(e)?e:null}function ER(){let e=Dl();if(!e)return null;let t=TR();if(t)try{let s=JSON.parse(fR(t,"utf8")).rg?.find(a=>a.platform===e);if(s){let a=We(xo(t),s.file);if(Ke(a))return a}}catch{}let n=process.platform==="win32"?".exe":"",r=[`rg-${e}${n}`,`rg${n}`],o=[We(rn,"runtime","rg"),We(rn,"..","runtime","rg"),We(rn,"..","..","runtime","rg")];for(let i of o)for(let s of r){let a=We(i,s);if(Ke(a))return a}return null}function TR(){let e=[We(rn,"runtime-assets.json"),We(rn,"..","runtime-assets.json")];for(let t of e)if(Ke(t))return t;return null}function wR(){try{let e=process.execPath;if(/[/\\](node|bun)(\.exe)?$/.test(e))return null;let t=xo(e),n=process.platform==="win32"?".exe":"",r=We(t,`rg${n}`);if(Ke(r))return r;let o=Dl();if(o){let i=We(t,`rg-${o}${n}`);if(Ke(i))return i}}catch{}return null}function _R(){if(process.env.OCTOCODE_DISABLE_VSCODE_RIPGREP==="1")return null;try{let e=gr("@vscode/ripgrep");if(e.rgPath&&typeof e.rgPath=="string"&&Ke(e.rgPath))return e.rgPath}catch{}try{let e=process.env.npm_config_arch||process.arch,t=process.platform==="win32"?"rg.exe":"rg",n=`@vscode/ripgrep-${process.platform}-${e}`,r=gr.resolve(`${n}/bin/${t}`);if(Ke(r))return r}catch{}return null}function xR(){try{let t=process.platform==="win32"?"where.exe":"which",n=hR(t,["rg"],{encoding:"utf8",timeout:3e3});if(n.status===0&&n.stdout){let r=(n.stdout.trim().split(`
|
|
42
|
-
|
|
43
|
-
`).filter(Boolean).filter(n=>!Bl(n)).map(n=>({path:n,matchCount:1,matches:[]}))}function OR(e){return e.trim().split(`
|
|
44
|
-
`).filter(Boolean).filter(n=>!Bl(n)).map(n=>{let r=n.lastIndexOf(":");if(r===-1)return{path:n,matchCount:1,matches:[]};let o=n.slice(0,r),i=parseInt(n.slice(r+1),10);return{path:o,matchCount:isNaN(i)?1:i,matches:[]}})}function Bl(e){return/^\d+\s/.test(e)&&/\b(?:files|bytes|seconds|matches|searched|printed|spent)\b/.test(e)}function Ul(e,t){let n=t.countLinesPerFile||t.countMatchesPerFile,r=t.filesOnly||t.filesWithoutMatch;if(n){let o=OR(e),i=o.reduce((s,a)=>s+(a.matchCount??0),0);return{files:o,stats:{matchCount:i}}}else return r?{files:IR(e),stats:{}}:$l(e,t)}async function kt(e,t,n,r,o){let i=e;i.sort((ce,Q)=>vR(ce,Q,t));let s=i,a=!1;t.maxFiles&&i.length>t.maxFiles&&(s=i.slice(0,t.maxFiles),a=!0);let c=s.length,l=!!(t.filesOnly||t.filesWithoutMatch),d=!!(t.countLinesPerFile||t.countMatchesPerFile),u=l||d,m=s.reduce((ce,Q)=>ce+(Q.matchCount??0),0),p=u?o?.matchCount??m:m,f=t,h=f.itemsPerPage||Ie.DEFAULT_FILES_PER_PAGE,R=f.page||1,b=Math.ceil(c/h),g=(R-1)*h,C=Math.min(g+h,c),E=s.slice(g,C),L=f.maxMatchesPerFile||Ie.DEFAULT_MATCHES_PER_PAGE,I=E.map(ce=>{let Q=ce.matches?.length??0,O=Math.ceil(Q/L),K=Math.max(1,f.matchPage||1),pe=(K-1)*L,Se=Math.min(pe+L,Q),De=u?void 0:ce.matches?.slice(pe,Se);return{path:ce.path,...l?{}:{matchCount:d?ce.matchCount||1:Q},...De!==void 0&&{matches:De},pagination:!u&&Q>L?{currentPage:K,totalPages:O,matchesPerPage:L,totalMatches:Q,hasMore:K<O}:void 0}}),k=R<b?[`Page ${R}/${b} (${I.length} of ${c} files${l?"":`, ${p} matches`}). Next: page=${R+1}`]:b>0&&R>b?[`Page ${R} is outside range (1\u2013${b}). Use page=${b}.`]:[];a&&k.push(`Results limited to ${t.maxFiles} files (found ${i.length} matching)`);let j=I.filter(ce=>ce.pagination?.hasMore);j.length>0&&k.push(`Note: ${j.length} file(s) have more matches \u2014 use matchPage=${(f.matchPage||1)+1} with maxMatchesPerFile to continue matches inside those files`);let P=kR(I,t,p),x=t,A=[],B=x.include;Array.isArray(B)&&B.length>0&&A.push(`include: ${B.join(", ")}`);let N=x.exclude;Array.isArray(N)&&N.length>0&&A.push(`exclude: ${N.join(", ")}`);let M=x.excludeDir;Array.isArray(M)&&M.length>0&&A.push(`excludeDir: ${M.join(", ")}`);let oe=x.langType;oe&&A.push(`langType: ${oe}`),x.caseSensitive&&A.push("case-sensitive"),x.wholeWord&&A.push("whole-word"),A.length>0&&P.unshift(`Active filters \u2014 ${A.join(" | ")}`);let ae={files:I,pagination:{currentPage:R,totalPages:b,filesPerPage:h,totalFiles:c,...l?{}:{totalMatches:p},hasMore:R<b,...a?{totalFilesFound:i.length}:{}},...r.length>0?{warnings:r}:{},hints:[...c>0&&!u?["Use localGetFileContent with the full path (prepend base to each returned path) and line numbers to read surrounding code.","Pass line numbers as lineHint to lspGetSemantics for definitions, references, or call flow."]:[],...c>0&&u?["Use localGetFileContent to read listed files, or rerun localSearchCode without filesOnly/count mode for matched snippets."]:[],...k,...P]};return zl(ae,t,{totalMatches:p,totalFiles:c})}function zl(e,t,n){return e}function kR(e,t,n){let r=[];if(n>100||e.length>20){let o=[];!t.langType&&!t.include&&o.push("add langType or include"),t.excludeDir?.length||o.push("add excludeDir"),(t.keywords?.length??0)<5&&o.push("lengthen pattern"),o.length>0&&r.push(`Large result set (${n} matches in ${e.length} files). Narrow: ${o.join(", ")}.`)}return r}function vR(e,t,n){let r=(t.matchCount??0)-(e.matchCount??0);return r!==0?r:e.path.localeCompare(t.path)}function dr(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};if(!e.fixedString){let o=FR(r);o&&t.push(`invalid regex: ${o}`)}return!e.fixedString&&MR(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&NR(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function FR(e){try{return new RegExp(e),null}catch(t){return t instanceof Error?t.message:"unknown regex parse error"}}function MR(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function NR(e){return/\(\?[=!<]/.test(e)}async function Ql(e){let t=[],n=HR(e);if(!n.isValid)return _(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=tt.safeParse(e);if(!r.success){let R=r.error.issues.map(b=>b.message);return _(new Error(`Query validation failed: ${R.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return _(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}});let s=Re(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=dr({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return _(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],d=new ur,{command:u,args:m}=d.fromQuery(a).build(),p=await _e(u,m);if(p.code===null){let R=Ie.DEFAULT_EXEC_TIMEOUT_MS;return D({status:"error",error:`Search timed out after ${R/1e3} seconds.`,errorCode:G.COMMAND_TIMEOUT,searchEngine:"rg",hints:[`Search timed out after ${R/1e3} seconds.`,"Try a more specific path or add langType/include filters to narrow the search.","Use filesOnly=true for faster discovery.","Consider excluding large directories with excludeDir.",...l]},p.stdout.length+p.stderr.length)}if(p.code===1||p.success&&!p.stdout.trim())return D({status:"empty",searchEngine:"rg",warnings:[...t,...l],hints:se(S.LOCAL_RIPGREP,"empty",{keywords:o.keywords,path:o.path,langType:o.langType,include:o.include,excludeDir:o.excludeDir,fixedString:o.fixedString,caseSensitive:o.caseSensitive,mode:o.mode})},p.stdout.length);if(!p.success){let b=p.code===2&&/No such file or directory/.test(p.stderr)?`Search path not found: ${o.path}. Verify it with localViewStructure or localFindFiles.`:`Ripgrep failed (exit code ${p.code}): ${p.stderr}`;return _(new Error(b),o,{toolName:S.LOCAL_RIPGREP,rawResponse:p.stdout.length+p.stderr.length})}let f=Ul(p.stdout,o);!a.filesOnly&&p.stdout.length>Ie.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p.stdout.length/1024)}KB).`);let h=await kt(f.files,o,"rg",[...t,...l],f.stats);return D(h,p.stdout.length)}var DR="Using grep fallback because bundled ripgrep is unavailable; advanced ripgrep-only options may be ignored.";async function Vl(e,t){let n=[],r=tt.safeParse(e);if(!r.success){let h=r.error.issues.map(R=>R.message);return _(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n}})}let o=r.data;if(!o.path)return _(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n}});let s=Re(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=dr({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return _(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...n,...c.warnings]}});let l=BR(n,c.warnings,t,o),{args:d,outputMode:u}=GR(a),m=await _e("grep",d);if(m.code===null){let h=Ie.DEFAULT_EXEC_TIMEOUT_MS;return D({status:"error",error:`Search timed out after ${h/1e3} seconds.`,errorCode:G.COMMAND_TIMEOUT,searchEngine:"grep",hints:[`Search timed out after ${h/1e3} seconds.`,"Try a more specific path or add include/exclude filters to narrow the search.","Use filesOnly=true for faster discovery.",...l]},m.stdout.length+m.stderr.length)}if(m.code===1||m.success&&!m.stdout.trim())return D({status:"empty",searchEngine:"grep",warnings:l,hints:[...se(S.LOCAL_RIPGREP,"empty",{keywords:o.keywords,path:o.path,langType:o.langType,include:o.include,excludeDir:o.excludeDir,fixedString:o.fixedString,caseSensitive:o.caseSensitive,mode:o.mode,searchEngine:"grep"}),"Try with ripgrep for better results when bundled ripgrep is repaired."]},m.stdout.length);if(!m.success)return _(new Error(`grep fallback failed (exit code ${m.code}): ${m.stderr}`),o,{toolName:S.LOCAL_RIPGREP,rawResponse:m.stdout.length+m.stderr.length});let p=UR(m.stdout,u),f=await kt(p.files,o,"grep",l,{matchCount:p.matchCount});return D({...f,searchEngine:"grep"},m.stdout.length)}function GR(e){let t=["-R","-H"];e.fixedString?t.push("-F"):e.perlRegex&&t.push("-E"),(e.caseInsensitive||$R(e))&&t.push("-i"),e.wholeWord&&t.push("-w"),e.invertMatch&&t.push("-v"),t.push("-I");let n=e.contextLines;n!==void 0&&n>0&&t.push("-C",String(n));let r=e.filesOnly?"files":e.countLinesPerFile||e.countMatchesPerFile?"count":"matches";r==="files"?t.push("-l"):r==="count"?t.push("-c"):t.push("-n");for(let o of e.include??[])t.push(`--include=${o}`);for(let o of e.exclude??[])t.push(`--exclude=${o}`);for(let o of e.excludeDir??[])t.push(`--exclude-dir=${o}`);return e.langType&&t.push(`--include=*.${e.langType}`),t.push("--",e.keywords??"",e.path),{args:t,outputMode:r}}function $R(e){return e.caseSensitive!==!0&&e.caseInsensitive!==!0&&(e.keywords??"")===(e.keywords??"").toLowerCase()}function BR(e,t,n,r){let o=[DR];n&&o.push(`Ripgrep unavailable: ${n}`),o.push(...e,...t);let i=[];return r.filesWithoutMatch&&i.push("filesWithoutMatch"),r.countMatchesPerFile&&i.push("countMatchesPerFile uses grep -c line counts"),r.hidden&&i.push("hidden"),r.noIgnore&&i.push("noIgnore"),r.multiline&&i.push("multiline"),r.multilineDotall&&i.push("multilineDotall"),(r.sort||r.sortReverse)&&i.push("sort"),i.length>0&&o.push(`grep fallback ignored/degraded options: ${i.join(", ")}.`),o}function UR(e,t){if(t==="files"){let i=jl(e).map(s=>({path:s,matchCount:1,matches:[]}));return{files:i,matchCount:i.length}}if(t==="count"){let i=jl(e).map(zR).filter(a=>a!==void 0),s=i.reduce((a,c)=>a+(c.matchCount??0),0);return{files:i,matchCount:s}}let n=new Map;for(let i of e.split(`
|
|
45
|
-
`)){if(
|
|
46
|
-
`
|
|
47
|
-
`,1)[0],column:g.startCol}))}))}if(m)return _(new Error(`Invalid structural ${o?"rule":"pattern"}: ${m}`),e,{toolName:S.LOCAL_RIPGREP,customHints:[o?"Check the YAML rule shape. Relational sub-rules (inside/has) need `stopBy: end` to walk all ancestors/descendants, else they silently match nothing.":"Check the pattern syntax. Use $X for a single node, $$$ARGS for a list. The pattern must be a complete code fragment for the target language."]});i?u>0&&c.push(`Pre-filter on "${i}" skipped parsing ${u} file(s); parsed ${d}.`):c.push(`No literal anchor in the ${o?"rule":"pattern"} \u2014 parsed all ${d} candidate file(s) with no text pre-filter.`);let f=await kt(a,e,"rg",c,{matchCount:l});if(l>0){let h=Array.isArray(f.hints)?[...f.hints]:[];return h.push("Structural matches return node ranges \u2014 pass matches[].line as the lspGetSemantics lineHint to navigate semantically."),{...f,hints:h}}return f}function JR(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Xl(e){let t=JR(e);if(t.mode==="structural")return await Yl(t);t.contextLines===void 0&&(t.contextLines=2);try{let n=await Gl("rg");return n.available?await Ql(t):await Vl(t,n.error)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:G.OUTPUT_TOO_LARGE,hints:["Output exceeded 10MB - your pattern matched too broadly. Think about why results exploded:","Is the pattern too generic? Make it specific to target what you actually need","Searching everything? Add langType filters or path restrictions to focus scope","For node_modules: Target specific packages rather than searching the entire directory","Need file names only? FIND_FILES searches metadata without reading content","Strategy: Start with filesOnly=true to see what matched, then narrow before reading content"]}:_(n,t,{toolName:S.LOCAL_RIPGREP})}}async function Zl(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=tt.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await Xl(r.data)}}),{toolName:S.LOCAL_RIPGREP,peerHints:!0},e)}var qR=new Set(["+","*","?"]),eb=1e3;function tb(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Jl(e,t){let n=e[t];return n===void 0?!1:qR.has(n)||n==="{"&&ob(e,t)}function nb(e,t,n){let r=n.pop()??!1,o=Jl(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?eu(e,t+1):t+1})}function rb(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:eu(e,t)})}function ql(e){if(e.length>eb)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=tb(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=nb(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Jl(e,r)){let i=rb(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function ob(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function eu(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function ib(e){return e.startsWith(".")?e.slice(1):e}function tu(e,t){let n=e;if(t.pattern){let o=t.pattern;if(o.includes("*")||o.includes("?")||o.includes("[")){let s=o.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");s=s.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let a=`^${s}$`;if(!ql(a).safe)return n=n.filter(d=>(d.name.includes("/")?d.name.split("/").pop():d.name).includes(o)),n;let l=new RegExp(a,"i");n=n.filter(d=>{let u=d.name.includes("/")?d.name.split("/").pop():d.name;return l.test(u)})}catch{n=n.filter(a=>(a.name.includes("/")?a.name.split("/").pop():a.name).includes(o))}}else n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(o))}let r=t.extensions&&t.extensions.length>0?t.extensions.map(ib):[];return r.length>0&&(n=n.filter(o=>o.type==="directory"||o.extension&&r.includes(o.extension))),t.directoriesOnly&&(n=n.filter(o=>o.type==="directory")),t.filesOnly&&(n=n.filter(o=>o.type==="file")),n}function nu(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function ru(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}function ou(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+tn(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Ot(r)})`}function iu(e,t){let n=e.length,r=t.itemsPerPage||Ie.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n);return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:i<o}}}function su(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function au(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}async function cu(e){try{let t=Re(e,S.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return sb(e,t.sanitizedPath,n)}catch(t){let n=ke.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode,hints:se(S.LOCAL_VIEW_STRUCTURE,"error")}}}function sb(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=cb(e),s=r&&e.limit&&!ab(e,i)?e.limit*2:1e4,a;try{a=U.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,entryType:lb(e),limit:s})}catch(A){return pb(A,e,t)}let c=a.entries.map(A=>ub(A,n,e.details??!1)),l=tu(c,e),d=e.sortBy??"name";l=l.sort((A,B)=>{let N=0;switch(d){case"size":{let M=A.sizeBytes??(A.size?tn(A.size):0),oe=B.sizeBytes??(B.size?tn(B.size):0);N=M-oe;break}case"time":n&&A.modified&&B.modified?N=A.modified.localeCompare(B.modified):N=A.name.localeCompare(B.name);break;case"extension":N=(A.extension||"").localeCompare(B.extension||"");break;default:N=A.name.localeCompare(B.name);break}return e.reverse?-N:N}),e.limit&&(l=l.slice(0,e.limit));let u=l.length,{paginatedEntries:m,endIdx:p,pagination:f}=iu(l,e),R=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(A=>({...ru(A),path:A.path??`${t.replace(/\/$/,"")}/${A.name}`}))}:{path:t,...nu(m)},b=[...a.warnings,...au({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],g=u===0,C=typeof e.pattern=="string"?e.pattern:void 0,E=(e.extensions?.length??0)>0||!!C,L=l.filter(A=>A.type==="file").length,I=E&&L===0&&!g,k={entryCount:u,path:e.path,extensions:e.extensions,pattern:C},j=g||I?se(S.LOCAL_VIEW_STRUCTURE,"empty",k):["Use localSearchCode to search or localGetFileContent to read discovered files."],P=su(l,m.length,f,p),x=ou(l);return D(lu({...g?{status:"empty"}:{},...R,summary:x,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b},hints:[...j,...P]},e),a.entries.reduce((A,B)=>A+B.path.length,0))}function ab(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t||(e.extensions?.length??0)>0)}function cb(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function lb(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function ub(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:Ot(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=db(e.permissions)),o}function db(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function pb(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=ke.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return _(a,t,{toolName:S.LOCAL_VIEW_STRUCTURE,customHints:o?[`Path not found: ${n}`]:i?[`Permission denied: ${n}`]:[`Cannot access path: ${n}`]})}function lu(e,t){return e}async function uu(e){let{queries:t}=e;return X(t||[],async n=>we({toolName:S.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=kn.safeParse(n);if(!r.success){let i=r.error.issues.map(s=>s.message).join("; ");return _(`Validation error: ${i}`,n)}return await cu(r.data)}}),{toolName:S.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"],peerHints:!0},e)}import{acquirePooledClient as Ru,isLanguageServerAvailable as bu}from"octocode-lsp/manager";import{resolveWorkspaceRootForFile as Su}from"octocode-lsp/workspaceRoot";import{safeReadFile as mb}from"octocode-lsp/validation";var du={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0};function on(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function pu(e,t,n){if(t<=0)return e;let r=await mb(e.uri);if(!r)return e;let o=r.split(/\r?\n/),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,d)=>{let u=s+d+1;return`${u===i+1?">":" "}${String(u).padStart(4," ")}| ${l}`}).join(`
|
|
48
|
-
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function fb(e,t){return Promise.all(e.map(async n=>({...n,from:await pu(n.from,t,n.fromRanges)})))}async function hb(e,t){return Promise.all(e.map(async n=>({...n,to:await pu(n.to,t)})))}async function Ao(e,t,n,r,o){if(n<=0||!e)return{calls:[],...du};try{let i=await e.getIncomingCalls(t),s=o>0?await fb(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=on(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Ao(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function Lo(e,t,n,r,o){if(n<=0||!e)return{calls:[],...du};try{let i=await e.getOutgoingCalls(t),s=o>0?await hb(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=on(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Lo(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}import{readFile as gb}from"node:fs/promises";import{SymbolResolver as yb,SymbolResolutionError as Rb}from"octocode-lsp/resolver";import{LSP_ERROR_CODES as mu}from"octocode-lsp/lspErrorCodes";async function Io(e,t){let n=e.uri,r=Re({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{return{ok:!0,value:{uri:o,absolutePath:o,content:await gb(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:mu.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function fu(e,t){let n=await Io(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new yb({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:bb(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof Rb)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:mu.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function bb(e){return{start:e,end:{line:e.line,character:e.character}}}var Sb=40,Cu=40,Cb=10,Pb=8;async function Pu(e){return X(e.queries||[],async t=>we({toolName:ge,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await kb(t);return Eb(Tb(t,n))}}),{toolName:ge,peerHints:!0,minQueryTimeoutMs:3e4},e)}function Eb(e){return D(e,$(e))}function Tb(e,t){return e.format!=="compact"||!wb(t)?t:_b(t)}function wb(e){return Rt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Rt(e.payload)}function _b(e){return{...e,format:"compact",payload:xb(e.payload)}}function xb(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(hu)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(Lb)}:{locations:(e.locations??[]).map(hu)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Eu(e.root)}:{},direction:e.direction,calls:e.calls.map(Ib),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(Ab)};case"hover":case"empty":return e}}function Ab(e){if(!Rt(e))return String(e);let t=xe(e,"line"),n=xe(e,"character"),r=xe(e,"endLine"),o=Xe(e,"kind"),i=Xe(e,"name"),s=xe(e,"childCount"),a=Xe(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function hu(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${wu(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function Lb(e){if(!Rt(e))return String(e);let t=Xe(e,"uri"),n=xe(e,"firstLine"),r=xe(e,"firstCharacter"),o=xe(e,"count"),i=Tu(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function Ib(e){if(!Rt(e))return String(e);let t=Xe(e,"direction"),n=Eu(e.item),r=Tu(e,"ranges").map(Ob).join(","),o=xe(e,"rangeCount"),i=xe(e,"rangeSampleCount"),s=Xe(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${wu(s,180)}`:""].filter(Boolean).join(" ")}function Eu(e){if(!Rt(e))return String(e);let t=Xe(e,"name"),n=Xe(e,"kind"),r=Xe(e,"uri"),o=xe(e,"line"),i=xe(e,"endLine"),s=xe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function Ob(e){return Rt(e)?`${xe(e,"line")}:${xe(e,"character")}`:String(e)}function Rt(e){return typeof e=="object"&&e!==null}function Xe(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function xe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Tu(e,t){let n=e[t];return Array.isArray(n)?n:[]}function wu(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function kb(e){if(e.type==="documentSymbols")return vb(e);let t=await fu(e,ge);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed",s=Array.isArray(t.error.hints)?t.error.hints:void 0;return Qb(e,i,s)}let n=e.workspaceRoot??await Su(t.value.uri);if(!await bu(t.value.uri,n))return Ye(e.type,t.value,"Language server unavailable");let o=await Ru(n,t.value.uri);if(!o)return Ye(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?Oo(e,t.value,"definition","definitionProvider",await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?Oo(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?Oo(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?Fb(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):Ye(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?Mb(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ye(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?Nb(e,t.value,o):Ye(e.type,t.value,"callHierarchyProvider unsupported",!0)}}async function vb(e){let t=await Io(e,ge);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Su(t.value.uri),r=await bu(t.value.uri,n),o=r?await Ru(n,t.value.uri):null,i=o?o.hasCapability("documentSymbolProvider")?await o.documentSymbols(t.value.uri,t.value.content):[]:[],s=!!o?.hasCapability("documentSymbolProvider"),a=Hb(Array.isArray(i)?i:[]),c=$b(Array.isArray(i)?i:[]),{pageItems:l,pagination:d}=mr(a,e.page??1,e.itemsPerPage??Sb),u=Bb(a,f=>f.kind),p=s?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(s?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...s?{provider:"documentSymbolProvider"}:{}},summary:{totalSymbols:a.length,returnedSymbols:l.length,topLevelSymbols:c,kinds:u},payload:{kind:"documentSymbols",symbols:l,...p?{empty:p}:{}},pagination:d,hints:[...d.hasMore?[pr(d,"symbols")]:[],...rt("documentSymbols",s)]}}function Oo(e,t,n,r,o){let i=o.length>0,s=o.map(Pr),{pageItems:a,pagination:c}=mr(s,e.page??1,e.itemsPerPage??Cu);return{type:e.type,uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{},hints:[...i&&c.hasMore?[pr(c,"locations")]:[],...rt(e.type,i)]}}function Fb(e,t,n){let r=n.map(l=>{let d=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...d?{isDefinition:!0}:{}}}),o=e.groupByFile?jb(r):void 0,i=o??r.map(Pr),{pageItems:s,pagination:a}=mr(i,e.page??1,e.itemsPerPage??Cu),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a,hints:[...a.hasMore?[pr(a,o?"reference files":"references")]:[],...rt("references",!0)]}}async function Mb(e,t,n){let r=Vb(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"},hints:rt(e.type,o)}}async function Nb(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Ye(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await Ao(n,o,i,new Set([on(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Lo(n,o,i,new Set([on(o)]),e.contextLines??0):s,l=g=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(g.to.uri),d=c.calls.filter(l).length,u=c.calls.filter(g=>!l(g)),m=[...a.calls.map(g=>({direction:"incoming",...g})),...u.map(g=>({direction:"outgoing",...g}))],p=m.map(g=>g.direction==="incoming"?Ub(g,e.contextLines??0):zb(g,e.contextLines??0)),{pageItems:f,pagination:h}=mr(p,e.page??1,e.itemsPerPage??Cb),R=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:vo(o),direction:R,calls:f,incomingCalls:a.calls.length,outgoingCalls:u.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...d>0&&{stdlibCallsExcluded:d}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:h,hints:[...h.hasMore?[pr(h,"calls")]:[],...rt(e.type,!0),...a.truncatedByDepth||c.truncatedByDepth?["Calls exist beyond the traversal depth \u2014 increase depth to follow the chain further."]:[]]}}function pr(e,t){let n=Math.min(e.currentPage*e.itemsPerPage,e.totalResults)-(e.currentPage-1)*e.itemsPerPage,r=e.nextPage??e.currentPage+1;return`Page ${e.currentPage}/${e.totalPages} (${n} of ${e.totalResults} ${t}). Next: page=${r}`}function mr(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function Hb(e){let t=[];for(let n of e)_u(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function _u(e,t,n){if(!e||typeof e!="object")return;let r=e,o=Gb(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:ko(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&Db.has(ko(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)_u(s,t,i)}}var Db=new Set(["file","module","namespace","package","class","enum","interface","struct"]);function Gb(e){if(gu(e.range))return e.range;let t=e.location;return t&&gu(t.range)?t.range:void 0}function gu(e){if(!e||typeof e!="object")return!1;let t=e;return yu(t.start)&&yu(t.end)}function yu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function $b(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Bb(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function Ub(e,t){let n=xu(e.fromRanges);return{direction:"incoming",item:vo(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Au(e.from,t)}}function zb(e,t){let n=xu(e.fromRanges);return{direction:"outgoing",item:vo(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Au(e.to,t)}}function vo(e){return{name:e.name,kind:ko(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function xu(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=Pb))break}return n}function Au(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function ko(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function Lu(e,t){return/unavailable/i.test(t)?"serverUnavailable":/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function Qb(e,t,n){let r=e.uri??"";return{type:e.type,uri:r,lsp:{},payload:{kind:"empty",category:Lu(e.type,t),reason:t},hints:n?.length?n:rt(e.type,!1)}}function Ye(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:bt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Lu(e,n),reason:n},hints:rt(e,!1)}}function jb(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function Vb(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>Wb(r)).join(`
|
|
49
|
-
`).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function Wb(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var Fo={hasTool(e){return Mr(e)},getDescription(e){return Fr[e]??""},getToolName(e){return S[e]??String(e)}};var Iu=(e,t=Fo)=>t.getDescription(e);function Kb(e,t){return t.getToolName(e)}function Fe(e,t,n){let r=Kb(t,e);return{...n,name:r,description:Iu(r,e)}}function Yb(e=Fo){let t=Fe(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:xs,inputSchema:As,executionFn:zc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=Fe(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:An,inputSchema:Ts,executionFn:Bc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=Fe(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Ds,inputSchema:Gs,executionFn:il,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=Fe(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Fs,inputSchema:Ms,executionFn:ol,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=Fe(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Ln,inputSchema:Os,executionFn:qc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=Fe(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Us,inputSchema:zs,executionFn:Ll,security:"remote",requiresServerRuntime:!0}}),a=Fe(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Wr,inputSchema:Cs,executionFn:Sc,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=Fe(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:tt,inputSchema:Js,executionFn:Zl,security:"basic"}}),l=Fe(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:kn,inputSchema:ta,executionFn:uu,security:"basic"}}),d=Fe(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:On,inputSchema:Ys,executionFn:Hl,security:"basic"}}),u=Fe(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:In,inputSchema:Vs,executionFn:vl,security:"basic"}}),m={name:ge,description:Iu(ge,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:sa,inputSchema:aa,executionFn:Pu,security:"basic",requiresServerRuntime:!0}},p=Fe(e,"LOCAL_BINARY_INSPECT",{isDefault:!1,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Mn,inputSchema:da,executionFn:ac,security:"basic"}});return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:d,LOCAL_FETCH_CONTENT:u,LSP_GET_SEMANTIC_CONTENT:m,LOCAL_BINARY_INSPECT:p,ALL_TOOLS:[t,n,r,o,i,s,a,c,l,d,u,m,p]}}var Ae=Yb(),lv=Ae.GITHUB_SEARCH_CODE,uv=Ae.GITHUB_FETCH_CONTENT,dv=Ae.GITHUB_VIEW_REPO_STRUCTURE,pv=Ae.GITHUB_SEARCH_REPOSITORIES,mv=Ae.GITHUB_SEARCH_PULL_REQUESTS,fv=Ae.PACKAGE_SEARCH,hv=Ae.GITHUB_CLONE_REPO,gv=Ae.LOCAL_RIPGREP,yv=Ae.LOCAL_VIEW_STRUCTURE,Rv=Ae.LOCAL_FIND_FILES,bv=Ae.LOCAL_FETCH_CONTENT,Sv=Ae.LSP_GET_SEMANTIC_CONTENT,Cv=Ae.LOCAL_BINARY_INSPECT,Ou=Ae.ALL_TOOLS;import{ContentSanitizer as Xb}from"octocode-security";import{maskSensitiveData as ku}from"octocode-security/mask";function fr(e){let t=e;if(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let r=Xb.sanitizeContent(n.text),o=r.hasSecrets?ku(r.content):ku(n.text);return{...n,text:o}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:nt(t.structuredContent)}}catch{}return t}var Zb="TOOL_CALLBACK_EXCEPTION";function vu(e,t){let n=Jb(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
50
|
-
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:Zb,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return fr(r)}catch{return r}}function Jb(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:qb(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function qb(e){try{return JSON.stringify(e)}catch{return}}import{withSecurityValidation as eS,withBasicSecurityValidation as tS}from"octocode-security";function Fu(e,t){let n=eS(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function Mu(e,t){let n=tS(r=>e(r),t);return(r,o)=>n(r,o)}import{releaseAllPooledClients as nS}from"octocode-lsp/manager";var Do=["GitHub","Local","LSP","Package","Other"],Nu=new Map([W.GITHUB_SEARCH_CODE,W.GITHUB_SEARCH_REPOSITORIES,W.GITHUB_SEARCH_PULL_REQUESTS,W.GITHUB_FETCH_CONTENT,W.GITHUB_VIEW_REPO_STRUCTURE,W.GITHUB_CLONE_REPO,W.LOCAL_RIPGREP,W.LOCAL_FIND_FILES,W.LOCAL_FETCH_CONTENT,W.LOCAL_VIEW_STRUCTURE,ge,W.PACKAGE_SEARCH].map((e,t)=>[e,t])),Qe=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},Mo=null,No=null,rS=["id","mainResearchGoal","researchGoal","reasoning"],Bo=new Set([...rS]),oS=["id","researchGoal","reasoning"],Hu=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function iS(e){return async t=>e(t)}function sS(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:iS(t.executionFn),security:t.security,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var Du=Ou.map(sS),aS=Du.map(Bu);function Uo(e){let t=Qo(e);return t?Bu(t):void 0}function sn(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")?"Local":e.startsWith("lsp")?"LSP":e===W.PACKAGE_SEARCH?"Package":"Other"}function cS(e){return[...e].sort((t,n)=>{let r=Do.indexOf(sn(t)),o=Do.indexOf(sn(n));if(r!==o)return r-o;let i=Nu.get(t)??Number.MAX_SAFE_INTEGER,s=Nu.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function lS(e){let t=Uo(e);if(!t)return"{}";try{return JSON.stringify(Ho.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(Ho.toJSONSchema(t.schema),null,2)}}function uS(e){return JSON.stringify(e??{},null,2)}function dS(e){let t=sn(e),n=[...oS];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function pS(){return Hu.map(e=>({...e}))}function mS(){return JSON.stringify(Object.fromEntries(Hu.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function fS(e,t){return t?.tools?.[e]?.description??e}function zo(e){let t=Uo(e);if(!t)return[];let n=Ho.toJSONSchema(t.schema);if(!an(n))return[];let r=at(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Bo.has(i)&&!$o(r[i])):[]);return Go(r,o)}function hS(e){let t=zo(e),n=t.filter(i=>i.required),r=n.length>0?n:t.slice(0,4),o={};for(let i of r)o[i.name]=ES(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===ge&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function gS(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Qe("Tool input must be valid JSON.")}return Gu(e,r,n)}function Gu(e,t,n={}){let r=RS(e,t,n),o=Qo(e);if(!o)throw new Qe(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Qe("Tool input does not match the expected schema.",yS(i.error));return i.data}function yS(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function RS(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(at(t)&&Array.isArray(t.queries))r=t.queries;else if(at(t))r=[t];else throw new Qe('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Qe("At least one query is required.");let o=at(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,l)=>{i=!0,n.onUnknownFields?.(c,l)}},a=r.map((c,l)=>bS(e,l,CS(e,c,l,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new Qe("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function bS(e,t,n,r){let o={...n},i=sn(e),s=r.sourceLabel??"direct tool execution",a=SS(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function SS(e,t){return`Execute ${e} via ${t}`}function CS(e,t,n,r={}){if(!at(t))throw new Qe("Tool input must be a JSON object or an array of objects.");let o=new Set([...zo(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Bo]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function PS(e){let t=[],n=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return n!==void 0&&r!==void 0?t.push(`${n}-${r}`):n!==void 0?t.push(`>=${n}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function $u(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let t=an(e.items)?e.items:void 0;return`array<${t?$u(t):"value"}>`}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Go(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Bo.has(o))continue;let s=an(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:$u(s),constraints:PS(s),description:typeof s.description=="string"?s.description:void 0}),at(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(d=>typeof d=="string"?!$o(s.properties?.[d]):!1):[]);r.push(...Go(s.properties,l,a))}let c=s.type==="array"&&an(s.items)?s.items:void 0;if(c&&at(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(d=>typeof d=="string"?!$o(c.properties?.[d]):!1):[]);r.push(...Go(c.properties,l,a))}}return r}function ES(e,t){if(t.startsWith("array<"))return[e];if(t==="integer"||t==="number")return 1;if(t==="boolean")return!0;if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;switch(e){case"path":return".";case"owner":return"bgauryy";case"repo":return"octocode";case"name":case"packageName":return"react";default:return e}}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function an(e){return at(e)}function $o(e){return an(e)&&"default"in e}async function TS(e,t){let n=Qo(e);if(!n)throw new Error(`Unknown tool: ${e}`);let r=wS(n,t);try{return await _S(n),e===W.GITHUB_CLONE_REPO&&!un()?fr({content:[{type:"text",text:`error: ghCloneRepo is disabled
|
|
51
|
-
message: Set ENABLE_CLONE=true (and ENABLE_LOCAL=true) to enable repository cloning.
|
|
52
|
-
hints:
|
|
53
|
-
- To browse without cloning, use ghViewRepoStructure to list files or ghGetFileContent to read specific files.`}],structuredContent:{status:"error",tool:e,code:"TOOL_DISABLED",error:{message:"ghCloneRepo is disabled \u2014 set ENABLE_CLONE=true (and ENABLE_LOCAL=true) to enable repository cloning."},hints:["To browse without cloning, use ghViewRepoStructure to list files or ghGetFileContent to read specific files."]},isError:!0}):await xS(n,r)}finally{e===ge&&await nS()}}function Bu(e){return{name:e.name,schema:e.schema,inputSchema:e.inputSchema}}function Qo(e){return Du.find(t=>t.name===e)}function wS(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function _S(e){e.requiresServerRuntime&&(Mo||(Mo=Xo()),await Mo),e.requiresProviders&&(No||(No=bs().then(()=>{})),await No)}async function xS(e,t){try{let n=e.security==="remote"?await AS(e,t):await LS(e,t);return fr(n)}catch(n){return vu(e.name,n)}}async function AS(e,t){return Fu(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function LS(e,t){return Mu(e.execute,e.name)(t)}import{completeMetadata as IS}from"@octocodeai/octocode-core";var jo=null;function OS(){return jo||(jo=IS),jo}async function kS(){return OS()}export{Do as DIRECT_TOOL_CATEGORIES,aS as DIRECT_TOOL_DEFINITIONS,Qe as DirectToolInputError,hS as buildDirectToolExampleQuery,TS as executeDirectTool,Uo as findDirectToolDefinition,Qm as formatCallToolResultForOutput,uS as formatDirectToolMetadataSchemaText,mS as formatDirectToolOutputSchemaText,lS as formatDirectToolSchemaText,dS as getDirectToolAutoFilledFields,sn as getDirectToolCategory,fS as getDirectToolDescription,zo as getDirectToolDisplayFields,pS as getDirectToolOutputFields,kS as loadToolContent,Gu as prepareDirectToolInput,gS as prepareDirectToolInputFromJsonText,cS as sortDirectToolNames};
|
|
35
|
+
`)}function Db(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(Nr(p))):o,a=Fi(t),c=a?s.filter(p=>Dr(Nr(p),a)||Dr(p.patch,a)):s,{items:u,pagination:l}=Mi(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=u.map(p=>{let f=Ob(p,!1);if(!d||typeof p.patch!="string")return f;let g=r&&!a?Mb(p.patch):p.patch,h=Gr(g,t.charOffset??0,t.charLength??12e3);return{...f,patch:h?.content??"",diff:fn(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(Nr).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function Ln(e){return typeof e=="object"&&e!==null}function vi(e){if(Ln(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Ni(e){if(Ln(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function Hb(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function Gb(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Ln(n))continue;let r=Ni(n.patchPagination);if(r?.hasMore)return r}}function Ub(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Ln(n))continue;let r=Ni(n.bodyPagination);if(r?.hasMore)return r}}function Bb(e,t,n,r){let o={},i=Ni(e.bodyPagination),s=vi(e.filePagination),a=vi(e.commentPagination),c=vi(e.commitPagination),u=Gb(e),l=Ub(e),d=Hb(n);i&&(o.body={...i,nextQuery:Vl(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:ki(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:ki(t,r,{comments:n.comments},"commentPage",a)}),l?.hasMore&&l.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...l,nextQuery:Hr(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:ki(t,r,{commits:n.commits},"commitPage",c)}),u&&n.patches.mode!=="none"&&(o.patches={...u,nextQuery:Vl(t,r,{patches:n.patches},u,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return Ln(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Hr(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function zb(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Yl(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?Nb(s):s,c=n.body?Gr(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:Wl(typeof e.body=="string"?e.body:void 0)}:{},...l?{next:Lb(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...Db(e,t,n,r),...kb(e,t,n),...vb(e,t,n),...Fb(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=Bb(f,t,n,i);return zb(f),g&&(f.contentPagination=g),f}function Qb(e){return e?e.includes('rel="next"'):!1}function Xl(e,t){if(e)return!t||e.length<=t?e:e.slice(0,t)}async function Jl(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=Qb(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(`
|
|
36
|
+
`)[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?Xl(g.patch,e.charLength):void 0;return{...l,additions:g.additions,deletions:g.deletions,status:g.status,...h!==void 0?{patch:h,diff:fn(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 b=h.patch!==void 0?Xl(h.patch,e.charLength):void 0;return{filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,...b!==void 0?{patch:b,diff:fn(b)}:{},...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 X(n)}}async function Zl(e){let{queries:t,authInfo:n}=e,r=Me(n);return Y(t,async(o,i)=>{try{let s=Te(br,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let A=s.data;if(!A.owner||!A.repo)return _("owner and repo are required for commits mode.",o);let G=A.path,$=G&&!G.endsWith("/")?"file":"repo";if($==="file"&&!G)return _("path is required when querying a specific file in commits mode.",o);let x=await Jl({type:$,owner:A.owner,repo:A.repo,path:G,branch:A.branch,since:A.since,until:A.until,author:A.author,page:Number(A.page)||1,perPage:Number(A.perPage)||30,includeDiff:!!A.includeDiff,charLength:typeof A.charLength=="number"?A.charLength:void 0},n);if(Ht(x))return _(x,o,{toolName:S.GITHUB_SEARCH_PULL_REQUESTS});let{commits:L}=x.data,z=L.length>0;return he(o,x.data,z,S.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:x.rawResponseChars})}let a=r(),c={...s.data},u=jl(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 _("At least one valid search parameter, filter, or PR number is required.",o);let m=await ut(c,()=>a.provider.searchPullRequests(Fl(c)));if(m.ok===!1)return m.result;let p=l?u.changedFiles||u.patches.mode!=="none":!1,{pullRequests:f,resultData:g}=Ml(m.response.data,{includeFileChanges:p});c.prNumber!==void 0&&delete g.pagination;let h=!l&&(!!o.content||!!o.reviewMode),b={...u,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},R=c.minify==="standard",C=l,w=f.map(A=>Yl(A,c,h?b:u,R,C));g.pull_requests=w,!l&&c.concise===!0&&(g.pull_requests=w.map(A=>{let G=A;return`#${G.number} ${G.title}`}));let T=w.length>0;return he(c,g,T,S.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:m.response.rawResponseChars})}catch(s){return ye(s,o,void 0,S.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}function ql(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 $b(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 jb(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($b)}}}function nd(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function rd(e){return!!(e.keywords&&e.keywords.length>0)}function Vb(e){return!!(rd(e)||nd(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 ed(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Wb(e){let t=nd(e),n=rd(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:ed(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:ed(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function Kb(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 Yb(e,t){return[...e].sort((n,r)=>{let o=Xb(n,r,t.sort);if(o!==0)return o;let i=td(r,t)-td(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Di(n).localeCompare(Di(r))})}function Xb(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 ql(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function td(e,t){let n=Jb(t),r=Di(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 Jb(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Di(e){return`${e.owner}/${e.repo}`}function Zb(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 qb(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 eS(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??F(n.response.data??n.response)),0)}async function od(e){let{queries:t,authInfo:n}=e,r=Me(n);return Y(t,async(o,i)=>{try{if(!Vb(o))return _("At least one repository search term or filter is required.",o);let s=r(),a=Wb(o),{successes:c,failures:u}=await al(a.map(T=>({meta:{label:T.label,query:T.query},operation:()=>s.provider.searchRepos(kl(T.query))}))),l=c.map(T=>({label:T.meta.label,query:T.meta.query,response:T.response})),d=u.map(T=>({label:T.meta.label,query:T.meta.query,response:T.response}));if(l.length===0){let T=d[0];return T?Ar(T.response,o):ye(new Error("Repository search produced no provider results"),o,void 0,S.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=Yb(Kb(l.flatMap(T=>vl(T.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,g=l.length===1?l[0]:void 0,b=l.length>1?qb(l):g?.response.data.pagination,R=b?Zb(b):void 0,C=f.length>0,w=jb({repositories:f,pagination:R},o);return he(o,w.data,C,S.GITHUB_SEARCH_REPOSITORIES,{rawResponse:eS([...l,...d])})}catch(s){return ye(s,o,void 0,S.GITHUB_SEARCH_REPOSITORIES)}},{toolName:S.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}function tS(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 nS(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&pn(o))continue;let i=r.files.filter(a=>!Dt(a)),s=r.folders.filter(a=>!pn(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function id(e){let{queries:t,authInfo:n}=e,r=Me(n);return Y(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),u=await ut(o,()=>s.provider.getRepoStructure(Hl(o,c)));if(u.ok===!1)return tS(u.result,o);let l=nS(u.response.data.structure),d=Object.keys(l).length>0,m=Gl(u.response.data,o,l,c);return he(o,m,d,S.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return ye(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{existsSync as sd}from"fs";import{delimiter as rS,dirname as oS,join as ad}from"path";function cd(){return process.platform==="win32"?"npm.cmd":"npm"}function iS(){let e=oS(process.execPath);return ad(e,cd())}function sS(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function aS(){let e=(process.env.PATH??"").split(rS).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...sS()])]}function cS(){let e=iS();if(sd(e))return{command:process.execPath,argsPrefix:[e]};let t=cd();for(let n of aS()){let r=ad(n,t);if(sd(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var uS=["view","search","ping","config","whoami"],lS=[...Lr,...Vu];async function Ur(e,t,n={}){if(!uS.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Or(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=cS(),c=await Tt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:lS});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var On=new Map,dS=5,Hi=3e4;function In(e){try{return new URL(e).host||e}catch{return e}}var Gi=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 ud(e,t=Date.now()){let n=On.get(In(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Hi)throw new Gi(In(e),Hi-r);n.state="half-open"}}function Ui(e){let t=On.get(In(e));t&&(t.failures=0,t.state="closed")}function ld(e,t=Date.now()){let n=In(e),r=On.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=dS&&(r.state="open",r.openedAt=t)),On.set(n,r)}function dd(e,t=Date.now()){let n=On.get(In(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Hi:!1}var pS=6e4;function pd(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function mS(e,t,n,r){e&&at({limit_type:"primary",retry_after_seconds:pd(r),api_method:t,api_url:n,provider:e}).catch(Se("fetch rate-limit session logging"))}function fS(e,t,n,r,o){e.body?.cancel?.().catch(Se("response body cancellation")),v("fetchWithRetries",it.FETCH_HTTP_ERROR.code).catch(Se("fetch retry session logging"));let i=new Error(it.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&ya(r),e.status===429&&mS(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function gS(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=pd(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function lt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=pS,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(ht)}`}let m={"User-Agent":`Octocode-MCP/${ht}`,...i},p=globalThis.fetch;if(!p)throw v("fetchWithRetries",it.FETCH_NOT_AVAILABLE.code).catch(Se("fetch retry session logging")),new Error(it.FETCH_NOT_AVAILABLE.message);ud(d);let f,g=n+1;for(let h=1;h<=g;h++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(d,{method:s,headers:m,signal:c});if(!b.ok)throw fS(b,s,d,l,u);if(b.status===204)return Ui(d),null;let R=await b.json();return Ui(d),R}catch(b){let R=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(R&&R.retryable===!1)throw b;if(f=b instanceof Error?b:new Error(String(b)),h===g)break;let C=gS(h,r,o,R);await new Promise(w=>setTimeout(w,C))}}throw ld(d),await v("fetchWithRetries",it.FETCH_FAILED_AFTER_RETRIES.code),new Error(it.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}import{z as E}from"zod";var Br=E.looseObject({name:E.string(),version:E.string(),repository:E.union([E.string(),E.object({url:E.string().optional(),type:E.string().optional(),directory:E.string().optional()})]).optional(),main:E.string().optional(),module:E.string().optional(),type:E.string().optional(),exports:E.unknown().optional(),types:E.string().optional(),typings:E.string().optional(),description:E.string().optional(),keywords:E.array(E.string()).optional(),license:E.union([E.string(),E.object({type:E.string().optional()})]).optional(),homepage:E.string().optional(),author:E.union([E.string(),E.object({name:E.string().optional(),email:E.string().optional(),url:E.string().optional()})]).optional(),maintainers:E.array(E.object({name:E.string().optional(),email:E.string().optional()})).optional(),engines:E.record(E.string(),E.string()).optional(),dependencies:E.record(E.string(),E.string()).optional(),devDependencies:E.record(E.string(),E.string()).optional(),peerDependencies:E.record(E.string(),E.string()).optional(),time:E.record(E.string(),E.string().optional()).optional()}),hS=E.looseObject({package:E.looseObject({name:E.string().nullish(),version:E.string().nullish(),description:E.string().nullish(),links:E.looseObject({npm:E.string().nullish(),homepage:E.string().nullish(),repository:E.string().nullish()}).nullish()}),score:E.looseObject({final:E.number().nullish(),detail:E.looseObject({quality:E.number().nullish(),popularity:E.number().nullish(),maintenance:E.number().nullish()}).nullish()}).nullish()}),md=E.looseObject({objects:E.array(hS),total:E.union([E.number(),E.string()]).optional()}),yS=E.union([E.string(),E.boolean(),E.number(),E.null(),E.record(E.string(),E.unknown())]);var Qr="https://registry.npmjs.org",RS=3e3,zr=null;async function bd(){if(zr)return zr;try{let e=await Ur("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 zr=t,t}}catch{}return zr=Qr,Qr}function Et(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var bS="https://api.npmjs.org/downloads/point/last-week";function ve(e){return e===void 0?0:F(e)}async function Sd(e){try{let t=`${bS}/${encodeURIComponent(e)}`,n=await lt(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:ve(n)}}catch{return{rawResponseChars:0}}}function $r(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Cd(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 SS(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function CS(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 fd(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 gd(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 TS(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Bi(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Et(e.repository):(e.repository.url&&(r=Et(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:TS(e),...o?{repositoryDirectory:o}:{},...fd(e.exports)?{exports:fd(e.exports)}:{},...gd(e.bin,e.name)?{bin:gd(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 PS(e){return typeof e.links?.repository=="string"?Et(e.links.repository):typeof e.repository=="string"?Et(e.repository):typeof e.repository?.url=="string"?Et(e.repository.url):null}function ES(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:PS(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 Td(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function Pd(e){try{let t=await bd(),n=Td(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await lt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=ve(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await lt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:ve(i)}}catch{return{rawResponseChars:0}}}async function zi(e,t,n){let[r,o]=await Promise.all([Sd(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Pd(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 jr(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function wS(e,t){try{let n=await Ur("view",[e,"--json"],{timeout:RS});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,...jr(c)?{}:{errorDetail:c},rawResponseChars:ve(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=ve(o),s=Br.safeParse(o);return s.success?{pkg:Bi(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,...jr(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function _S(e,t){try{let n=await bd(),r=Td(e),o=`${n}/${r}/latest`,i;try{i=await lt(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=ve(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=Br.safeParse(i);return a.success?{pkg:Bi(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,...jr(r)?{}:{errorDetail:r},rawResponseChars:0}}}function xS(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Ed(e,t){let n=0,r;for(let o of xS(e)){let i;try{i=await lt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);jr(u)||(r=u);continue}if(n+=ve(i),!i||typeof i!="object")continue;let s=Br.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Bi(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Qi(e,t=!1){let[n,r]=await Promise.allSettled([wS(e,t),_S(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?zi(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function AS(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Qi(e,t);if(!r){if(o){let s=Cd(o);if(s&&n){let a=await Ed(e,t);if(a.pkg){let c=await zi(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 LS(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ur("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:ve(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=ve(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 Qi(g.name,!0);if(h.pkg)return h}return{pkg:ES(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 OS(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Qr}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await lt(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=ve(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=md.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 Qi(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"?Et(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:CS(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 hd(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 lt(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:ve(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:ve(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"?Et(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:ve(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function yd(e,t,n,r=0){try{let o=await LS(e,t,n,r);if(!("error"in o))return o}catch{}return OS(e,t,n,r)}async function Rd(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}):Sd(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Pd(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 wd(e,t,n,r=0){let o=we("npm-search",{name:e,limit:t,metadata:n,from:r});return _e(o,async()=>{if(dd(Qr)){if(r===0&&t===1&&$r(e)){let l=await Ed(e,n);if(l.pkg){let d=await zi(e,l.pkg,l.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let u=await hd(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&&$r(e)){let u=await AS(e,n,t===1);if("error"in u){if(!Cd(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await yd(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Rd(s);let a=SS(e);if(a!==e){let u=await yd(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return Rd(u)}let c=await hd(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 _d(e){let t=$r(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return wd(e.name,n,!0,r)}function IS(e){return"error"in e}function Vr(e){return"npmUrl"in e}function kS(e){return Vr(e)&&e.path?e.path:e.name}function vS(e){return Vr(e)?e.repoUrl:e.repository}function FS(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function MS(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 NS(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 DS(e,t){let n=NS(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 HS(e){let t=kS(e),n=MS(vS(e)),r={name:t};Vr(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=FS(Vr(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=DS(n,o);return i&&(r.next=i),r}function GS(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 xd(e){return Y(e.queries,async t=>{try{if(!t.packageName)return _("Package name is required for package search",t);let n=await _d({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(IS(n))return _(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(HS),i=o.length>0,s=r.length>1||n.totalFound>1,a=GS(t,n.totalFound,o.length,s);return he(t,{packages:o,pagination:a},i,S.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return _(n,t,{toolName:S.PACKAGE_SEARCH})}},{toolName:S.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{open as US,readFile as BS,stat as zS}from"fs/promises";import{ContentSanitizer as QS}from"@octocodeai/octocode-engine/contentSanitizer";var We={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 Ld(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ad(e,t,n){return{...e,...Ld(t,n)}}function $S(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 jS(e,t){try{return{fileStats:await zS(t)}}catch(n){let r=Fe.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:_(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function VS(e,t){return t>We.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function WS(e,t,n){let r=Fe.fileTooLarge(e.path,n,We.LARGE_FILE_THRESHOLD_KB);return _(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function KS(e,t){let n=Fe.binaryFileUnsupported(e.path);return _(n,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function YS(e){let n=Buffer.alloc(8192),r;try{r=await US(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(wa("binary sample handle close",void 0))}}async function XS(e,t){try{return{content:await BS(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?Fe.fileAccessFailed(e.path,r):Fe.fileReadFailed(e.path,r);return{errorResult:_(i,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function JS(e,t){return{status:"empty",errorCode:H.NO_MATCHES,totalLines:t}}function ZS(e,t,n){let r=ur(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:JS(e,n)};let o=r.lines.join(`
|
|
37
|
+
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,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 qS(e){return e.startLine!==void 0&&e.endLine!==void 0}function eC(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(`
|
|
38
|
+
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function tC(e,t,n){let r=t.split(`
|
|
39
|
+
`),o=bt(t);return e.matchString?ZS(e,r,o):qS(e)?eC(e,r,o):{resultContent:t,isPartial:!1}}function nC(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 T=cr(u,f,m,c);g=T.chunkMode,h=T.length}let b=Gt(u,f,h,m!==void 0?{pageSize:m}:void 0),R=t.isPartial||b.hasMore,C;if(b.hasMore&&g==="char-limit"&&sr(b.paginatedContent)){let T=b.charOffset+b.charLength;C=ar(u,T,c)}let w=b.hasMore&&b.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:b.nextCharOffset,charLength:m??b.charLength,minify:e.minify}}}:void 0;return{path:c,content:b.paginatedContent,...s!=="standard"&&{contentView:s},...R&&{isPartial:R},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:{...Ja(b),chunkMode:g,...C!==void 0&&{nextBlockChar:C}}},...w?{next:w}:{},...a.length>0&&{warnings:a}}}function rC(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function Od(e){let t=Be();try{let n=Le(e,S.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=$S(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await jS(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,u=c/1024;if(await YS(o))return D(KS(e,o),c);if(VS(e,u))return D(WS(e,o,u),c);let{content:l,errorResult:d}=await XS(e,o);if(d||l===void 0)return d;let m=QS.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,b=e.minify,R=b==="standard"||b==="symbols",C=R?"standard":"none",w;if(b==="symbols"){let x=O.extractSignatures(p,i);if(x===null&&(w=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),x!==null){let L=bt(p),z=O.applyContentViewMinification(x,i);return D({path:e.path,content:z,contentView:"symbols",isSkeleton:!0,totalLines:L,...Ld(f,g),...h?{warnings:[h]}:{}},f)}}let T=bt(p),A=tC(e,p,t),G=x=>{let L=[...w?[w]:[],...h?[h]:[]];if(L.length===0)return x;let z=x.warnings??[];return{...x,warnings:[...z,...L]}};if(A.earlyResult){let x=A.earlyResult.content,L=R&&typeof x=="string"?{...A.earlyResult,content:O.applyContentViewMinification(x,i)}:A.earlyResult;return D(Ad(G($i(rC(L,C),e,T)),f,g),f)}let $=nC(e,A,s,T,t,R,C);return D(Ad(G($i($,e,T)),f,g),f)}catch(n){return _(n,e,{toolName:S.LOCAL_FETCH_CONTENT})}}function $i(e,t,n){return e}async function Id(e){let{queries:t}=e;return Y(t||[],async n=>Ae({toolName:S.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Te(Sr,n);return r.ok===!1?r.error:await Od(r.data)}}),{toolName:S.LOCAL_FETCH_CONTENT},e)}function Vt(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 kn(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var iC=[];function sC(e,t){let n=t??iC,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function kd(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Le(e,S.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:sC(i.path,i.excludeDir)},a=dC(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(L=>aC(L,r)),p=e.sortBy||"modified";cC(m,p,r);let f=uC(m,t,n),g=f.length,h=e.itemsPerPage||20,b=e.page||1,R=Math.max(1,Math.ceil(g/h)),C=(b-1)*h,w=Math.min(C+h,g),A=f.slice(C,w),G=[...u.warnings,...u.skipped>0?[`${u.skipped} entr${u.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],$=[...a,...G],x={...g===0?{status:"empty"}:{},path:i.path,files:A,pagination:{currentPage:b,totalPages:R,filesPerPage:h,totalFiles:g,hasMore:b<R,...b<R?{nextPage:b+1}:{},...d?{totalFilesFound:l}:{}},...$.length>0&&{warnings:$}};return D(vd(x,e,{totalFiles:g}),u.entries.reduce((L,z)=>L+z.path.length,0))}catch(o){return _(o,e,{toolName:S.LOCAL_FIND_FILES})}}function aC(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 vd(e,t,n){return e}function cC(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 uC(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=Vt(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var lC=/^\d+[hdwm]$/;function dC(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&&!lC.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 Fd(e){let{queries:t}=e;return Y(t||[],async n=>Ae({toolName:S.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Te(Cr,n);return r.ok===!1?r.error:await kd(r.data)}}),{toolName:S.LOCAL_FIND_FILES},e)}import{validateRipgrepQuery as ZC}from"@octocodeai/octocode-core/schemas/runtime";var Md=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],Z={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},pC=2e3,mC=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Nd={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+['"]/]},vn={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Nd},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Nd},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/]}},fC=/^\s*#{1,6}\s/,Vi=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,gC=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,hC=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,yC=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,RC=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,bC=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,SC=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,CC=new Set(["typescript","javascript","rust","python","go","java","scala"]),Hd=/\.([a-z0-9]+)$/i;function Wi(e){return Hd.exec(e)?.[1]?.toLowerCase()??""}function TC(e){let t=Wi(e);if(!t)return!1;for(let n of CC)if(vn[n].extensions.includes(t))return!0;return!1}function PC(e,t,n){if(n&&n!=="auto")return vn[n];let r=Wi(e),o=(t??"").toLowerCase();for(let i of Md){let s=vn[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Md){let s=vn[i];if(i!=="generic"&&s.extensions.includes(r))return s}return vn.generic}function Gd(e){return gC.test(e)?"generated":yC.test(e)?"fixture":hC.test(e)?"test":bC.test(e)?"config":RC.test(e)?"docs":!Vi.test(e)&&(SC.test(e)||TC(e))?"source":"unknown"}function EC(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function wC(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 _C(e,t,n,r,o){if(!e||e.length===0)return 0;let i=DC(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=HC(u,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Bd(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(d+=Z.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(d+=Z.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(d+=Z.substring,m.push("substring match")));let p=c.kind;if(p)d+=xC(p,m);else{let f=GC(l,r,t.id,n.caseSensitive);f!=="code"?(d+=Z.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(ji(t.declaration,l)&&(d+=Z.declarationLine,m.push("declaration line")),ji(t.export,l)&&(d+=Z.exportLine,m.push("export/public line")),ji(t.import,l)&&(d+=Z.importLine,m.push("import line")),t.id==="markdown"&&fC.test(l)&&(d+=Z.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&AC(l,r)&&(d+=Z.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function xC(e,t){switch(e){case"declaration":return t.push("AST: declaration"),Z.declarationLine;case"export":return t.push("AST: export/public"),Z.exportLine;case"configKey":return t.push("AST: config key"),Z.configKeyLine;case"heading":return t.push("AST: heading"),Z.headingLine;case"import":return t.push("AST: import"),Z.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),Z.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function AC(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 LC(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(Hd,"").includes(u))&&(s+=Z.pathSegmentToken,i.push("query token in path"))}let a=Wi(e);return r.extensions.includes(a)&&t.langType&&(s+=Z.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=Z.sourceDir,i.push("source file")),s}function OC(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),Z.lowSignalPathPenalty):0}function IC(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*Z.matchCountScale,r=Math.min(n,Z.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function kC(e,t){let n=wC(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=>vC(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 vC(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Bd(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function FC(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*Z.rareQueryTokenScale,Z.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 MC(e,t,n){let r=PC(e.path,t.langType,t.profileOverride),o=Gd(e.path),i=EC(t.keyword),s=[],a=0;return a+=_C(e.matches,r,t,i,s),a+=LC(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=Z.pathUnderQuery,s.push("under requested subtree")),a+=OC(o,t,s),Vi.test(e.path)&&!t.explicitLowSignal&&(a+=Z.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=IC(e.matchCount??0,s),a+=FC(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Ud(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Dd),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??pC,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Dd);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=kC(i,n),u=i.map(d=>{try{return{file:d,s:MC(d,n,c)}}catch{return{file:d,s:NC()}}});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 NC(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Dd(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function ji(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Bd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DC(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function HC(e,t,n){if(e.indexOf(`
|
|
40
|
+
`)<0)return e;let o=e.split(`
|
|
41
|
+
`);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 GC(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(mC.test(e))return"comment";let o=UC(e,t,r);if(o<0)return"code";let i=BC(e);return i>=0&&o>i?"comment":zC(e,o)?"string":"code"}function UC(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function BC(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 zC(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 zd(e){if(!e)return!1;if(Vi.test(e))return!0;let t=Gd(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Qd=8,QC=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"]),$C=/^[A-Za-z_$][A-Za-z0-9_$]*$/;async function Kr(e,t,n,r,o){let i=t.sort??"relevance",s;try{s=Ud(e,i,YC(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((Q,M)=>Q+(M.matchCount??0),0),h=f?o?.matchCount??g:g,b=t,R=b.itemsPerPage||We.DEFAULT_FILES_PER_PAGE,C=b.page||1,w=Math.ceil(d/R),T=(C-1)*R,A=Math.min(T+R,d),G=u.slice(T,A),$=b.maxMatchesPerFile||We.DEFAULT_MATCHES_PER_PAGE,x=G.map(Q=>{let M=Q.matches?.length??0,fe=Math.ceil(M/$),ie=Math.max(1,b.matchPage||1),Ye=(ie-1)*$,_t=Math.min(Ye+$,M),j=f?void 0:Q.matches?.slice(Ye,_t),Qe=c?.get(Q.path);return{path:Q.path,...m?{}:{matchCount:p?Q.matchCount||1:M},...j!==void 0&&{matches:j},...Qe?{ranking:{score:Qe.score,profile:Qe.profile,pathRole:Qe.pathRole,reasons:Qe.reasons}}:{},pagination:!f&&M>$?{currentPage:ie,totalPages:fe,matchesPerPage:$,totalMatches:M,hasMore:ie<fe,...ie<fe?{nextMatchPage:ie+1}:{}}:void 0}}),L=x.filter(Q=>Q.pagination?.hasMore),z=jC(x,t,n,{isFileListMode:f,currentPage:C,totalFilePages:w,matchPage:b.matchPage||1,matchesPerPage:$,hasFileWithMoreMatches:L.length>0}),se={searchEngine:n,...o?{stats:o}:{},files:x,pagination:{currentPage:C,totalPages:w,filesPerPage:R,totalFiles:d,...m?{}:{totalMatches:h},hasMore:C<w,...C<w?{nextPage:C+1}:{},...l?{totalFilesFound:a.length}:{}},...r.length>0?{warnings:r}:{},...Object.keys(z).length>0?{next:z}:{}};return $d(se,t,{totalMatches:h,totalFiles:d})}function $d(e,t,n){return e}function jC(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=VC(i);s.fetchExact={tool:"localGetFileContent",query:Wr({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:Wr({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=WC(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:Wr({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Wr({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function VC(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-Qd),endLine:n+Qd}}function WC(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return KC(e?.metavars);if(!t.matchWindow)return t.onlyMatching?Ki(e?.value):Ki(t.keywords)}}function KC(e){if(e)for(let t of Object.values(e))for(let n of t){let r=Ki(n);if(r)return r}}function Ki(e){if(typeof e!="string")return;let t=e.trim();if($C.test(t)&&!QC.has(t))return t}function Wr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function YC(e){let t=e.rankingProfile,n=!!(e.include?.length||zd(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function jd(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&&XC(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&JC(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function XC(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function JC(e){return/\(\?[=!<]/.test(e)}function qC(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function eT(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:qC(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 tT(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 Vd(e){let t=[],n=ZC(e);if(!n.isValid)return _(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=Qt.safeParse(e);if(!r.success){let g=r.error.issues.map(h=>h.message);return _(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return _(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}});let s=Le(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=jd({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return _(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await O.searchRipgrep(eT(a))}catch(g){return _(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 b={line:h.line,column:h.column,value:h.value};return h.count!==void 0&&(b.count=h.count),h.kind!==void 0&&(b.kind=h.kind),h.scoreHint!==void 0&&(b.scoreHint=h.scoreHint),b})})),m=tT(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 D({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...u]},m);!a.filesOnly&&m>We.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let f=await Kr(d,o,"rg",[...t,...u],p);return D(f,m)}var nT=[],rT=2e3,oT=1e6,iT="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`.",sT={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 aT(e){if(!e)return;let t=e.trim().toLowerCase();return(sT[t]??[t.replace(/^[.*]+/,"")]).filter(Boolean).map(r=>`*.${r}`)}async function Wd(e){let t=Le(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:aT(e.langType),excludeDir:e.excludeDir?.length?e.excludeDir:nT,maxFiles:e.maxFiles??rT,maxFileBytes:oT})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return _(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(`
|
|
42
|
+
`,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(iT),await Kr(r,e,"structural",i,o)}function cT(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 Kd(e){let t=cT(e);if(t.mode==="structural")return await Wd(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Vd(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}:_(n,t,{toolName:S.LOCAL_RIPGREP})}}async function Yd(e){let{queries:t}=e;return Y(t||[],async n=>Ae({toolName:S.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Te(Qt,n);return r.ok===!1?r.error:await Kd(r.data)}}),{toolName:S.LOCAL_RIPGREP},e)}var uT=new Set(["+","*","?"]),lT=1e3;function dT(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Xd(e,t){let n=e[t];return n===void 0?!1:uT.has(n)||n==="{"&&fT(e,t)}function pT(e,t,n){let r=n.pop()??!1,o=Xd(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?Zd(e,t+1):t+1})}function mT(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Zd(e,t)})}function Jd(e){if(e.length>lT)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=dT(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=pT(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Xd(e,r)){let i=mT(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function fT(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 Zd(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function qd(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(!Jd(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 ep(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 tp(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 np(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+kn(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Vt(r)})`}function rp(e,t){let n=e.length,r=t.itemsPerPage||We.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 op(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 ip(e){try{let t=Le(e,S.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return gT(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}}}function gT(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=yT(e),s=r&&e.limit&&!hT(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:RT(e),limit:s})}catch(C){return CT(C,e,t)}let c=a.entries.map(C=>bT(C,n,e.details??!1)),u=qd(c,e),l=e.sortBy??"name";u=u.sort((C,w)=>{let T=0;switch(l){case"size":{let A=C.sizeBytes??(C.size?kn(C.size):0),G=w.sizeBytes??(w.size?kn(w.size):0);T=A-G;break}case"time":n&&C.modified&&w.modified?T=C.modified.localeCompare(w.modified):T=C.name.localeCompare(w.name);break;case"extension":T=(C.extension||"").localeCompare(w.extension||"");break;default:T=C.name.localeCompare(w.name);break}return e.reverse?-T:T}),e.limit&&(u=u.slice(0,e.limit));let d=u.length,{paginatedEntries:m,pagination:p}=rp(u,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(C=>({...tp(C),path:C.path??`${t.replace(/\/$/,"")}/${C.name}`}))}:{path:t,...ep(m)},h=[...a.warnings,...op({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],b=d===0,R=np(u);return D(sp({...b?{status:"empty"}:{},...g,summary:R,...p.hasMore||p.totalPages>1?{pagination:p}:{},...h.length>0&&{warnings:h}},e),a.entries.reduce((C,w)=>C+w.path.length,0))}function hT(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function yT(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function RT(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function bT(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:Vt(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=ST(e.permissions)),o}function ST(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 CT(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,t,{toolName:S.LOCAL_VIEW_STRUCTURE})}function sp(e,t){return e}async function ap(e){let{queries:t}=e;return Y(t||[],async n=>Ae({toolName:S.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Te(Tr,n);return r.ok===!1?r.error:await ip(r.data)}}),{toolName:S.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import LT from"node:path";import{acquirePooledClient as gp,isLanguageServerAvailable as hp}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as OT}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as yp}from"@octocodeai/octocode-engine/lsp/workspaceRoot";import{safeReadFile as TT}from"@octocodeai/octocode-engine/lsp/validation";var cp={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0};function Fn(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function up(e,t,n){if(t<=0)return e;let r=await TT(e.uri);if(!r)return e;let o=mn(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(`
|
|
43
|
+
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function PT(e,t){return Promise.all(e.map(async n=>({...n,from:await up(n.from,t,n.fromRanges)})))}async function ET(e,t){return Promise.all(e.map(async n=>({...n,to:await up(n.to,t)})))}async function Yi(e,t,n,r,o){if(n<=0||!e)return{calls:[],...cp};try{let i=await e.getIncomingCalls(t),s=o>0?await PT(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=Fn(c.from);return r.has(u)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(u),Yi(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 Xi(e,t,n,r,o){if(n<=0||!e)return{calls:[],...cp};try{let i=await e.getOutgoingCalls(t),s=o>0?await ET(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=Fn(c.to);return r.has(u)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(u),Xi(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 wT}from"node:fs/promises";import{SymbolResolver as _T,SymbolResolutionError as xT}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as lp}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function Ji(e,t){let n=e.uri,r=Le({...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 wT(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:lp.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function dp(e,t){let n=await Ji(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 _T({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:AT(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u}}}}}catch(o){if(o instanceof xT)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:lp.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 AT(e){return{start:e,end:{line:e.line,character:e.character}}}var Zi;function Rp(e){return Zi||(Zi=new Set(O.getSupportedJsTsExtensions().map(t=>`.${t}`))),Zi.has(LT.extname(e).toLowerCase())}function IT(e,t){if(!Rp(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 kT=40,bp=40,vT=10,FT=8;async function Sp(e){return Y(e.queries||[],async t=>Ae({toolName:Ee,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await $T(t);return MT(NT(t,n))}}),{toolName:Ee,minQueryTimeoutMs:3e4},e)}function MT(e){return D(e,F(e))}function NT(e,t){return e.format!=="compact"||!DT(t)?t:HT(t)}function DT(e){return wt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&wt(e.payload)}function HT(e){return{...e,format:"compact",payload:GT(e.payload)}}function GT(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(pp)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(BT)}:{locations:(e.locations??[]).map(pp)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Cp(e.root)}:{},direction:e.direction,calls:e.calls.map(zT),...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(UT)};case"hover":case"empty":return e}}function UT(e){if(!wt(e))return String(e);let t=Oe(e,"line"),n=Oe(e,"character"),r=Oe(e,"endLine"),o=et(e,"kind"),i=et(e,"name"),s=Oe(e,"childCount"),a=et(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function pp(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Pp(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function BT(e){if(!wt(e))return String(e);let t=et(e,"uri"),n=Oe(e,"firstLine"),r=Oe(e,"firstCharacter"),o=Oe(e,"count"),i=Tp(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 zT(e){if(!wt(e))return String(e);let t=et(e,"direction"),n=Cp(e.item),r=Tp(e,"ranges").map(QT).join(","),o=Oe(e,"rangeCount"),i=Oe(e,"rangeSampleCount"),s=et(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Pp(s,180)}`:""].filter(Boolean).join(" ")}function Cp(e){if(!wt(e))return String(e);let t=et(e,"name"),n=et(e,"kind"),r=et(e,"uri"),o=Oe(e,"line"),i=Oe(e,"endLine"),s=Oe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function QT(e){return wt(e)?`${Oe(e,"line")}:${Oe(e,"character")}`:String(e)}function wt(e){return typeof e=="object"&&e!==null}function et(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Oe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Tp(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Pp(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 $T(e){if(e.type==="documentSymbols")return jT(e);let t=await dp(e,Ee);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return rP(e,i)}let n=e.workspaceRoot??await yp(t.value.uri);if(!await hp(t.value.uri,n)){if(e.type==="references"){let i=WT(e,t.value);if(i)return i}return qe(e.type,t.value,"Language server unavailable")}let o=await gp(n,t.value.uri);if(!o)return qe(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?qi(e,t.value,"definition","definitionProvider",await OT({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):qe(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?qi(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):qe(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?qi(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):qe(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?Ep(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):qe(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?KT(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):qe(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?YT(e,t.value,o):qe(e.type,t.value,"callHierarchyProvider unsupported",!0)}}async function jT(e){let t=await Ji(e,Ee);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await yp(t.value.uri),r=await hp(t.value.uri,n),o=r?await gp(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=IT(t.value.uri,t.value.content);h&&(s=h,a="native")}let c=a!==void 0,u=XT(s),l=qT(s),{pageItems:d,pagination:m}=Yr(u,e.page??1,e.itemsPerPage??kT),p=eP(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 qi(e,t,n,r,o){let i=o.length>0,s=o.map(Io),{pageItems:a,pagination:c}=Yr(s,e.page??1,e.itemsPerPage??bp);return{type:e.type,uri:t.uri,resolvedSymbol:Ft(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 VT={kind:"lsp"};function Ep(e,t,n,r=VT){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?oP(i):void 0,a=s??i.map(Io),{pageItems:c,pagination:u}=Yr(a,e.page??1,e.itemsPerPage??bp),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:Ft(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 WT(e,t){if(!Rp(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(`
|
|
44
|
+
`),o=n.map(i=>({uri:t.uri,range:i,content:(r[i.start.line]??"").trim()}));return Ep(e,t,o,{kind:"native",scope:"file"})}async function KT(e,t,n){let r=iP(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Ft(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function YT(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return qe(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 Yi(n,o,i,new Set([Fn(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Xi(n,o,i,new Set([Fn(o)]),e.contextLines??0):s,u=R=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(R.to.uri),l=c.calls.filter(u).length,d=c.calls.filter(R=>!u(R)),m=[...a.calls.map(R=>({direction:"incoming",...R})),...d.map(R=>({direction:"outgoing",...R}))],p=m.map(R=>R.direction==="incoming"?tP(R,e.contextLines??0):nP(R,e.contextLines??0)),{pageItems:f,pagination:g}=Yr(p,e.page??1,e.itemsPerPage??vT),h=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:Ft(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:ts(o),direction:h,calls:f,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}function Yr(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 XT(e){let t=[];for(let n of e)wp(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function wp(e,t,n){if(!e||typeof e!="object")return;let r=e,o=ZT(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:es(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)&&JT.has(es(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)wp(s,t,i)}}var JT=new Set(["file","module","namespace","package","class","enum","interface","struct"]);function ZT(e){if(mp(e.range))return e.range;let t=e.location;return t&&mp(t.range)?t.range:void 0}function mp(e){if(!e||typeof e!="object")return!1;let t=e;return fp(t.start)&&fp(t.end)}function fp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function qT(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function eP(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function tP(e,t){let n=_p(e.fromRanges);return{direction:"incoming",item:ts(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...xp(e.from,t)}}function nP(e,t){let n=_p(e.fromRanges);return{direction:"outgoing",item:ts(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...xp(e.to,t)}}function ts(e){return{name:e.name,kind:es(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 _p(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>=FT))break}return n}function xp(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function es(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 Ap(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 rP(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Ap(e.type,t),reason:t}}}function qe(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Ft(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Ap(e,n),reason:n}}}function oP(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 iP(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=>sP(r)).join(`
|
|
45
|
+
`).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function sP(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var ns={hasTool(e){return $o(e)},getDescription(e){return Qo[e]??""},getToolName(e){return S[e]??String(e)}};var Lp=(e,t=ns)=>t.getDescription(e);function aP(e,t){return t.getToolName(e)}function He(e,t,n){let r=aP(t,e);return{...n,name:r,description:Lp(r,e)}}function cP(e=ns){let t=He(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Vc,inputSchema:Wc,executionFn:$l,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=He(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Rr,inputSchema:Qc,executionFn:zl,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=He(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:ru,inputSchema:ou,executionFn:id,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=He(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:qc,inputSchema:eu,executionFn:od,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=He(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:br,inputSchema:Xc,executionFn:Zl,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=He(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:au,inputSchema:cu,executionFn:xd,security:"remote",requiresServerRuntime:!0}}),a=He(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:oi,inputSchema:Uc,executionFn:Tl,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=He(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Qt,inputSchema:yu,executionFn:Yd,security:"basic"}}),u=He(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Tr,inputSchema:Su,executionFn:ap,security:"basic"}}),l=He(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Cr,inputSchema:fu,executionFn:Fd,security:"basic"}}),d=He(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Sr,inputSchema:du,executionFn:Id,security:"basic"}}),m={name:Ee,description:Lp(Ee,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:wu,inputSchema:_u,executionFn:Sp,security:"basic",requiresServerRuntime:!0}},p=He(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:wr,inputSchema:Iu,executionFn:il,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 Ie=cP(),fH=Ie.GITHUB_SEARCH_CODE,gH=Ie.GITHUB_FETCH_CONTENT,hH=Ie.GITHUB_VIEW_REPO_STRUCTURE,yH=Ie.GITHUB_SEARCH_REPOSITORIES,RH=Ie.GITHUB_SEARCH_PULL_REQUESTS,bH=Ie.PACKAGE_SEARCH,SH=Ie.GITHUB_CLONE_REPO,CH=Ie.LOCAL_RIPGREP,TH=Ie.LOCAL_VIEW_STRUCTURE,PH=Ie.LOCAL_FIND_FILES,EH=Ie.LOCAL_FETCH_CONTENT,wH=Ie.LSP_GET_SEMANTIC_CONTENT,_H=Ie.LOCAL_BINARY_INSPECT,Op=Ie.ALL_TOOLS;import{ContentSanitizer as uP}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as Ip}from"@octocodeai/octocode-engine/mask";function rs(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=uP.sanitizeContent(n.text),o=r.hasSecrets?Ip(r.content):Ip(n.text);return{...n,text:o}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:ct(t.structuredContent)}}catch{}return t}var lP="TOOL_CALLBACK_EXCEPTION";function os(e,t){let n=dP(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
46
|
+
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:lP,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return rs(r)}catch{return r}}function dP(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:pP(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 pP(e){try{return JSON.stringify(e)}catch{return}}import{withSecurityValidation as mP,withBasicSecurityValidation as fP}from"@octocodeai/octocode-engine/security";function kp(e,t){let n=mP(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function vp(e,t){let n=fP(r=>e(r),t);return(r,o)=>n(r,o)}import{releaseAllPooledClients as gP}from"@octocodeai/octocode-engine/lsp/manager";var cs=["GitHub","Local","LSP","Package","Other"],Fp=new Map([de.GITHUB_SEARCH_CODE,de.GITHUB_SEARCH_REPOSITORIES,de.GITHUB_SEARCH_PULL_REQUESTS,de.GITHUB_FETCH_CONTENT,de.GITHUB_VIEW_REPO_STRUCTURE,de.GITHUB_CLONE_REPO,de.LOCAL_RIPGREP,de.LOCAL_FIND_FILES,de.LOCAL_FETCH_CONTENT,de.LOCAL_VIEW_STRUCTURE,Ee,de.PACKAGE_SEARCH].map((e,t)=>[e,t])),Ke=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},is=null,ss=null,hP=["id","mainResearchGoal","researchGoal","reasoning"],ds=new Set([...hP]),yP=["id","researchGoal","reasoning"],Mp=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function RP(e){return async t=>e(t)}function bP(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:RP(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var Np=Op.map(bP),SP=Np.map(Gp);function ps(e){let t=fs(e);return t?Gp(t):void 0}function Mn(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")?"Local":e.startsWith("lsp")?"LSP":e===de.PACKAGE_SEARCH?"Package":"Other"}function CP(e){return[...e].sort((t,n)=>{let r=cs.indexOf(Mn(t)),o=cs.indexOf(Mn(n));if(r!==o)return r-o;let i=Fp.get(t)??Number.MAX_SAFE_INTEGER,s=Fp.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function TP(e){let t=ps(e);if(!t)return"{}";try{return JSON.stringify(as.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(as.toJSONSchema(t.schema),null,2)}}function PP(e){return JSON.stringify(e??{},null,2)}function EP(e){let t=Mn(e),n=[...yP];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function wP(){return Mp.map(e=>({...e}))}function _P(){return JSON.stringify(Object.fromEntries(Mp.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function xP(e,t){return t?.tools?.[e]?.description??e}function ms(e){let t=ps(e);if(!t)return[];let n=as.toJSONSchema(t.schema);if(!Nn(n))return[];let r=dt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!ds.has(i)&&!ls(r[i])):[]);return us(r,o)}function AP(e){let t=ms(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]=NP(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Ee&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function LP(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Ke("Tool input must be valid JSON.")}return Dp(e,r,n)}function Dp(e,t,n={}){let r=IP(e,t,n),o=fs(e);if(!o)throw new Ke(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Ke("Tool input does not match the expected schema.",OP(i.error));return i.data}function OP(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function IP(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(dt(t)&&Array.isArray(t.queries))r=t.queries;else if(dt(t))r=[t];else throw new Ke('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Ke("At least one query is required.");let o=dt(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)=>kP(e,u,FP(e,c,u,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new Ke("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function kP(e,t,n,r){let o={...n},i=Mn(e),s=r.sourceLabel??"direct tool execution",a=vP(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 vP(e,t){return`Execute ${e} via ${t}`}function FP(e,t,n,r={}){if(!dt(t))throw new Ke("Tool input must be a JSON object or an array of objects.");let o=new Set([...ms(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...ds]),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 MP(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 Hp(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let t=Nn(e.items)?e.items:void 0;return`array<${t?Hp(t):"value"}>`}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function us(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&ds.has(o))continue;let s=Nn(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Hp(s),constraints:MP(s),description:typeof s.description=="string"?s.description:void 0}),dt(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!ls(s.properties?.[l]):!1):[]);r.push(...us(s.properties,u,a))}let c=s.type==="array"&&Nn(s.items)?s.items:void 0;if(c&&dt(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!ls(c.properties?.[l]):!1):[]);r.push(...us(c.properties,u,a))}}return r}function NP(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 dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nn(e){return dt(e)}function ls(e){return Nn(e)&&"default"in e}async function DP(e,t){let n=fs(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=HP(n,t);return await GP(n),UP(n),await BP(n,r)}catch(r){return os(n.name,r)}finally{e===Ee&&await gP()}}function Gp(e){return{name:e.name,schema:e.schema,inputSchema:e.inputSchema}}function fs(e){return Np.find(t=>t.name===e)}function HP(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function GP(e){e.requiresServerRuntime&&(is||(is=pa()),await is),e.requiresProviders&&(ss||(ss=Nc().then(()=>{})),await ss)}function UP(e){if(!e.isLocal&&!e.isClone)return;let t=ge();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 BP(e,t){try{let n=e.security==="remote"?await zP(e,t):await QP(e,t);return rs(n)}catch(n){return os(e.name,n)}}async function zP(e,t){return kp(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function QP(e,t){return vp(e.execute,e.name)(t)}import{completeMetadata as $P}from"@octocodeai/octocode-core";var gs=null;function jP(){return gs||(gs=$P),gs}async function VP(){return jP()}export{cs as DIRECT_TOOL_CATEGORIES,SP as DIRECT_TOOL_DEFINITIONS,Ke as DirectToolInputError,AP as buildDirectToolExampleQuery,DP as executeDirectTool,ps as findDirectToolDefinition,uy as formatCallToolResultForOutput,PP as formatDirectToolMetadataSchemaText,_P as formatDirectToolOutputSchemaText,TP as formatDirectToolSchemaText,EP as getDirectToolAutoFilledFields,Mn as getDirectToolCategory,xP as getDirectToolDescription,ms as getDirectToolDisplayFields,wP as getDirectToolOutputFields,VP as loadToolContent,Dp as prepareDirectToolInput,LP as prepareDirectToolInputFromJsonText,CP as sortDirectToolNames};
|