@octocodeai/octocode-tools-core 18.0.1 → 18.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,36 +5,34 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- import{withSecurityValidation as ly,withBasicSecurityValidation as py}from"@octocodeai/octocode-engine/security";function ju(e,t){let n=ly(e,(r,o)=>t(r,o));return(r,o)=>n(r,o)}function zu(e,t){let n=py((r,o)=>e(r,o),t);return(r,o)=>n(r,o)}var me=30,oe=100,DL=10,ML=100,Wu=200,Ne=20,ct=100,Do=20,ln=50,Je=1e4,bt=20,Mo=1e3,Vu=100,pn=5e4,Ku=8e3,No=1e5,Yu=500;var Ps={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},tr={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"}},nr={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})`}},dy={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"}},Ct={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}`}},xt={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"}},Ee={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}`}},my={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}`}},rr={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},fy={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}`}},GL={...Ps,...tr,...nr,...dy,...Ct,...xt,...Ee,...my,...rr,...fy};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",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"},hy=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(hy||{}),Xu={[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"},[H.LSP_SERVER_UNAVAILABLE]:{code:H.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}};var xe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Xu[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
9
- Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function ws(e){return e instanceof xe}function qu(e,t=H.TOOL_EXECUTION_FAILED,n){if(ws(e))return e;if(e instanceof Error)return new xe(t,e.message,n,e);let r=String(e);return new xe(t,r,n)}import{redactPath as or}from"@octocodeai/octocode-engine/pathUtils";var Le={pathValidationFailed:(e,t,n)=>new xe(H.PATH_VALIDATION_FAILED,t||`Path validation failed: ${or(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=or(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 xe(H.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new xe(H.FILE_READ_FAILED,`Failed to read file: ${or(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new xe(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)}). Use startLine/endLine, matchString, or charOffset/charLength to read a bounded slice.`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new xe(H.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${or(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new xe(H.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new xe(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 xe(H.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new xe(H.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as cR}from"octokit";import{throttling as uR}from"@octokit/plugin-throttling";import{createHash as lR}from"crypto";function Ze(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function ut(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 ir(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var sr=new Map,gy=300*1e3;function yy(e){let t=Ze(e),n=sr.get(t);return!n||Date.now()-n.cachedAt>=gy?!1:n.credentials?!ut(n.credentials):!0}function ar(e){e?sr.delete(Ze(e)):sr.clear()}function Ju(e){let t=Ze(e);if(yy(t))return sr.get(t).credentials}function Zu(e,t){let n=Ze(e);sr.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as Qo,readFileSync as ol,writeFileSync as il,unlinkSync as rl,statSync as Py,chmodSync as wy}from"node:fs";import{createCipheriv as Ty,createDecipheriv as Ey,randomBytes as sl}from"node:crypto";import{existsSync as Go,mkdirSync as Ho}from"node:fs";import{join as je}from"node:path";import{getOctocodeHome as Ry}from"@octocodeai/config";var Bo=448;function el(){return Ry(process.env)}function zt(){return Ie}var Ie=el(),we={home:Ie,config:je(Ie,".octocoderc"),credentials:je(Ie,"credentials.json"),key:je(Ie,".key"),session:je(Ie,"session.json"),stats:je(Ie,"stats.json"),tmp:je(Ie,"tmp"),clone:je(Ie,"tmp","clone"),tree:je(Ie,"tmp","tree"),repos:je(Ie,"tmp","clone"),cliConfig:je(Ie,"config.json"),lspConfig:je(Ie,"lsp-servers.json")};function Uo(){Go(we.home)||Ho(we.home,{recursive:!0,mode:Bo})}function Sy(){tl()}function Ts(){Uo(),Go(we.tmp)||Ho(we.tmp,{recursive:!0,mode:Bo})}function tl(){Ts(),Go(we.clone)||Ho(we.clone,{recursive:!0,mode:Bo})}function by(){Ts(),Go(we.tree)||Ho(we.tree,{recursive:!0,mode:Bo})}import{z as Se}from"zod";var Cy=Se.object({token:Se.string(),tokenType:Se.literal("oauth"),scopes:Se.array(Se.string()).optional(),refreshToken:Se.string().optional(),expiresAt:Se.string().optional(),refreshTokenExpiresAt:Se.string().optional()}),xy=Se.object({hostname:Se.string(),username:Se.string(),token:Cy,gitProtocol:Se.enum(["ssh","https"]),createdAt:Se.string(),updatedAt:Se.string()}),nl=Se.object({version:Se.number(),credentials:Se.record(Se.string(),xy)});var Es=we.home,lt=we.credentials,et=we.key,al="aes-256-gcm",Ly=16;function Pt(){Uo()}function cl(){if(Pt(),Qo(et))return Py(et).mode&511&63&&wy(et,384),Buffer.from(ol(et,"utf8"),"hex");let e=sl(32);return il(et,e.toString("hex"),{mode:384}),e}function $o(e){let t=cl(),n=sl(Ly),r=Ty(al,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 jo(e){let t=cl(),[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=Ey(al,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function pt(){if(Pt(),!Qo(lt))return{version:1,credentials:{}};try{let e=ol(lt,"utf8"),t=jo(e),n=JSON.parse(t),r=nl.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Ls(e){Pt();let t=$o(JSON.stringify(e,null,2));il(lt,t,{mode:384})}function ul(){try{Qo(lt)&&rl(lt),Qo(et)&&rl(et)}catch{}}import{refreshToken as Ay}from"@octokit/oauth-methods";import{request as _y}from"@octokit/request";var dn="178c6fc778ccc68e1d6a",wt="github.com";function ky(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 Iy(e){return e==="github.com"||e===wt?"https://api.github.com":`https://${e}/api/v3`}async function As(e,t=wt,n=dn){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(ir(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Ay({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:_y.defaults({baseUrl:Iy(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?ky(o.message):"Token refresh failed"}}}async function ll(e,t=wt,n=dn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!ut(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await As(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as vy}from"@octocodeai/config";import{execFile as Oy}from"child_process";var Fy=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function zo(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=Fy.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Oy("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Wo=null;function pl(e){Wo=e}function _s(){Wo=null}function Dy(){if(!Wo)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Wo}async function Tt(e){let t=e?.hostname??wt,n=e?.clientId??dn,r=e?.getGhCliToken??zo,o=vy();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await Dy().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
10
- `)}return null}async function ks(e=wt){let t=await Tt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Is(e=wt,t=dn){let n=await Tt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}async function Os(e){let t=Ze(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=pt();return r.credentials[t]=n,Ls(r),ar(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Wt(e="github.com",t){let n=Ze(e);if(!t?.bypassCache){let i=Ju(n);if(i!==void 0)return i}let o=pt().credentials[n]||null;return Zu(n,o),o}function Vo(e="github.com"){let t=Ze(e);return pt().credentials[t]||null}async function dl(e="github.com"){let t=Ze(e),n=!1,r=pt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?ul():Ls(r),n=!0),ar(t),{success:n,deletedFromFile:n}}async function ml(){let e=pt();return Object.keys(e.credentials)}function fl(){let e=pt();return Object.keys(e.credentials)}async function hl(e="github.com"){return await Wt(e)!==null}function gl(e="github.com"){return Vo(e)!==null}async function Ko(e,t){let n=await Wt(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Os(n),!0):!1}function yl(){return lt}async function Rl(e="github.com"){let t=await Wt(e);return!t||!t.token||ut(t)?null:t.token.token}function Sl(e="github.com"){let t=Vo(e);return!t||!t.token||ut(t)?null:t.token.token}async function bl(e,t){return As({getCredentials:Wt,updateToken:Ko},e,t)}async function Fs(e,t){return ll({getCredentials:Wt,updateToken:Ko},e,t)}pl({getTokenWithRefresh:Fs});import fn from"node:os";import Cl from"node:path";var cr=fn.platform()==="win32",vs=fn.platform()==="darwin",Ds=fn.platform()==="linux",mn=fn.homedir();function xl(){return cr?process.env.APPDATA||Cl.join(mn,"AppData","Roaming"):mn}function Pl(){return cr?process.env.LOCALAPPDATA||Cl.join(mn,"AppData","Local"):mn}function wl(){return vs?"macOS":cr?"Windows":Ds?"Linux":fn.platform()}function Tl(){return fn.arch()}import{randomUUID as Ky}from"node:crypto";import{existsSync as Ms,readFileSync as kl,writeFileSync as By,unlinkSync as Uy,renameSync as Qy}from"node:fs";import{isStatsEnabled as Il}from"@octocodeai/config";import{z as W}from"zod";var My=W.object({rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),calls:W.number()}),Ny=W.object({hits:W.record(W.string(),W.number()).default({}),rateLimits:W.number().default(0)}),Yo=W.record(W.string(),W.number()).default({}),Gy=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Yo,rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),charSavingsCalls:W.number(),githubCacheHits:W.number(),githubCacheRateLimits:W.number(),packageRegistryFailures:W.number().default(0),packageRegistryFailuresByRegistry:Yo}),Xo=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Yo,charsSavedByTool:W.record(W.string(),My).default({}),githubCacheHits:Ny.default({hits:{},rateLimits:0}),packageRegistryFailures:Yo,totalUsage:Gy.optional()}),El=W.object({version:W.literal(1),sessionId:W.string(),createdAt:W.string(),lastActiveAt:W.string(),stats:Xo.optional()}),Ll=W.object({version:W.literal(1),stats:Xo});function Al(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Hy(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:Al(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Al(o),packageRegistryFailuresByRegistry:o}}function Et(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Hy(t)}}function Lt(){return Et({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Vt=we.session,Kt=we.stats;function _l(e,t){let n=`${e}.tmp`;By(n,JSON.stringify(t,null,2),{mode:384}),Qy(n,e)}function $y(e){let t=JSON.parse(e),n=Ll.safeParse(t);if(n.success)return Et(n.data.stats);let r=Xo.safeParse(t);return r.success?Et(r.data):null}function jy(){if(!Ms(Kt))return Lt();try{let e=kl(Kt,"utf8");return $y(e)??Lt()}catch{return Lt()}}function qo(e){Pt(),Il()&&_l(Kt,{version:e.version,stats:Et(e.stats)});let{stats:t,...n}=e;_l(Vt,n)}function Ol(){if(!Ms(Vt))return null;try{let e=kl(Vt,"utf8"),t=JSON.parse(e),n=El.safeParse(t);return n.success?{...n.data,stats:Il()?jy():Lt()}:null}catch{return null}}function Fl(){let e=!1;for(let t of[Vt,Kt])if(Ms(t))try{Uy(t),e=!0}catch{return!1}return e}var zy=6e4,ze=null,At=!1,hn=null,Ns=!1,ur=null,lr=null,pr=null,Jo=!1;function Wy(){Ns||(Ns=!0,ur=()=>{dr()},lr=()=>{dr()},pr=()=>{dr()},process.on("exit",ur),process.on("SIGINT",lr),process.on("SIGTERM",pr))}function Gs(){ur&&(process.removeListener("exit",ur),ur=null),lr&&(process.removeListener("SIGINT",lr),lr=null),pr&&(process.removeListener("SIGTERM",pr),pr=null),Ns=!1}function Vy(){hn||(hn=setInterval(()=>{At&&ze&&(qo(ze),At=!1)},zy),hn.unref())}function Hs(){hn&&(clearInterval(hn),hn=null)}function mr(){if(ze)return ze;let e=Ol();return e&&(ze=e),e}function gn(e){ze=e,At=!0,Wy(),Vy()}function fr(){At&&ze&&(qo(ze),At=!1)}function dr(){if(!Jo&&At&&ze){Jo=!0;try{qo(ze),At=!1}catch{}finally{Jo=!1}}}function Bs(){ze=null,At=!1,Jo=!1}function vl(){Bs(),Hs(),Gs()}var Yy=1;function Xy(e){return Et(e)}function qy(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 Dl(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 Jy(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 Ml(){let e=new Date().toISOString();return{version:Yy,sessionId:Ky(),createdAt:e,lastActiveAt:e,stats:Lt()}}function Nl(){fr()}function Gl(){dr()}function Hl(e){if(e?.forceNew){let r=Ml();return gn(r),fr(),r}let t=mr();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return gn(r),fr(),r}let n=Ml();return gn(n),fr(),n}function Bl(){return mr()?.sessionId??null}function Ge(e){let t=mr();if(!t)return{success:!1,session:null};let n=Xy(t.stats),r=Et({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Dl(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:qy(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:Jy(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Dl(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return gn(o),{success:!0,session:o}}function Ul(e=1){return Ge({toolCalls:e})}function Ql(e=1){return Ge({errors:e})}function Zo(e=1){return Ge({rateLimits:e})}function $l(e,t=1){return Ge({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function ei(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Ge({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function ti(e,t=1){return Ge({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ni(e=1){return Ge({githubCacheHits:{hits:{},rateLimits:e}})}function jl(e,t=1){return Ge({packageRegistryFailures:{[e]:t}})}function zl(){let e=mr();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Lt()};return gn(t),{success:!0,session:t}}function Wl(){return Bs(),Hs(),Gs(),Fl()}function Vl(){vl()}import{z as de}from"zod";var Kl=de.looseObject({$schema:de.string().optional(),version:de.number().int().optional(),github:de.record(de.string(),de.unknown()).optional(),local:de.record(de.string(),de.unknown()).optional(),tools:de.record(de.string(),de.unknown()).optional(),network:de.record(de.string(),de.unknown()).optional(),lsp:de.record(de.string(),de.unknown()).optional(),output:de.record(de.string(),de.unknown()).optional()});import{existsSync as Zy,readdirSync as eR,lstatSync as tR}from"node:fs";import{join as nR}from"node:path";function hr(e){if(!Zy(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=eR(r)}catch{continue}for(let i of o){let s=nR(r,i);try{let a=tR(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function rR(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}import{getConfigSync as Yl,invalidateConfigCache as iR}from"@octocodeai/config";var Yt="18.0.1";import{maskSensitiveData as sR}from"@octocodeai/octocode-engine/mask";var _t=null,yn=null,Us=Tt;function __(e){e.resolveTokenFull&&(Us=e.resolveTokenFull)}function k_(){Us=Tt}var aR=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function Qs(){try{let e=await Us({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:aR.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Xl(){if(_t!==null)return;if(yn!==null)return yn;let e=(async()=>{let t=Yl(),n=await Qs();_t={version:Yt,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();yn=e;try{await e}catch(t){throw yn===e&&(_t=null,yn=null),t}}function I_(){_t=null,yn=null,iR()}function gr(){if(!_t){let e=sR(Ps.NOT_INITIALIZED.message);throw new Error(e)}return _t}async function $s(){return(await Qs()).token}function O_(){return gr().enableLocal}function ql(){let e=gr();return e.enableLocal&&e.enableClone}async function F_(){return _t!==null?_t.tokenSource:(await Qs()).source}function js(){return"github"}function zs(){let e=Yl().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}function kt(e){(e.provider?Ge({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Zo(1)).session&&e.provider==="github"&&ni(1)}function Jl(e){Ge({packageRegistryFailures:{[e]:1}})}function rp(e){return lR("sha256").update(e).digest("hex").substring(0,16)}async function fe(e){let t=e?.token??await $s(),n=t?rp(t):"anon",r=gr().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var pR=cR.plugin(uR),dR=300*1e3,Ws=50,mR=60*1e3;function op(e){return Date.now()-e.createdAt>dR}var tt=new Map,It=null;function ip(){for(let[e,t]of tt.entries())op(t)&&tt.delete(e);if(tt.size>Ws){let e=tt.size-Ws,t=0;for(let[n]of tt){if(t>=e)break;tt.delete(n),t++}}}function fR(){It||(It=setInterval(ip,mR),typeof It=="object"&&"unref"in It&&It.unref())}var Zl=3,ep=60;function tp(e,t,n){kt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var hR=()=>({onRateLimit:(e,t,n,r)=>(tp("primary",e,t),r<Zl&&e<ep),onSecondaryRateLimit:(e,t,n,r)=>(tp("secondary",e,t),r<Zl&&e<ep)});function gR(e){let t=gr(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Yt}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:hR(),log:r,...e&&{auth:e}};return new pR(o)}async function Q(e){fR();let t=e?.token??await $s(),n=t?rp(t):"ANONYMOUS",r=tt.get(n);if(r&&!op(r))return r.client;tt.size>=Ws&&ip();let o=gR(t??void 0);return tt.set(n,{client:o,createdAt:Date.now()}),o}var yR=200,Rn=new Map;async function Ae(e,t,n){let r=`${e}/${t}`,o=Rn.get(r);if(o)return o;let i=await Q(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return np(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}),np(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 np(e,t){if(Rn.size>=yR){let n=Rn.keys().next().value;n!==void 0&&Rn.delete(n)}Rn.set(e,t)}function j_(){tt.clear(),Rn.clear(),It&&(clearInterval(It),It=null)}import{ContentSanitizer as zR}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as RR}from"node:module";var SR=RR(import.meta.url),sp="@octocodeai/octocode-engine",bR=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??SR(sp),ri,CR=bR,Vs=class extends Error{constructor(n){super(`Failed to load native dependency ${sp}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function J(){if(ri)return ri;try{return ri=CR(),ri}catch(e){throw new Vs(e)}}var O={applyContentViewMinification(e,t){return J().applyContentViewMinification(e,t)},applyMinification(e,t){return J().applyMinification(e,t)},minifyContent(e,t){return J().minifyContent(e,t)},minifyContentSync(e,t){return J().minifyContentSync(e,t)},minifyContentResult(e,t){return J().minifyContentResult(e,t)},minifyMarkdownCore(e){return J().minifyMarkdownCore(e)},extractSignatures(e,t){return J().extractSignatures(e,t)},extractJsSymbols(e,t){return J().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return J().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return J().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return J().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return J().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return J().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return J().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return J().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return J().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return J().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return J().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return J().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return J().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return J().parseRipgrepJson(e,t)},searchRipgrep(e){return J().searchRipgrep(e)},queryFileSystem(e){return J().queryFileSystem(e)},extractMatchingLines(e,t,n){return J().extractMatchingLines(e,t,n)},filterPatch(e,t){return J().filterPatch(e,t)},computeLineDiff(e,t){return J().computeLineDiff(e,t)},charToByteOffset(e,t){return J().charToByteOffset(e,t)},byteToCharOffset(e,t){return J().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return J().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return J().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return J().SIGNATURES_ONLY_HINT}};import{RequestError as cp}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"},ye={[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."}},ap={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},Ks={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},Ys={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},oi={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var xR=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function nt(e){if(!(e instanceof cp)||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 xR.some(o=>r.includes(o))})}function V(e){return e instanceof cp?PR(e):e instanceof Error?IR(e):{error:typeof e=="string"?e:ye[z.UNKNOWN].message,type:"unknown"}}function PR(e){let{status:t,message:n,response:r}=e;if(t===403)return TR(n,r);if(t===429)return wR(n,r);let o=ap[t];return o?kR(o,t):Sn(z.UNKNOWN,{error:n||ye[z.UNKNOWN].message,status:t})}function Xs(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function wR(e,t){let n=t?.headers,r=Xs(n,"retry-after"),o=Xs(n,"x-ratelimit-reset"),i=Xs(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+oi.RESET_BUFFER_SECONDS,0):void 0);return kt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:e||ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function TR(e,t){let n=t?.headers;if(Ys.SECONDARY.test(e))return ER(n);let r=n?.["x-ratelimit-remaining"],o=_R(t);return r!==void 0&&String(r)==="0"||o?LR(n):AR(n)}function ER(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?oi.SECONDARY_FALLBACK_SECONDS:t;return kt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Sn(z.RATE_LIMIT_SECONDARY,{error:ye[z.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ye[z.RATE_LIMIT_SECONDARY].suggestion})}function LR(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)+oi.RESET_BUFFER_SECONDS,0):void 0,i=r?ye[z.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime;return kt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function AR(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ye[z.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=OR(String(t),String(n))),Sn(z.FORBIDDEN_PERMISSIONS,{error:ye[z.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function _R(e){return e?.data?.errors?.some(n=>n.type===Ys.GRAPHQL_TYPE)??!1}function kR(e,t){let n=ye[e];return Sn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function IR(e){return Ks.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ye[z.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ye[z.NETWORK_CONNECTION_FAILED].suggestion}:Ks.TIMEOUT.some(t=>e.message.includes(t))?{error:ye[z.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ye[z.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Sn(e,t){return{type:"http",...t}}function OR(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?ye[z.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ye[z.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function up(e){return`user:${e}`}var FR=/[@/]/,vR=/^[A-Za-z0-9_-]+$/;function qs(e){return e.startsWith('"')||vR.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var dt=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(up(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=FR.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var DR=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Js=class extends dt{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(qs))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(DR):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}},Zs=class extends dt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(qs)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function ea(e){return new Js().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ta(e){return new Zs().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var na=class extends dt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function ra(e){return new na().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function oa(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var ia=class extends dt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function sa(e){return new ia().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function aa(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import MR from"crypto";var NR="v2",GR=new Set([]);function HR(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(GR.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function ce(e,t,n){let r=ca(HR(t)),o=n?`${n}:${r}`:r,i=MR.createHash("sha256").update(o).digest("hex");return`${NR}-${e}:${i}`}function ca(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=>ca(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${ca(i,t)}`}).join(",")}}`)}import BR from"node-cache";var UR=300*1e3,Te=new BR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ue={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},lp={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},He=new Map;function QR(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function $R(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function yr(e){let t=QR(e);if(!(!t||!$R(t)))try{ti(t,1)}catch{}}function ii(){let e=Date.now();for(let[t,n]of He.entries())e-n.startedAt>UR&&He.delete(t)}function Rr(e){return lp[e]||lp.default}function Sr(e,t,n){try{return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{try{let r=Te.keys();for(let o of r)Te.get(o);return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{return!1}}}async function he(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}ii();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Rr(u)}Sr(e,i,a)}return i}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}import jR from"node-cache";var br=new jR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function si(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}ii();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:br.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ue.hits++,yr(e);let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}return Sr(e,i.data,c),i.data}if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}Sr(e,s.value,c),br.set(e,{data:s.value,etag:s.etag})}return s.value}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}function Pk(){Te.flushAll(),br.flushAll(),He.clear(),ue.hits=0,ue.misses=0,ue.sets=0,ue.totalKeys=0,ue.lastReset=new Date}function Ot(e){let t=Te.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Te.del(r)>0&&n++}return n>0&&(ue.totalKeys=Te.keys().length),n}function wk(){return Ot("local-")}function Tk(){return Ot("lsp-")}function Ek(){let e=0;return e+=Ot("gh-api-"),e+=Ot("bb-api-"),e+=Ot("gh-repo-"),e+=Ot("bb-repo-"),e+=Ot("github-user"),e+=Ot("npm-search"),br.flushAll(),e}function Lk(){let e=ue.hits+ue.misses;return{...ue,hitRate:e>0?ue.hits/e*100:0,cacheSize:Te.keys().length}}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as Mk,DISCOVERY_IGNORED_FILE_NAMES as Nk,DISCOVERY_IGNORED_FOLDER_NAMES as Gk,getDiscoveryExtension as pp,shouldIgnoreDiscoveryDir as Cr,shouldIgnoreDiscoveryFile as bn}from"@octocodeai/octocode-engine/security";var dp=Symbol.for("octocode.rawResponseChars");function N(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function mp(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?mp(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,dp,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ne(e){if(!(typeof e!="object"||e===null))return mp(e[dp])}function Cn(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function fp(e){let t=Cn(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function xn(e){let t=Cn(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function hp(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var gp=30;async function yp(e,t,n){let r=await fe(t),o=ce("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await he(o,async()=>await WR(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function WR(e,t){try{let n=await Q(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(h=>h&&h.trim()).length===0)return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let r=ea(e);if(!r.trim())return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:gp,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 VR(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,p=Math.min(l,1e3),m=Math.min(Math.ceil(p/o),10),d=Math.min(i,Math.max(1,m)),f=d<m,g=Math.min(p,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:d,totalPages:m,perPage:o,totalMatches:p,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>p,hasMore:f,...f?{nextPage:d+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Cn(a.headers),rawResponseChars:N(a.data)}}catch(n){if(nt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:gp,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 V(n)}}async function VR(e,t){let n=KR(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(d=>!bn(d.path)),c=0,u=0,l=await Promise.allSettled(a.map(async d=>{s.add(d.path);let f=[],g=await Promise.allSettled((d.text_matches||[]).map(async C=>{let P=C.fragment,T=zR.sanitizeContent(P||"",d.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${d.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(_=>r.add(`${d.path}: ${_}`));try{let _=await O.minifyContent(P||"",d.path);P=_.content,_.failed?o=!0:_.type!=="failed"&&(f.push(_.type),i.push(_.type))}catch{o=!0}let L=C.matches?.flatMap(_=>Array.isArray(_.indices)&&_.indices.length>=2?[[_.indices[0],_.indices[1]]]:[])||[];return{context:P||"",positions:hp(C.fragment||"",L,P||"")}})),R=g.filter(C=>C.status==="fulfilled").map(C=>C.value),h=g.filter(C=>C.status==="rejected").length;h>0&&(u+=h);let y=d,S=Array.from(new Set(f));return{path:d.path,matches:R,url:d.html_url,repository:{nameWithOwner:d.repository.full_name,url:d.repository.url,pushedAt:d.repository.pushed_at||void 0},...y.last_modified_at&&{lastModifiedAt:y.last_modified_at},...S.length>0&&{minificationType:S.join(",")}}})),p=l.filter(d=>d.status==="fulfilled").map(d=>d.value);c=l.filter(d=>d.status==="rejected").length;let m={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let d=n.full_name.split("/");return d.length===2&&d[0]&&d[1]?{owner:d[0],repo:d[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 KR(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{readdirSync as YR,statSync as Rp}from"node:fs";import{join as XR}from"node:path";var xr=50,ai=5*1024*1024,ua=300*1024,Sp=5,qR=1e4,bp=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"]),la={maxDirectoryFiles:xr,maxTotalSize:ai,maxFileSize:ua};function pa(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function Cp(e){return Object.values(e).every(t=>t===0)}function da(e,t){if(!t&&e)return["Cannot verify completeness against remote tree; use forceRefresh or ghCloneRepo if completeness matters."];if(!e)return["Directory materialization is partial; inspect skipped counts or use ghCloneRepo before repo-wide reachability/dead-code conclusions."]}async function xp(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 ZR(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var JR=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function ZR(e,t){try{let o=new URL(e);if(!JR.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(),qR);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 Pp(e,t){let n=[],r=0;function o(i){let s;try{s=YR(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=XR(i,a);try{let u=Rp(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 wp(e){try{return Rp(e).size}catch{return 0}}import{writeFileSync as SS,mkdirSync as Op,existsSync as ha,rmSync as bS}from"node:fs";import{join as Fp,dirname as CS,resolve as vp,sep as Dp}from"node:path";import{existsSync as Lr,readFileSync as nS,writeFileSync as rS,mkdirSync as oS,rmSync as Er,readdirSync as iS,statSync as sS}from"node:fs";import{join as Ft}from"node:path";import{join as ci}from"node:path";import{createHash as Tp}from"node:crypto";function eS(e){return Pr(e)}function Pr(e){return ci(e,"tmp","clone")}function ui(e){return ci(e,"tmp","tree")}function tS(e){return e?`__sp_${Tp("sha256").update(e).digest("hex").substring(0,6)}`:""}function Ep(e){if(!/[\\/]/.test(e))return e;let t=Tp("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function ma(e,t,n,r,o){let i=`${Ep(r)}${tS(o)}`;return ci(Pr(e),t,n,i)}function wr(e,t,n,r){return ci(ui(e),t,n,Ep(r))}var aS=1440*60*1e3,cS=600*1e3,uS=2*1024*1024*1024,lS=50,Ap=".octocode-clone-meta.json",Pn=null;function pS(e){return typeof e=="object"&&e!==null}function dS(e){if(!pS(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),typeof e.commitSha=="string"&&e.commitSha.length===40&&(t.commitSha=e.commitSha),t}function fa(e){let t=Ft(e,Ap);if(!Lr(t))return null;try{return dS(JSON.parse(nS(t,"utf-8")))}catch{return null}}function Tn(e,t){try{rS(Ft(e,Ap),JSON.stringify(t,null,2),"utf-8")}catch{}}function _p(e){return Date.now()<new Date(e.expiresAt).getTime()}function En(e){let t=fa(e);return t?_p(t)?Lr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function mS(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return aS}function fS(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return uS}function hS(){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 lS}function Ln(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+mS()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function vt(e){let t=Ft(e,"..");try{Lr(t)||oS(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 pi(e){try{Lr(e)&&Er(e,{recursive:!0,force:!0})}catch{}}function Tr(e){try{return sS(e).isDirectory()}catch{return!1}}function Xt(e){try{return iS(e)}catch{return[]}}function*kp(e){for(let t of Xt(e)){let n=Ft(e,t);if(Tr(n))for(let r of Xt(n)){let o=Ft(n,r);if(Tr(o))for(let i of Xt(o)){let s=Ft(o,i);Tr(s)&&(yield s)}}}}function Lp(e){for(let t of[...Xt(e)]){let n=Ft(e,t);if(Tr(n)){for(let r of[...Xt(n)]){let o=Ft(n,r);if(Tr(o)&&Xt(o).length===0)try{Er(o,{recursive:!0,force:!0})}catch{}}if(Xt(n).length===0)try{Er(n,{recursive:!0,force:!0})}catch{}}}}function gS(e){let t=0;for(let n of kp(e))try{let r=fa(n);(!r||!_p(r))&&(Er(n,{recursive:!0,force:!0}),t++)}catch{}return t}function yS(e){let t=[];for(let n of kp(e)){let r=fa(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??hr(n)})}return t}function RS(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{Er(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Ip(e){if(!Lr(e))return 0;let t=0;try{t+=gS(e)}catch{return t}Lp(e);let n=RS(yS(e),fS(),hS());return t+=n,n>0&&Lp(e),t}function li(e){return Ip(Pr(e))}function wn(e){return Ip(ui(e))}function pI(e){Pn||(li(e),wn(e),Pn=setInterval(()=>{li(e),wn(e)},cS),Pn.unref())}function dI(){Pn&&(clearInterval(Pn),Pn=null)}async function ga(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=vp(Fp(a,n));if(!c.startsWith(a+Dp)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(u.hit&&!i&&ha(c)){let b=Pp(c,a),A=pa();return{localPath:c,repoRoot:a,files:b.files,fileCount:b.fileCount,totalSize:b.totalSize,complete:!0,verified:!1,...u.meta.commitSha?{commitSha:u.meta.commitSha}:{},directoryEntryCount:b.fileCount,eligibleFileCount:b.fileCount,savedFileCount:b.fileCount,skipped:A,limits:la,warnings:da(!0,!1),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await Q(o),p;try{p=(await l.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await l.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let d=m,f=pa(),g=[];for(let b of d){if(b.type!=="file"){f.nonFile+=1;continue}if(!b.download_url){f.missingDownloadUrl+=1;continue}if(b.size>ua){f.oversized+=1;continue}let A=pp(b.name,{lowercase:!0,leadingDot:!0});if(bp.has(A)){f.binary+=1;continue}g.push(b)}f.fileLimit=Math.max(0,g.length-xr);let R=g.slice(0,xr),h=o?.token,y=await xp(R,Sp,h);f.fetchFailed=R.length-y.length;let S=0,C=[];for(let b=0;b<y.length;b+=1){let{entry:A,content:M}=y[b];if(S+M.length>ai){f.totalSizeLimit=y.length-b;break}S+=M.length,C.push({entry:A,content:M})}wn(s),vt(a),ha(c)&&bS(c,{recursive:!0,force:!0}),Op(c,{recursive:!0,mode:448});let P=[];for(let{entry:b,content:A}of C){let M=vp(Fp(a,b.path));if(!M.startsWith(a+Dp)){f.pathTraversal+=1;continue}let B=CS(M);ha(B)||Op(B,{recursive:!0,mode:448}),SS(M,A,"utf-8"),P.push({path:b.path,size:A.length,type:"file"})}let T=Ln(e,t,r,"treeFetch",void 0,void 0,p);Tn(a,T);let L=Cp(f),_=L,w=f.nonFile>0;return{localPath:c,repoRoot:a,files:P,fileCount:P.length,totalSize:S,complete:L,verified:_,...p?{commitSha:p}:{},...w?{hasSubdirectories:!0}:{},directoryEntryCount:d.length,eligibleFileCount:g.length,savedFileCount:P.length,skipped:f,limits:la,warnings:da(L,_),cached:!1,expiresAt:T.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}import{writeFileSync as _S,mkdirSync as kS,existsSync as Gp}from"node:fs";import{join as IS,dirname as OS,resolve as FS,sep as vS}from"node:path";import{RequestError as Pa}from"octokit";import{completeMetadata as ya}from"@octocodeai/octocode-core";var x=new Proxy({},{get(e,t){return ya.toolNames[t]},ownKeys(){return Object.keys(ya.toolNames)},getOwnPropertyDescriptor(e,t){let n=ya.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as xS}from"@octocodeai/octocode-core";var Ra=new Proxy({},{get(e,t){return xS.tools[t]?.description??""}});import{completeMetadata as PS}from"@octocodeai/octocode-core";function Sa(e){return Object.prototype.hasOwnProperty.call(PS.tools,e)}import{completeMetadata as wS}from"@octocodeai/octocode-core";function ba(){return wS.baseSchema}var TS=new Proxy({},{get(e,t){return ba()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(ba())]))},getOwnPropertyDescriptor(e,t){let n=ba();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});function Ca(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 xa(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(d=>d.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(d=>d.name===s?!1:!!d.name.startsWith(p+".")).forEach(d=>u.push(d.path)),u.length===0&&p.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==p&&g.length>=3&&(p.startsWith(g)||g.startsWith(p))}).forEach(f=>u.push(f.path)),Array.from(new Set(u)).slice(0,3)}catch{return[]}}async function ES(e,t,n,r,o,i,s,a){let c=await Ae(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=V(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await xa(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Ca(i,m)]),{...l,...p&&{scopesSuggestion:p}}}async function LS(e,t,n,r,o,i){let s=V(t),a=await xa(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Ca(o,a)]),s}async function Mp(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:Ct.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:Ct.DECODE_FAILED.message,type:"unknown",status:422}}}async function Np(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"?Mp(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return V(i)}}async function AS(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 Ae(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 p=await Np(e,t,n,l.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return V(s)}}async function Ar(e,t,n={}){try{let r=await Q(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},u,l=a;try{u=await r.rest.repos.getContent(c)}catch(d){if(d instanceof Pa&&d.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(d instanceof Pa&&d.status===404)if(a){let f=await ES(r,d,c,o,i,s,a,t);if("result"in f)u=f.result,l=f.actualBranch;else return f}else return await LS(r,d,o,i,s,a);else{if(d instanceof Pa&&d.status===413)return await AS(r,o,i,s,a||l,t);throw d}}let p=u.data,m=xn(u.headers);if(Array.isArray(p))return{error:Ct.PATH_IS_DIRECTORY.message(x.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let d=typeof p.content=="string"?p.content:"",f=p.size??0,g;if(d.length>0)g=await Mp(d,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)g=await Np(r,o,i,p.sha,s);else return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!l&&!a)try{l=await Ae(o,i,t)}catch{}return{data:{rawContent:g.data,branch:l||void 0,resolvedRef:l||a||"HEAD"},status:200,rawResponseChars:N(p),...m?{etag:m}:{}}}return{error:Ct.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return V(r)}}async function wa(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=FS(IS(a,n));if(!c.startsWith(a+vS)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(!i&&u.hit&&Gp(c))return{localPath:c,repoRoot:a,path:n,size:wp(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await Ar({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}`)}wn(s),vt(a);let p=OS(c);Gp(p)||kS(p,{recursive:!0,mode:448}),_S(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,d=Ln(e,t,m,"treeFetch");return Tn(a,d),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:d.expiresAt,owner:e,repo:t,branch:m}}import{ContentSanitizer as _a}from"@octocodeai/octocode-engine/contentSanitizer";function _r(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function rt(e){return _r(e).length}function di(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(`
11
- `),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)}}var DS=/\.(?:md|markdown|mdx)$/i;function MS(e){return DS.test(e.split(/[?#]/,1)[0]??e)}function Hp(e,t){return MS(t)?GS(NS(e)):null}function mi(e,t){let n=Hp(e,t);if(n===null||n.length===0)return null;let r=[];return Up(n,r),r.join(`
12
- `)}function Bp(e,t){let n=Hp(e,t);return n===null?null:n.map(Qp)}function NS(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let u=s[1][0],l=s[1].length;r?r.marker===u&&l>=r.length&&(r=void 0):r={marker:u,length:l};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function GS(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n[n.length-1].level>=r.level;)n.pop();let o=n[n.length-1];o?o.children.push(r):t.push(r),n.push(r)}return t}function Up(e,t){for(let n of e){let r=String(n.line).padStart(4," "),o=" ".repeat(Math.max(0,n.level-1));t.push(`${r}| ${o}${"#".repeat(n.level)} ${n.text}`),Up(n.children,t)}}function Qp(e){let t=`${"#".repeat(e.level)} ${e.text}`;return{name:t,kind:"markdownHeading",range:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},selectionRange:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},children:e.children.map(Qp)}}import{getConfigSync as HS,DEFAULT_OUTPUT_CONFIG as BS}from"@octocodeai/config";function Dt(){try{return HS().output.pagination.defaultCharLength}catch{return BS.pagination.defaultCharLength}}var $p=1e5;function pO(e){let t=Math.min(Math.max(Dt(),1),$p),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,$p)}function US(e,t,n){return O.byteSliceContent(e,t,n)}function fi(e,t){return O.byteToCharOffset(e,t)}function jp(e,t){return O.charToByteOffset(e,t)}function zp(e){return O.charToByteOffset(e,e.length)}function fO(e,t,n){let r=US(e,t,t+n);return{charOffset:fi(e,t),charLength:r.length,text:r}}function Ta(e,t,n,r){return O.sliceContent(e,t,n,r)}function hi(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=zp(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,p,m,d,f,g;if(o==="bytes"){let R=Math.min(t,s),h=Math.min(R+n,s);p=fi(e,R),m=fi(e,h),m<i&&jp(e,m)<h&&(m+=1);let y=Ta(e,p,m-p);c=y.text,p=y.charOffset,m=y.charOffset+y.charLength,u=y.byteOffset,l=y.byteOffset+y.byteLength,d=l<s;let S=r.actualOffset??R;f=Math.floor(S/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let R=Ta(e,t,n);c=R.text,p=R.charOffset,m=R.charOffset+R.charLength,u=R.byteOffset,l=R.byteOffset+R.byteLength,d=m<i;let h=r.actualOffset??p;f=Math.floor(h/a)+1,g=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:u,byteLength:l-u,totalBytes:s,nextByteOffset:d?l:void 0,charOffset:p,charLength:c.length,totalChars:i,nextCharOffset:d?m:void 0,hasMore:d,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:g}}function yO(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function Ea(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}function RO(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
8
+ import{withSecurityValidation as hy,withBasicSecurityValidation as gy}from"@octocodeai/octocode-engine/security";function Vu(e,t){let n=hy(e,(r,o)=>t(r,o));return(r,o)=>n(r,o)}function Ku(e,t){let n=gy((r,o)=>e(r,o),t);return(r,o)=>n(r,o)}var me=30,oe=100,qL=10,JL=100,Yu=200,Ne=20,ct=100,Mo=20,ln=50,Je=1e4,bt=20,No=1e3,Xu=100,pn=5e4,qu=8e3,Go=1e5,Ju=500;var Ts={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},tr={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"}},nr={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})`}},yy={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"}},Ct={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}`}},xt={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"}},Ee={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}`}},Ry={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}`}},rr={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Sy={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}`}},eA={...Ts,...tr,...nr,...yy,...Ct,...xt,...Ee,...Ry,...rr,...Sy};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",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"},by=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(by||{}),Zu={[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"},[H.LSP_SERVER_UNAVAILABLE]:{code:H.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}};var xe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Zu[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
9
+ Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function Es(e){return e instanceof xe}function el(e,t=H.TOOL_EXECUTION_FAILED,n){if(Es(e))return e;if(e instanceof Error)return new xe(t,e.message,n,e);let r=String(e);return new xe(t,r,n)}import{redactPath as or}from"@octocodeai/octocode-engine/pathUtils";var Le={pathValidationFailed:(e,t,n)=>new xe(H.PATH_VALIDATION_FAILED,t||`Path validation failed: ${or(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=or(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 xe(H.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new xe(H.FILE_READ_FAILED,`Failed to read file: ${or(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new xe(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)}). Use startLine/endLine, matchString, or charOffset/charLength to read a bounded slice.`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new xe(H.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${or(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new xe(H.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new xe(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 xe(H.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new xe(H.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as mR}from"octokit";import{throttling as fR}from"@octokit/plugin-throttling";import{createHash as hR}from"crypto";function Ze(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function ut(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 ir(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var sr=new Map,Cy=300*1e3;function xy(e){let t=Ze(e),n=sr.get(t);return!n||Date.now()-n.cachedAt>=Cy?!1:n.credentials?!ut(n.credentials):!0}function ar(e){e?sr.delete(Ze(e)):sr.clear()}function tl(e){let t=Ze(e);if(xy(t))return sr.get(t).credentials}function nl(e,t){let n=Ze(e);sr.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as $o,readFileSync as al,writeFileSync as cl,unlinkSync as sl,statSync as Ay,chmodSync as ky}from"node:fs";import{createCipheriv as _y,createDecipheriv as Iy,randomBytes as ul}from"node:crypto";import{existsSync as Ho,mkdirSync as Bo}from"node:fs";import{join as je}from"node:path";import{getOctocodeHome as Py}from"@octocodeai/config";var Uo=448;function rl(){return Py(process.env)}function zt(){return Ie}var Ie=rl(),we={home:Ie,config:je(Ie,".octocoderc"),credentials:je(Ie,"credentials.json"),key:je(Ie,".key"),session:je(Ie,"session.json"),stats:je(Ie,"stats.json"),tmp:je(Ie,"tmp"),clone:je(Ie,"tmp","clone"),tree:je(Ie,"tmp","tree"),repos:je(Ie,"tmp","clone"),cliConfig:je(Ie,"config.json"),lspConfig:je(Ie,"lsp-servers.json")};function Qo(){Ho(we.home)||Bo(we.home,{recursive:!0,mode:Uo})}function wy(){ol()}function Ls(){Qo(),Ho(we.tmp)||Bo(we.tmp,{recursive:!0,mode:Uo})}function ol(){Ls(),Ho(we.clone)||Bo(we.clone,{recursive:!0,mode:Uo})}function Ty(){Ls(),Ho(we.tree)||Bo(we.tree,{recursive:!0,mode:Uo})}import{z as Se}from"zod";var Ey=Se.object({token:Se.string(),tokenType:Se.literal("oauth"),scopes:Se.array(Se.string()).optional(),refreshToken:Se.string().optional(),expiresAt:Se.string().optional(),refreshTokenExpiresAt:Se.string().optional()}),Ly=Se.object({hostname:Se.string(),username:Se.string(),token:Ey,gitProtocol:Se.enum(["ssh","https"]),createdAt:Se.string(),updatedAt:Se.string()}),il=Se.object({version:Se.number(),credentials:Se.record(Se.string(),Ly)});var As=we.home,lt=we.credentials,et=we.key,ll="aes-256-gcm",Oy=16;function Pt(){Qo()}function pl(){if(Pt(),$o(et))return Ay(et).mode&511&63&&ky(et,384),Buffer.from(al(et,"utf8"),"hex");let e=ul(32);return cl(et,e.toString("hex"),{mode:384}),e}function jo(e){let t=pl(),n=ul(Oy),r=_y(ll,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 zo(e){let t=pl(),[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=Iy(ll,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function pt(){if(Pt(),!$o(lt))return{version:1,credentials:{}};try{let e=al(lt,"utf8"),t=zo(e),n=JSON.parse(t),r=il.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function ks(e){Pt();let t=jo(JSON.stringify(e,null,2));cl(lt,t,{mode:384})}function dl(){try{$o(lt)&&sl(lt),$o(et)&&sl(et)}catch{}}import{refreshToken as Fy}from"@octokit/oauth-methods";import{request as vy}from"@octokit/request";var dn="178c6fc778ccc68e1d6a",wt="github.com";function Dy(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 My(e){return e==="github.com"||e===wt?"https://api.github.com":`https://${e}/api/v3`}async function _s(e,t=wt,n=dn){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(ir(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Fy({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:vy.defaults({baseUrl:My(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?Dy(o.message):"Token refresh failed"}}}async function ml(e,t=wt,n=dn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!ut(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await _s(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as Hy}from"@octocodeai/config";import{execFile as Ny}from"child_process";var Gy=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Wo(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=Gy.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Ny("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Vo=null;function fl(e){Vo=e}function Is(){Vo=null}function By(){if(!Vo)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Vo}async function Tt(e){let t=e?.hostname??wt,n=e?.clientId??dn,r=e?.getGhCliToken??Wo,o=Hy();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await By().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
10
+ `)}return null}async function Os(e=wt){let t=await Tt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Fs(e=wt,t=dn){let n=await Tt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}async function vs(e){let t=Ze(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=pt();return r.credentials[t]=n,ks(r),ar(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Wt(e="github.com",t){let n=Ze(e);if(!t?.bypassCache){let i=tl(n);if(i!==void 0)return i}let o=pt().credentials[n]||null;return nl(n,o),o}function Ko(e="github.com"){let t=Ze(e);return pt().credentials[t]||null}async function hl(e="github.com"){let t=Ze(e),n=!1,r=pt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?dl():ks(r),n=!0),ar(t),{success:n,deletedFromFile:n}}async function gl(){let e=pt();return Object.keys(e.credentials)}function yl(){let e=pt();return Object.keys(e.credentials)}async function Rl(e="github.com"){return await Wt(e)!==null}function Sl(e="github.com"){return Ko(e)!==null}async function Yo(e,t){let n=await Wt(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await vs(n),!0):!1}function bl(){return lt}async function Cl(e="github.com"){let t=await Wt(e);return!t||!t.token||ut(t)?null:t.token.token}function xl(e="github.com"){let t=Ko(e);return!t||!t.token||ut(t)?null:t.token.token}async function Pl(e,t){return _s({getCredentials:Wt,updateToken:Yo},e,t)}async function Ds(e,t){return ml({getCredentials:Wt,updateToken:Yo},e,t)}fl({getTokenWithRefresh:Ds});import fn from"node:os";import wl from"node:path";var cr=fn.platform()==="win32",Ms=fn.platform()==="darwin",Ns=fn.platform()==="linux",mn=fn.homedir();function Tl(){return cr?process.env.APPDATA||wl.join(mn,"AppData","Roaming"):mn}function El(){return cr?process.env.LOCALAPPDATA||wl.join(mn,"AppData","Local"):mn}function Ll(){return Ms?"macOS":cr?"Windows":Ns?"Linux":fn.platform()}function Al(){return fn.arch()}import{randomUUID as Zy}from"node:crypto";import{existsSync as Gs,readFileSync as Fl,writeFileSync as zy,unlinkSync as Wy,renameSync as Vy}from"node:fs";import{isStatsEnabled as vl}from"@octocodeai/config";import{z as W}from"zod";var Uy=W.object({rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),calls:W.number()}),Qy=W.object({hits:W.record(W.string(),W.number()).default({}),rateLimits:W.number().default(0)}),Xo=W.record(W.string(),W.number()).default({}),$y=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Xo,rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),charSavingsCalls:W.number(),githubCacheHits:W.number(),githubCacheRateLimits:W.number(),packageRegistryFailures:W.number().default(0),packageRegistryFailuresByRegistry:Xo}),qo=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Xo,charsSavedByTool:W.record(W.string(),Uy).default({}),githubCacheHits:Qy.default({hits:{},rateLimits:0}),packageRegistryFailures:Xo,totalUsage:$y.optional()}),kl=W.object({version:W.literal(1),sessionId:W.string(),createdAt:W.string(),lastActiveAt:W.string(),stats:qo.optional()}),_l=W.object({version:W.literal(1),stats:qo});function Il(e){return Object.values(e).reduce((t,n)=>t+n,0)}function jy(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:Il(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Il(o),packageRegistryFailuresByRegistry:o}}function Et(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:jy(t)}}function Lt(){return Et({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Vt=we.session,Kt=we.stats;function Ol(e,t){let n=`${e}.tmp`;zy(n,JSON.stringify(t,null,2),{mode:384}),Vy(n,e)}function Ky(e){let t=JSON.parse(e),n=_l.safeParse(t);if(n.success)return Et(n.data.stats);let r=qo.safeParse(t);return r.success?Et(r.data):null}function Yy(){if(!Gs(Kt))return Lt();try{let e=Fl(Kt,"utf8");return Ky(e)??Lt()}catch{return Lt()}}function Jo(e){Pt(),vl()&&Ol(Kt,{version:e.version,stats:Et(e.stats)});let{stats:t,...n}=e;Ol(Vt,n)}function Dl(){if(!Gs(Vt))return null;try{let e=Fl(Vt,"utf8"),t=JSON.parse(e),n=kl.safeParse(t);return n.success?{...n.data,stats:vl()?Yy():Lt()}:null}catch{return null}}function Ml(){let e=!1;for(let t of[Vt,Kt])if(Gs(t))try{Wy(t),e=!0}catch{return!1}return e}var Xy=6e4,ze=null,At=!1,hn=null,Hs=!1,ur=null,lr=null,pr=null,Zo=!1;function qy(){Hs||(Hs=!0,ur=()=>{dr()},lr=()=>{dr()},pr=()=>{dr()},process.on("exit",ur),process.on("SIGINT",lr),process.on("SIGTERM",pr))}function Bs(){ur&&(process.removeListener("exit",ur),ur=null),lr&&(process.removeListener("SIGINT",lr),lr=null),pr&&(process.removeListener("SIGTERM",pr),pr=null),Hs=!1}function Jy(){hn||(hn=setInterval(()=>{At&&ze&&(Jo(ze),At=!1)},Xy),hn.unref())}function Us(){hn&&(clearInterval(hn),hn=null)}function mr(){if(ze)return ze;let e=Dl();return e&&(ze=e),e}function gn(e){ze=e,At=!0,qy(),Jy()}function fr(){At&&ze&&(Jo(ze),At=!1)}function dr(){if(!Zo&&At&&ze){Zo=!0;try{Jo(ze),At=!1}catch{}finally{Zo=!1}}}function Qs(){ze=null,At=!1,Zo=!1}function Nl(){Qs(),Us(),Bs()}var eR=1;function tR(e){return Et(e)}function nR(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 Gl(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 rR(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 Hl(){let e=new Date().toISOString();return{version:eR,sessionId:Zy(),createdAt:e,lastActiveAt:e,stats:Lt()}}function Bl(){fr()}function Ul(){dr()}function Ql(e){if(e?.forceNew){let r=Hl();return gn(r),fr(),r}let t=mr();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return gn(r),fr(),r}let n=Hl();return gn(n),fr(),n}function $l(){return mr()?.sessionId??null}function Ge(e){let t=mr();if(!t)return{success:!1,session:null};let n=tR(t.stats),r=Et({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Gl(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:nR(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:rR(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Gl(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return gn(o),{success:!0,session:o}}function jl(e=1){return Ge({toolCalls:e})}function zl(e=1){return Ge({errors:e})}function ei(e=1){return Ge({rateLimits:e})}function Wl(e,t=1){return Ge({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function ti(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Ge({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function ni(e,t=1){return Ge({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ri(e=1){return Ge({githubCacheHits:{hits:{},rateLimits:e}})}function Vl(e,t=1){return Ge({packageRegistryFailures:{[e]:t}})}function Kl(){let e=mr();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Lt()};return gn(t),{success:!0,session:t}}function Yl(){return Qs(),Us(),Bs(),Ml()}function Xl(){Nl()}import{z as de}from"zod";var ql=de.looseObject({$schema:de.string().optional(),version:de.number().int().optional(),github:de.record(de.string(),de.unknown()).optional(),local:de.record(de.string(),de.unknown()).optional(),tools:de.record(de.string(),de.unknown()).optional(),network:de.record(de.string(),de.unknown()).optional(),lsp:de.record(de.string(),de.unknown()).optional(),output:de.record(de.string(),de.unknown()).optional()});import{existsSync as oR,readdirSync as iR,lstatSync as sR}from"node:fs";import{join as aR}from"node:path";function hr(e){if(!oR(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=iR(r)}catch{continue}for(let i of o){let s=aR(r,i);try{let a=sR(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function cR(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}import{getConfigSync as Jl,invalidateConfigCache as lR}from"@octocodeai/config";var Yt="18.1.2";import{maskSensitiveData as pR}from"@octocodeai/octocode-engine/mask";var kt=null,yn=null,$s=Tt;function zk(e){e.resolveTokenFull&&($s=e.resolveTokenFull)}function Wk(){$s=Tt}var dR=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function js(){try{let e=await $s({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:dR.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Zl(){if(kt!==null)return;if(yn!==null)return yn;let e=(async()=>{let t=Jl(),n=await js();kt={version:Yt,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();yn=e;try{await e}catch(t){throw yn===e&&(kt=null,yn=null),t}}function Vk(){kt=null,yn=null,lR()}function gr(){if(!kt){let e=pR(Ts.NOT_INITIALIZED.message);throw new Error(e)}return kt}async function zs(){return(await js()).token}function Kk(){return gr().enableLocal}function ep(){let e=gr();return e.enableLocal&&e.enableClone}async function Yk(){return kt!==null?kt.tokenSource:(await js()).source}function Ws(){return"github"}function Vs(){let e=Jl().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}function _t(e){(e.provider?Ge({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):ei(1)).session&&e.provider==="github"&&ri(1)}function tp(e){Ge({packageRegistryFailures:{[e]:1}})}function sp(e){return hR("sha256").update(e).digest("hex").substring(0,16)}async function fe(e){let t=e?.token??await zs(),n=t?sp(t):"anon",r=gr().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var gR=mR.plugin(fR),yR=300*1e3,Ks=50,RR=60*1e3;function ap(e){return Date.now()-e.createdAt>yR}var tt=new Map,It=null;function cp(){for(let[e,t]of tt.entries())ap(t)&&tt.delete(e);if(tt.size>Ks){let e=tt.size-Ks,t=0;for(let[n]of tt){if(t>=e)break;tt.delete(n),t++}}}function SR(){It||(It=setInterval(cp,RR),typeof It=="object"&&"unref"in It&&It.unref())}var np=3,rp=60;function op(e,t,n){_t({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var bR=()=>({onRateLimit:(e,t,n,r)=>(op("primary",e,t),r<np&&e<rp),onSecondaryRateLimit:(e,t,n,r)=>(op("secondary",e,t),r<np&&e<rp)});function CR(e){let t=gr(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Yt}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:bR(),log:r,...e&&{auth:e}};return new gR(o)}async function Q(e){SR();let t=e?.token??await zs(),n=t?sp(t):"ANONYMOUS",r=tt.get(n);if(r&&!ap(r))return r.client;tt.size>=Ks&&cp();let o=CR(t??void 0);return tt.set(n,{client:o,createdAt:Date.now()}),o}var xR=200,Rn=new Map;async function Ae(e,t,n){let r=`${e}/${t}`,o=Rn.get(r);if(o)return o;let i=await Q(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return ip(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}),ip(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 ip(e,t){if(Rn.size>=xR){let n=Rn.keys().next().value;n!==void 0&&Rn.delete(n)}Rn.set(e,t)}function s_(){tt.clear(),Rn.clear(),It&&(clearInterval(It),It=null)}import{ContentSanitizer as XR}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as PR}from"node:module";var wR=PR(import.meta.url),up="@octocodeai/octocode-engine",TR=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??wR(up),oi,ER=TR,Ys=class extends Error{constructor(n){super(`Failed to load native dependency ${up}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function J(){if(oi)return oi;try{return oi=ER(),oi}catch(e){throw new Ys(e)}}var O={applyContentViewMinification(e,t){return J().applyContentViewMinification(e,t)},applyMinification(e,t){return J().applyMinification(e,t)},minifyContent(e,t){return J().minifyContent(e,t)},minifyContentSync(e,t){return J().minifyContentSync(e,t)},minifyContentResult(e,t){return J().minifyContentResult(e,t)},minifyMarkdownCore(e){return J().minifyMarkdownCore(e)},extractSignatures(e,t){return J().extractSignatures(e,t)},extractJsSymbols(e,t){return J().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return J().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return J().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return J().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return J().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return J().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return J().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return J().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return J().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return J().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return J().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return J().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return J().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return J().parseRipgrepJson(e,t)},searchRipgrep(e){return J().searchRipgrep(e)},queryFileSystem(e){return J().queryFileSystem(e)},extractMatchingLines(e,t,n){return J().extractMatchingLines(e,t,n)},filterPatch(e,t){return J().filterPatch(e,t)},computeLineDiff(e,t){return J().computeLineDiff(e,t)},charToByteOffset(e,t){return J().charToByteOffset(e,t)},byteToCharOffset(e,t){return J().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return J().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return J().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return J().SIGNATURES_ONLY_HINT}};import{RequestError as pp}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"},ye={[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."}},lp={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},Xs={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},qs={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ii={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var LR=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function nt(e){if(!(e instanceof pp)||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 LR.some(o=>r.includes(o))})}function V(e){return e instanceof pp?AR(e):e instanceof Error?MR(e):{error:typeof e=="string"?e:ye[z.UNKNOWN].message,type:"unknown"}}function AR(e){let{status:t,message:n,response:r}=e;if(t===403)return _R(n,r);if(t===429)return kR(n,r);let o=lp[t];return o?DR(o,t):Sn(z.UNKNOWN,{error:n||ye[z.UNKNOWN].message,status:t})}function Js(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function kR(e,t){let n=t?.headers,r=Js(n,"retry-after"),o=Js(n,"x-ratelimit-reset"),i=Js(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ii.RESET_BUFFER_SECONDS,0):void 0);return _t({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:e||ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function _R(e,t){let n=t?.headers;if(qs.SECONDARY.test(e))return IR(n);let r=n?.["x-ratelimit-remaining"],o=vR(t);return r!==void 0&&String(r)==="0"||o?OR(n):FR(n)}function IR(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ii.SECONDARY_FALLBACK_SECONDS:t;return _t({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Sn(z.RATE_LIMIT_SECONDARY,{error:ye[z.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ye[z.RATE_LIMIT_SECONDARY].suggestion})}function OR(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)+ii.RESET_BUFFER_SECONDS,0):void 0,i=r?ye[z.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime;return _t({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function FR(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ye[z.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=NR(String(t),String(n))),Sn(z.FORBIDDEN_PERMISSIONS,{error:ye[z.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function vR(e){return e?.data?.errors?.some(n=>n.type===qs.GRAPHQL_TYPE)??!1}function DR(e,t){let n=ye[e];return Sn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function MR(e){return Xs.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ye[z.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ye[z.NETWORK_CONNECTION_FAILED].suggestion}:Xs.TIMEOUT.some(t=>e.message.includes(t))?{error:ye[z.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ye[z.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Sn(e,t){return{type:"http",...t}}function NR(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?ye[z.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ye[z.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function dp(e){return`user:${e}`}var GR=/[@/]/,HR=/^[A-Za-z0-9_-]+$/;function Zs(e){return e.startsWith('"')||HR.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var dt=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(dp(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=GR.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var BR=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ea=class extends dt{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(Zs))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(BR):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}},ta=class extends dt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Zs)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function na(e){return new ea().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ra(e){return new ta().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var oa=class extends dt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function ia(e){return new oa().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function sa(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var aa=class extends dt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function ca(e){return new aa().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function ua(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import UR from"crypto";var QR="v2",$R=new Set([]);function jR(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($R.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function ce(e,t,n){let r=la(jR(t)),o=n?`${n}:${r}`:r,i=UR.createHash("sha256").update(o).digest("hex");return`${QR}-${e}:${i}`}function la(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=>la(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${la(i,t)}`}).join(",")}}`)}import zR from"node-cache";var WR=300*1e3,Te=new zR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ue={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},mp={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},He=new Map;function VR(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function KR(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function yr(e){let t=VR(e);if(!(!t||!KR(t)))try{ni(t,1)}catch{}}function si(){let e=Date.now();for(let[t,n]of He.entries())e-n.startedAt>WR&&He.delete(t)}function Rr(e){return mp[e]||mp.default}function Sr(e,t,n){try{return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{try{let r=Te.keys();for(let o of r)Te.get(o);return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{return!1}}}async function he(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}si();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Rr(u)}Sr(e,i,a)}return i}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}import YR from"node-cache";var br=new YR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function ai(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}si();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:br.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ue.hits++,yr(e);let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}return Sr(e,i.data,c),i.data}if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}Sr(e,s.value,c),br.set(e,{data:s.value,etag:s.etag})}return s.value}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}function H_(){Te.flushAll(),br.flushAll(),He.clear(),ue.hits=0,ue.misses=0,ue.sets=0,ue.totalKeys=0,ue.lastReset=new Date}function Ot(e){let t=Te.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Te.del(r)>0&&n++}return n>0&&(ue.totalKeys=Te.keys().length),n}function B_(){return Ot("local-")}function U_(){return Ot("lsp-")}function Q_(){let e=0;return e+=Ot("gh-api-"),e+=Ot("bb-api-"),e+=Ot("gh-repo-"),e+=Ot("bb-repo-"),e+=Ot("github-user"),e+=Ot("npm-search"),br.flushAll(),e}function $_(){let e=ue.hits+ue.misses;return{...ue,hitRate:e>0?ue.hits/e*100:0,cacheSize:Te.keys().length}}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as J_,DISCOVERY_IGNORED_FILE_NAMES as Z_,DISCOVERY_IGNORED_FOLDER_NAMES as eI,getDiscoveryExtension as fp,shouldIgnoreDiscoveryDir as Cr,shouldIgnoreDiscoveryFile as bn}from"@octocodeai/octocode-engine/security";var hp=Symbol.for("octocode.rawResponseChars");function N(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function gp(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?gp(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,hp,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ne(e){if(!(typeof e!="object"||e===null))return gp(e[hp])}function Cn(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function yp(e){let t=Cn(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function xn(e){let t=Cn(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function Rp(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var Sp=30;async function bp(e,t,n){let r=await fe(t),o=ce("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await he(o,async()=>await qR(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function qR(e,t){try{let n=await Q(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(h=>h&&h.trim()).length===0)return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let r=na(e);if(!r.trim())return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Sp,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 JR(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,p=Math.min(l,1e3),m=Math.min(Math.ceil(p/o),10),d=Math.min(i,Math.max(1,m)),f=d<m,g=Math.min(p,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:d,totalPages:m,perPage:o,totalMatches:p,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>p,hasMore:f,...f?{nextPage:d+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Cn(a.headers),rawResponseChars:N(a.data)}}catch(n){if(nt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Sp,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 V(n)}}async function JR(e,t){let n=ZR(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(d=>!bn(d.path)),c=0,u=0,l=await Promise.allSettled(a.map(async d=>{s.add(d.path);let f=[],g=await Promise.allSettled((d.text_matches||[]).map(async C=>{let P=C.fragment,T=XR.sanitizeContent(P||"",d.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${d.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${d.path}: ${k}`));try{let k=await O.minifyContent(P||"",d.path);P=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let L=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:P||"",positions:Rp(C.fragment||"",L,P||"")}})),R=g.filter(C=>C.status==="fulfilled").map(C=>C.value),h=g.filter(C=>C.status==="rejected").length;h>0&&(u+=h);let y=d,S=Array.from(new Set(f));return{path:d.path,matches:R,url:d.html_url,repository:{nameWithOwner:d.repository.full_name,url:d.repository.url,pushedAt:d.repository.pushed_at||void 0},...y.last_modified_at&&{lastModifiedAt:y.last_modified_at},...S.length>0&&{minificationType:S.join(",")}}})),p=l.filter(d=>d.status==="fulfilled").map(d=>d.value);c=l.filter(d=>d.status==="rejected").length;let m={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let d=n.full_name.split("/");return d.length===2&&d[0]&&d[1]?{owner:d[0],repo:d[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 ZR(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{readdirSync as eS,statSync as Cp}from"node:fs";import{join as tS}from"node:path";var xr=50,ci=5*1024*1024,pa=300*1024,xp=5,nS=1e4,Pp=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"]),da={maxDirectoryFiles:xr,maxTotalSize:ci,maxFileSize:pa};function ma(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function wp(e){return Object.values(e).every(t=>t===0)}function fa(e,t){if(!t&&e)return["Cannot verify completeness against remote tree; use forceRefresh or ghCloneRepo if completeness matters."];if(!e)return["Directory materialization is partial; inspect skipped counts or use ghCloneRepo before repo-wide reachability/dead-code conclusions."]}async function Tp(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 oS(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var rS=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function oS(e,t){try{let o=new URL(e);if(!rS.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(),nS);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 Ep(e,t){let n=[],r=0;function o(i){let s;try{s=eS(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=tS(i,a);try{let u=Cp(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 Lp(e){try{return Cp(e).size}catch{return 0}}import{writeFileSync as wS,mkdirSync as Dp,existsSync as ya,rmSync as TS}from"node:fs";import{join as Mp,dirname as ES,resolve as Np,sep as Gp}from"node:path";import{existsSync as Lr,readFileSync as aS,writeFileSync as cS,mkdirSync as uS,rmSync as Er,readdirSync as lS,statSync as pS}from"node:fs";import{join as Ft}from"node:path";import{join as ui}from"node:path";import{createHash as Ap}from"node:crypto";function iS(e){return Pr(e)}function Pr(e){return ui(e,"tmp","clone")}function li(e){return ui(e,"tmp","tree")}function sS(e){return e?`__sp_${Ap("sha256").update(e).digest("hex").substring(0,6)}`:""}function kp(e){if(!/[\\/]/.test(e))return e;let t=Ap("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function ha(e,t,n,r,o){let i=`${kp(r)}${sS(o)}`;return ui(Pr(e),t,n,i)}function wr(e,t,n,r){return ui(li(e),t,n,kp(r))}var dS=1440*60*1e3,mS=600*1e3,fS=2*1024*1024*1024,hS=50,Ip=".octocode-clone-meta.json",Pn=null;function gS(e){return typeof e=="object"&&e!==null}function yS(e){if(!gS(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),typeof e.commitSha=="string"&&e.commitSha.length===40&&(t.commitSha=e.commitSha),t}function ga(e){let t=Ft(e,Ip);if(!Lr(t))return null;try{return yS(JSON.parse(aS(t,"utf-8")))}catch{return null}}function Tn(e,t){try{cS(Ft(e,Ip),JSON.stringify(t,null,2),"utf-8")}catch{}}function Op(e){return Date.now()<new Date(e.expiresAt).getTime()}function En(e){let t=ga(e);return t?Op(t)?Lr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function RS(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return dS}function SS(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return fS}function bS(){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 hS}function Ln(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+RS()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function vt(e){let t=Ft(e,"..");try{Lr(t)||uS(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 di(e){try{Lr(e)&&Er(e,{recursive:!0,force:!0})}catch{}}function Tr(e){try{return pS(e).isDirectory()}catch{return!1}}function Xt(e){try{return lS(e)}catch{return[]}}function*Fp(e){for(let t of Xt(e)){let n=Ft(e,t);if(Tr(n))for(let r of Xt(n)){let o=Ft(n,r);if(Tr(o))for(let i of Xt(o)){let s=Ft(o,i);Tr(s)&&(yield s)}}}}function _p(e){for(let t of[...Xt(e)]){let n=Ft(e,t);if(Tr(n)){for(let r of[...Xt(n)]){let o=Ft(n,r);if(Tr(o)&&Xt(o).length===0)try{Er(o,{recursive:!0,force:!0})}catch{}}if(Xt(n).length===0)try{Er(n,{recursive:!0,force:!0})}catch{}}}}function CS(e){let t=0;for(let n of Fp(e))try{let r=ga(n);(!r||!Op(r))&&(Er(n,{recursive:!0,force:!0}),t++)}catch{}return t}function xS(e){let t=[];for(let n of Fp(e)){let r=ga(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??hr(n)})}return t}function PS(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{Er(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function vp(e){if(!Lr(e))return 0;let t=0;try{t+=CS(e)}catch{return t}_p(e);let n=PS(xS(e),SS(),bS());return t+=n,n>0&&_p(e),t}function pi(e){return vp(Pr(e))}function wn(e){return vp(li(e))}function LI(e){Pn||(pi(e),wn(e),Pn=setInterval(()=>{pi(e),wn(e)},mS),Pn.unref())}function AI(){Pn&&(clearInterval(Pn),Pn=null)}async function Ra(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=Np(Mp(a,n));if(!c.startsWith(a+Gp)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(u.hit&&!i&&ya(c)){let b=Ep(c,a),A=ma();return{localPath:c,repoRoot:a,files:b.files,fileCount:b.fileCount,totalSize:b.totalSize,complete:!0,verified:!1,...u.meta.commitSha?{commitSha:u.meta.commitSha}:{},directoryEntryCount:b.fileCount,eligibleFileCount:b.fileCount,savedFileCount:b.fileCount,skipped:A,limits:da,warnings:fa(!0,!1),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await Q(o),p;try{p=(await l.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await l.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let d=m,f=ma(),g=[];for(let b of d){if(b.type!=="file"){f.nonFile+=1;continue}if(!b.download_url){f.missingDownloadUrl+=1;continue}if(b.size>pa){f.oversized+=1;continue}let A=fp(b.name,{lowercase:!0,leadingDot:!0});if(Pp.has(A)){f.binary+=1;continue}g.push(b)}f.fileLimit=Math.max(0,g.length-xr);let R=g.slice(0,xr),h=o?.token,y=await Tp(R,xp,h);f.fetchFailed=R.length-y.length;let S=0,C=[];for(let b=0;b<y.length;b+=1){let{entry:A,content:M}=y[b];if(S+M.length>ci){f.totalSizeLimit=y.length-b;break}S+=M.length,C.push({entry:A,content:M})}wn(s),vt(a),ya(c)&&TS(c,{recursive:!0,force:!0}),Dp(c,{recursive:!0,mode:448});let P=[];for(let{entry:b,content:A}of C){let M=Np(Mp(a,b.path));if(!M.startsWith(a+Gp)){f.pathTraversal+=1;continue}let B=ES(M);ya(B)||Dp(B,{recursive:!0,mode:448}),wS(M,A,"utf-8"),P.push({path:b.path,size:A.length,type:"file"})}let T=Ln(e,t,r,"treeFetch",void 0,void 0,p);Tn(a,T);let L=wp(f),k=L,w=f.nonFile>0;return{localPath:c,repoRoot:a,files:P,fileCount:P.length,totalSize:S,complete:L,verified:k,...p?{commitSha:p}:{},...w?{hasSubdirectories:!0}:{},directoryEntryCount:d.length,eligibleFileCount:g.length,savedFileCount:P.length,skipped:f,limits:da,warnings:fa(L,k),cached:!1,expiresAt:T.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}import{writeFileSync as vS,mkdirSync as DS,existsSync as Up}from"node:fs";import{join as MS,dirname as NS,resolve as GS,sep as HS}from"node:path";import{RequestError as Ta}from"octokit";import{completeMetadata as Sa}from"@octocodeai/octocode-core";var x=new Proxy({},{get(e,t){return Sa.toolNames[t]},ownKeys(){return Object.keys(Sa.toolNames)},getOwnPropertyDescriptor(e,t){let n=Sa.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as LS}from"@octocodeai/octocode-core";var ba=new Proxy({},{get(e,t){return LS.tools[t]?.description??""}});import{completeMetadata as AS}from"@octocodeai/octocode-core";function Ca(e){return Object.prototype.hasOwnProperty.call(AS.tools,e)}import{completeMetadata as kS}from"@octocodeai/octocode-core";function xa(){return kS.baseSchema}var _S=new Proxy({},{get(e,t){return xa()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(xa())]))},getOwnPropertyDescriptor(e,t){let n=xa();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});function Pa(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 wa(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(d=>d.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(d=>d.name===s?!1:!!d.name.startsWith(p+".")).forEach(d=>u.push(d.path)),u.length===0&&p.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==p&&g.length>=3&&(p.startsWith(g)||g.startsWith(p))}).forEach(f=>u.push(f.path)),Array.from(new Set(u)).slice(0,3)}catch{return[]}}async function IS(e,t,n,r,o,i,s,a){let c=await Ae(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=V(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await wa(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Pa(i,m)]),{...l,...p&&{scopesSuggestion:p}}}async function OS(e,t,n,r,o,i){let s=V(t),a=await wa(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Pa(o,a)]),s}async function Hp(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:Ct.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:Ct.DECODE_FAILED.message,type:"unknown",status:422}}}async function Bp(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"?Hp(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return V(i)}}async function FS(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 Ae(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 p=await Bp(e,t,n,l.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return V(s)}}async function Ar(e,t,n={}){try{let r=await Q(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},u,l=a;try{u=await r.rest.repos.getContent(c)}catch(d){if(d instanceof Ta&&d.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(d instanceof Ta&&d.status===404)if(a){let f=await IS(r,d,c,o,i,s,a,t);if("result"in f)u=f.result,l=f.actualBranch;else return f}else return await OS(r,d,o,i,s,a);else{if(d instanceof Ta&&d.status===413)return await FS(r,o,i,s,a||l,t);throw d}}let p=u.data,m=xn(u.headers);if(Array.isArray(p))return{error:Ct.PATH_IS_DIRECTORY.message(x.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let d=typeof p.content=="string"?p.content:"",f=p.size??0,g;if(d.length>0)g=await Hp(d,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)g=await Bp(r,o,i,p.sha,s);else return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!l&&!a)try{l=await Ae(o,i,t)}catch{}return{data:{rawContent:g.data,branch:l||void 0,resolvedRef:l||a||"HEAD"},status:200,rawResponseChars:N(p),...m?{etag:m}:{}}}return{error:Ct.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return V(r)}}async function Ea(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=GS(MS(a,n));if(!c.startsWith(a+HS)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(!i&&u.hit&&Up(c))return{localPath:c,repoRoot:a,path:n,size:Lp(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await Ar({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}`)}wn(s),vt(a);let p=NS(c);Up(p)||DS(p,{recursive:!0,mode:448}),vS(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,d=Ln(e,t,m,"treeFetch");return Tn(a,d),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:d.expiresAt,owner:e,repo:t,branch:m}}import{ContentSanitizer as Ia}from"@octocodeai/octocode-engine/contentSanitizer";function kr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function rt(e){return kr(e).length}function mi(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(`
11
+ `),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)}}var BS=/\.(?:md|markdown|mdx)$/i;function US(e){return BS.test(e.split(/[?#]/,1)[0]??e)}function Qp(e,t){return US(t)?$S(QS(e)):null}function fi(e,t){let n=Qp(e,t);if(n===null||n.length===0)return null;let r=[];return jp(n,r),r.join(`
12
+ `)}function $p(e,t){let n=Qp(e,t);return n===null?null:n.map(zp)}function QS(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let u=s[1][0],l=s[1].length;r?r.marker===u&&l>=r.length&&(r=void 0):r={marker:u,length:l};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function $S(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n[n.length-1].level>=r.level;)n.pop();let o=n[n.length-1];o?o.children.push(r):t.push(r),n.push(r)}return t}function jp(e,t){for(let n of e){let r=String(n.line).padStart(4," "),o=" ".repeat(Math.max(0,n.level-1));t.push(`${r}| ${o}${"#".repeat(n.level)} ${n.text}`),jp(n.children,t)}}function zp(e){let t=`${"#".repeat(e.level)} ${e.text}`;return{name:t,kind:"markdownHeading",range:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},selectionRange:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},children:e.children.map(zp)}}import{getConfigSync as jS,DEFAULT_OUTPUT_CONFIG as zS}from"@octocodeai/config";function Dt(){try{return jS().output.pagination.defaultCharLength}catch{return zS.pagination.defaultCharLength}}var Wp=1e5;function LO(e){let t=Math.min(Math.max(Dt(),1),Wp),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,Wp)}function WS(e,t,n){return O.byteSliceContent(e,t,n)}function hi(e,t){return O.byteToCharOffset(e,t)}function Vp(e,t){return O.charToByteOffset(e,t)}function Kp(e){return O.charToByteOffset(e,e.length)}function _O(e,t,n){let r=WS(e,t,t+n);return{charOffset:hi(e,t),charLength:r.length,text:r}}function La(e,t,n,r){return O.sliceContent(e,t,n,r)}function gi(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Kp(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,p,m,d,f,g;if(o==="bytes"){let R=Math.min(t,s),h=Math.min(R+n,s);p=hi(e,R),m=hi(e,h),m<i&&Vp(e,m)<h&&(m+=1);let y=La(e,p,m-p);c=y.text,p=y.charOffset,m=y.charOffset+y.charLength,u=y.byteOffset,l=y.byteOffset+y.byteLength,d=l<s;let S=r.actualOffset??R;f=Math.floor(S/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let R=La(e,t,n);c=R.text,p=R.charOffset,m=R.charOffset+R.charLength,u=R.byteOffset,l=R.byteOffset+R.byteLength,d=m<i;let h=r.actualOffset??p;f=Math.floor(h/a)+1,g=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:u,byteLength:l-u,totalBytes:s,nextByteOffset:d?l:void 0,charOffset:p,charLength:c.length,totalChars:i,nextCharOffset:d?m:void 0,hasMore:d,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:g}}function FO(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function Aa(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}function vO(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
13
13
  `){let u=e.lastIndexOf(`
14
14
  `,o-1);o=u===-1?0:u+1}let i=o,s=0;for(;i<r;){let u=e.indexOf(`
15
- `,i);if(u===-1){i=r;break}if(i=u+1,s++,i-o>=n)break}let a=e.substring(o,i),c=i<r;return{sliced:a,actualOffset:o,actualLength:a.length,hasMore:c,lineCount:s,totalChars:r,nextOffset:c?i:void 0}}var QS=8e3,$S="__octocode_generic__.unknown";function jS(e){return e&&e.trim().length>0?e:$S}async function Wp(e,t){return(await O.getSemanticBoundaryOffsets(e,jS(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function zS(e,t){let n=e.indexOf(`
16
- `,t);return n===-1?void 0:n+1}function kr(e){let t=e.trimEnd().split(`
17
- `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function Ir(e,t,n){let r=zS(e,Math.max(0,t));return r===void 0?void 0:(await Wp(e,n)).find(i=>i>=r&&i>t)}async function CO(e,t,n,r,o){if(!kr(e))return;let i=await Ir(t,n,o);if(i===void 0)return;let s=i-n,a=`Page cut mid-block at char ${n}. Next top-level definition at char ${i}. Re-request with charLength=${r+s} to extend this page to the next boundary, or use charOffset=${n} to continue page-by-page.`;return{nextBlockChar:i,hint:a}}async function gi(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=await Wp(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<=QS?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function WS(){let e=Dt();return Math.min(e,8e3)}async function La(e,t,n){let r=e.content??"",o=n??WS();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await gi(r,t,o,i),c=hi(r,t,s,{pageSize:o}),u;if(c.hasMore&&a==="char-limit"&&kr(c.paginatedContent)){let l=c.charOffset+c.charLength;u=await Ir(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,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...u!==void 0&&{nextBlockChar:u}}}}async function Aa(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}function Or(e,t){return{sourceChars:e,sourceBytes:t}}async function Vp(e,t,n,r,o,i,s,a,c=5,u,l,p,m="standard"){let d=e.length,f=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",R=g?"standard":"none",h;if(m==="symbols"){let k=O.extractSignatures(e,o);if(k===null){let U=mi(e,o);if(U!==null){let ee=_a.sanitizeContent(U,o),v=[O.SIGNATURES_ONLY_HINT];return ee.hasSecrets&&v.push(`Secrets detected and redacted: ${ee.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ee.content,contentView:"symbols",branch:r,totalLines:rt(e),...Or(d,f),isPartial:!1,signaturesExtracted:!0,hints:v}}h=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(k!==null){let U=_a.sanitizeContent(k,o),ee=O.applyContentViewMinification(U.content,o),v=[O.SIGNATURES_ONLY_HINT];return u&&v.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),U.hasSecrets&&v.push(`Secrets detected and redacted: ${U.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ee,contentView:"symbols",branch:r,totalLines:rt(e),...Or(d,f),isPartial:!1,signaturesExtracted:!0,hints:v}}}let y=new Set,S=e,C=S.split(`
18
- `),P=rt(S),T=e,L,_,w=!1,b,A;if(i)T=e;else if(u){let k=p===!0,U;try{U=di(C,u,c,l??!1,k)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:P,...Or(d,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(U.matchCount===0){let ae=l?[`Regex "${u}" matched no lines. Verify the pattern, check flags (case-${k?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${u}" not found in file${k?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:P,...Or(d,f),matchNotFound:!0,searchedFor:u,hints:ae}}T=U.lines.join(`
19
- `);let ee=U.matchRanges[0],v=U.matchRanges[U.matchRanges.length-1];s=ee.start,a=v.end,L=ee.start,_=v.end,w=!0,b=U.matchRanges,A=U.matchingLines;let X=U.matchingLines.slice(0,5).join(", "),le=U.matchingLines.length>5?` and ${U.matchingLines.length-5} more`:"";y.add(U.matchCount>1?`Found ${U.matchCount} occurrences of "${u}" on lines ${X}${le} \u2014 all shown as ${U.matchRanges.length} slice${U.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${u}" on line ${U.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let k=s||1,U=a||P;if(k<1||k>P)T=e,y.add(`Requested startLine ${k} is out of range for this ${P}-line file \u2014 returning the full file instead of a range.`);else if(U<k)T=e,y.add(`Requested range startLine=${k}, endLine=${U} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let ee=Math.max(1,k),v=Math.min(P,U),X=C.slice(ee-1,v);L=ee,_=v,w=!0,T=X.join(`
20
- `),U>P&&y.add(`Requested endLine ${U} adjusted to ${P} (file end)`)}}let M=_a.sanitizeContent(T,o);if(T=g?O.applyContentViewMinification(M.content,o):M.content,M.hasSecrets&&y.add(`Secrets detected and redacted: ${M.secretsDetected.join(", ")}`),M.warnings.length>0&&M.warnings.forEach(k=>y.add(k)),P>2e3&&m!=="symbols"&&!u&&!s&&!a&&!i){let k=Math.max(1,P-200);y.add(`Large file (${P} lines) \u2014 minify:"symbols" for an export index, or startLine=${k} for the tail.`)}let B=Array.from(y);return{owner:t,repo:n,path:o,content:T,contentView:R,branch:r,totalLines:P,...Or(d,f),...w&&{startLine:L,endLine:_,isPartial:w},...b&&{matchRanges:b},...A&&{matchedLines:A},...B.length>0&&{matchLocations:B},...(B.length>0||h)&&{warnings:[...h?[h]:[],...B]}}}async function Kp(e,t,n){let r=await fe(t),o=ce("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await si(o,async({ifNoneMatch:g})=>{let R=await Ar(e,t,{ifNoneMatch:g}),{etag:h,notModified:y,...S}=R;return{value:S,etag:h,notModified:y}},{shouldCache:g=>"data"in g&&!g.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await Vp(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...u}=a,l=e.charOffset??0,p=e.charLength,m=e.fullContent===!0&&l===0&&p===void 0,d=c||m?u:await La(u,l,p),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let g=await Q(t),R=await he(ce("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>Aa(g,e.owner,e.repo,e.path,e.branch),{shouldCache:h=>h!==null,forceRefresh:e.forceRefresh===!0});R&&(d.lastModified=R.lastModified,d.lastModifiedBy=R.lastModifiedBy)}catch{}return{data:d,status:200,rawResponseChars:i.rawResponseChars}}import{ContentSanitizer as qp}from"@octocodeai/octocode-engine/contentSanitizer";var VS=2,KS=20;function QO(e,t=KS){let n=e?_r(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Yp(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 Xp(e){return e?O.filterPatch(e,{trimContext:!0,contextLines:VS}):""}function ka(e){let t=qp.sanitizeContent(e.title??""),n=e.body?qp.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 YS=Dt(),XS=Math.round(Dt()/4),Jp=3;function Zp(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 An(e,t={}){let n=t.charOffset??0,r=t.charLength??YS,o=t.charLength??XS,i=typeof e.body=="string"?O.minifyMarkdownCore(e.body):e.body,s=Zp(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,g)=>{let R=f.commentType==="review_inline"?0:1,h=g.commentType==="review_inline"?0:1;return R-h}),c=a.filter(f=>f.commentType==="review_inline").length,u=a.length-c,l=t.includeFullCommentDetails?a:a.slice(0,Jp),p=l.map(f=>{let g=Zp(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:g.value??"",...g.pagination?{bodyPagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>l.length||p.some(f=>"bodyPagination"in f)),d=[...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 ${Jp} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??void 0,mergedAt:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(f=>({id:0,name:f,color:""}))}:{},headRef:e.head||"",...e.head_sha?{headSha:e.head_sha}:{},baseRef:e.base||"",...e.base_sha?{baseSha:e.base_sha}:{},body:s.value,...s.pagination?{bodyPagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{commentDetailsBreakdown:{inlineReview:c,discussion: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,changedFiles:e.file_changes?.total_count||0,...e.file_changes&&{fileChanges:e.file_changes.files?.map(f=>({filename:f.filename,status:f.status,additions:f.additions,deletions:f.deletions,patch:f.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commitDetails:e.commits},...p.length>0&&{commentDetails:p,commentDetailsShown:p.length,commentDetailsTotal:a.length,...m?{commentDetailsPaginated:!0}:{}},...(e._sanitization_warnings||d.length>0)&&{sanitizationWarnings:[...e._sanitization_warnings||[],...d]}}}function Fr(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 vr(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?Yp(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?Xp(a.patch):a.patch}))}function _n(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function ed(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function yi(e){let t=ed(e);return t?t.discussion!==!1:!1}function Ri(e){let t=ed(e);return t?t.reviewInline!==!1:!1}function Si(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function bi(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Ia(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:_n(e)||yi(e)||Ri(e)||Si(e)||bi(e)}function Oa(e){return!!e.content?.comments?.includeBots}function Ci(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
15
+ `,i);if(u===-1){i=r;break}if(i=u+1,s++,i-o>=n)break}let a=e.substring(o,i),c=i<r;return{sliced:a,actualOffset:o,actualLength:a.length,hasMore:c,lineCount:s,totalChars:r,nextOffset:c?i:void 0}}var VS=8e3,KS="__octocode_generic__.unknown";function YS(e){return e&&e.trim().length>0?e:KS}async function Yp(e,t){return(await O.getSemanticBoundaryOffsets(e,YS(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function XS(e,t){let n=e.indexOf(`
16
+ `,t);return n===-1?void 0:n+1}function _r(e){let t=e.trimEnd().split(`
17
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function Ir(e,t,n){let r=XS(e,Math.max(0,t));return r===void 0?void 0:(await Yp(e,n)).find(i=>i>=r&&i>t)}async function NO(e,t,n,r,o){if(!_r(e))return;let i=await Ir(t,n,o);if(i===void 0)return;let s=i-n,a=`Page cut mid-block at char ${n}. Next top-level definition at char ${i}. Re-request with charLength=${r+s} to extend this page to the next boundary, or use charOffset=${n} to continue page-by-page.`;return{nextBlockChar:i,hint:a}}async function yi(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=await Yp(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<=VS?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function qS(){let e=Dt();return Math.min(e,8e3)}async function ka(e,t,n){let r=e.content??"",o=n??qS();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await yi(r,t,o,i),c=gi(r,t,s,{pageSize:o}),u;if(c.hasMore&&a==="char-limit"&&_r(c.paginatedContent)){let l=c.charOffset+c.charLength;u=await Ir(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,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...u!==void 0&&{nextBlockChar:u}}}}async function _a(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}function Or(e,t){return{sourceChars:e,sourceBytes:t}}async function Xp(e,t,n,r,o,i,s,a,c=5,u,l,p,m="standard"){let d=e.length,f=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",R=g?"standard":"none",h;if(m==="symbols"){let I=O.extractSignatures(e,o);if(I===null){let U=fi(e,o);if(U!==null){let ee=Ia.sanitizeContent(U,o),v=[O.SIGNATURES_ONLY_HINT];return ee.hasSecrets&&v.push(`Secrets detected and redacted: ${ee.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ee.content,contentView:"symbols",branch:r,totalLines:rt(e),...Or(d,f),isPartial:!1,signaturesExtracted:!0,hints:v}}h=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(I!==null){let U=Ia.sanitizeContent(I,o),ee=O.applyContentViewMinification(U.content,o),v=[O.SIGNATURES_ONLY_HINT];return u&&v.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),U.hasSecrets&&v.push(`Secrets detected and redacted: ${U.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ee,contentView:"symbols",branch:r,totalLines:rt(e),...Or(d,f),isPartial:!1,signaturesExtracted:!0,hints:v}}}let y=new Set,S=e,C=S.split(`
18
+ `),P=rt(S),T=e,L,k,w=!1,b,A;if(i)T=e;else if(u){let I=p===!0,U;try{U=mi(C,u,c,l??!1,I)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:P,...Or(d,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(U.matchCount===0){let ae=l?[`Regex "${u}" matched no lines. Verify the pattern, check flags (case-${I?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${u}" not found in file${I?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:P,...Or(d,f),matchNotFound:!0,searchedFor:u,hints:ae}}T=U.lines.join(`
19
+ `);let ee=U.matchRanges[0],v=U.matchRanges[U.matchRanges.length-1];s=ee.start,a=v.end,L=ee.start,k=v.end,w=!0,b=U.matchRanges,A=U.matchingLines;let q=U.matchingLines.slice(0,5).join(", "),le=U.matchingLines.length>5?` and ${U.matchingLines.length-5} more`:"";y.add(U.matchCount>1?`Found ${U.matchCount} occurrences of "${u}" on lines ${q}${le} \u2014 all shown as ${U.matchRanges.length} slice${U.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${u}" on line ${U.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let I=s||1,U=a||P;if(I<1||I>P)T=e,y.add(`Requested startLine ${I} is out of range for this ${P}-line file \u2014 returning the full file instead of a range.`);else if(U<I)T=e,y.add(`Requested range startLine=${I}, endLine=${U} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let ee=Math.max(1,I),v=Math.min(P,U),q=C.slice(ee-1,v);L=ee,k=v,w=!0,T=q.join(`
20
+ `),U>P&&y.add(`Requested endLine ${U} adjusted to ${P} (file end)`)}}let M=Ia.sanitizeContent(T,o);if(T=g?O.applyContentViewMinification(M.content,o):M.content,M.hasSecrets&&y.add(`Secrets detected and redacted: ${M.secretsDetected.join(", ")}`),M.warnings.length>0&&M.warnings.forEach(I=>y.add(I)),P>2e3&&m!=="symbols"&&!u&&!s&&!a&&!i){let I=Math.max(1,P-200);y.add(`Large file (${P} lines) \u2014 minify:"symbols" for an export index, or startLine=${I} for the tail.`)}let B=Array.from(y);return{owner:t,repo:n,path:o,content:T,contentView:R,branch:r,totalLines:P,...Or(d,f),...w&&{startLine:L,endLine:k,isPartial:w},...b&&{matchRanges:b},...A&&{matchedLines:A},...B.length>0&&{matchLocations:B},...(B.length>0||h)&&{warnings:[...h?[h]:[],...B]}}}async function qp(e,t,n){let r=await fe(t),o=ce("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await ai(o,async({ifNoneMatch:g})=>{let R=await Ar(e,t,{ifNoneMatch:g}),{etag:h,notModified:y,...S}=R;return{value:S,etag:h,notModified:y}},{shouldCache:g=>"data"in g&&!g.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await Xp(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...u}=a,l=e.charOffset??0,p=e.charLength,m=e.fullContent===!0&&l===0&&p===void 0,d=c||m?u:await ka(u,l,p),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let g=await Q(t),R=await he(ce("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>_a(g,e.owner,e.repo,e.path,e.branch),{shouldCache:h=>h!==null,forceRefresh:e.forceRefresh===!0});R&&(d.lastModified=R.lastModified,d.lastModifiedBy=R.lastModifiedBy)}catch{}return{data:d,status:200,rawResponseChars:i.rawResponseChars}}import{ContentSanitizer as ed}from"@octocodeai/octocode-engine/contentSanitizer";var JS=2,ZS=20;function oF(e,t=ZS){let n=e?kr(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Jp(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 Zp(e){return e?O.filterPatch(e,{trimContext:!0,contextLines:JS}):""}function Oa(e){let t=ed.sanitizeContent(e.title??""),n=e.body?ed.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 eb=Dt(),tb=Math.round(Dt()/4),td=3;function nd(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 An(e,t={}){let n=t.charOffset??0,r=t.charLength??eb,o=t.charLength??tb,i=typeof e.body=="string"?O.minifyMarkdownCore(e.body):e.body,s=nd(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,g)=>{let R=f.commentType==="review_inline"?0:1,h=g.commentType==="review_inline"?0:1;return R-h}),c=a.filter(f=>f.commentType==="review_inline").length,u=a.length-c,l=t.includeFullCommentDetails?a:a.slice(0,td),p=l.map(f=>{let g=nd(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:g.value??"",...g.pagination?{bodyPagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>l.length||p.some(f=>"bodyPagination"in f)),d=[...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 ${td} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??void 0,mergedAt:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(f=>({id:0,name:f,color:""}))}:{},headRef:e.head||"",...e.head_sha?{headSha:e.head_sha}:{},baseRef:e.base||"",...e.base_sha?{baseSha:e.base_sha}:{},body:s.value,...s.pagination?{bodyPagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{commentDetailsBreakdown:{inlineReview:c,discussion: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,changedFiles:e.file_changes?.total_count||0,...e.file_changes&&{fileChanges:e.file_changes.files?.map(f=>({filename:f.filename,status:f.status,additions:f.additions,deletions:f.deletions,patch:f.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commitDetails:e.commits},...p.length>0&&{commentDetails:p,commentDetailsShown:p.length,commentDetailsTotal:a.length,...m?{commentDetailsPaginated:!0}:{}},...(e._sanitization_warnings||d.length>0)&&{sanitizationWarnings:[...e._sanitization_warnings||[],...d]}}}function Fr(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 vr(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?Jp(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?Zp(a.patch):a.patch}))}function kn(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function rd(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Ri(e){let t=rd(e);return t?t.discussion!==!1:!1}function Si(e){let t=rd(e);return t?t.reviewInline!==!1:!1}function bi(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function Ci(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Fa(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:kn(e)||Ri(e)||Si(e)||bi(e)||Ci(e)}function va(e){return!!e.content?.comments?.includeBots}function xi(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
21
21
 
22
- `).trim()}import{ContentSanitizer as Da}from"@octocodeai/octocode-engine/contentSanitizer";var qS=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function qt(e){let t=e.toLowerCase();return t.endsWith("[bot]")||qS.has(t)}async function xi(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=N(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Fa(e,t,n,r){let o=await Q(r),{items:i,rawResponseChars:s}=await xi(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $({total_count:i.length,files:i},s)}async function JS(e,t,n,r){let o=await Q(r),{items:i,rawResponseChars:s}=await xi(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $(i,s)}async function ZS(e,t,n,r){try{let i=await(await Q(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return $(i.data.files||[],i.data)}catch{return null}}var eb=5;async function tb(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)break;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function va(e,t,n,r,o){let i=await JS(e,t,n,o);if(!i)return null;let s=ne(i)??0,a=[...i].sort((u,l)=>{let p=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)-p}),c=await tb(a,eb,async u=>{let l=await ZS(e,t,u.sha,o),p=[];return l&&(s+=ne(l)??0,p=vr(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:p}});return $(c,s)}async function Ma(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let d=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=N(d.data),i.push(...d.data),c=d.data.length===100,a++}while(c);let u=o?i:i.filter(d=>!qt(d.user?.login??"")),l=i.length-u.length,p=u.map(d=>{let f=O.minifyMarkdownCore(Ci(d.body??""));return{id:String(d.id),user:d.user?.login??"unknown",body:Da.sanitizeContent(f).content,createdAt:d.created_at??"",updatedAt:d.updated_at??"",commentType:"discussion"}}),m=[];return l>0&&m.push(`${l} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(p,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Na(e,t,n,r){try{let{items:o,rawResponseChars:i}=await xi(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return $(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Da.sanitizeContent(O.minifyMarkdownCore(Ci(s.body??""))).content,submittedAt:s.submitted_at??void 0,commitId:s.commit_id??void 0})),i)}catch{return $([],0)}}async function Ga(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let d=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=N(d.data),i.push(...d.data),c=d.data.length===100,a++}while(c);let u=o?i:i.filter(d=>!qt(d.user?.login??"")),l=i.length-u.length,p=u.map(d=>{let f=O.minifyMarkdownCore(Ci(d.body??""));return{id:String(d.id),user:d.user?.login??"unknown",body:Da.sanitizeContent(f).content,createdAt:d.created_at??"",updatedAt:d.updated_at??"",commentType:"review_inline",path:d.path,line:d.line??d.original_line??void 0,...d.in_reply_to_id!=null?{inReplyToId:d.in_reply_to_id}:{}}}),m=[];return l>0&&m.push(`${l} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(p,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Ha(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=ka(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&Ia(t))try{let{owner:u,repo:l}=Fr(t);if(u&&l){let p=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(p.data&&(s+=N(p.data),o.head=p.data.head?.ref,o.head_sha=p.data.head?.sha,o.base=p.data.base?.ref,o.base_sha=p.data.base?.sha,o.draft=p.data.draft??!1,p.data.merged_at&&(o.merged_at=p.data.merged_at),o.additions=p.data.additions??0,o.deletions=p.data.deletions??0,_n(t)||(o.file_changes={total_count:p.data.changed_files??0,files:[]}),_n(t))){let m=await Fa(u,l,e.number);m&&(s+=ne(m)??0,m.files=vr(m.files,t),o.file_changes=m)}}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let a=yi(t),c=Ri(t);if(a||c){let{owner:u,repo:l}=Fr(t);if(u&&l){let p=Oa(t),m=()=>Promise.resolve({comments:$([],0)}),[{comments:d,note:f},{comments:g,note:R}]=await Promise.all([a?Ma(n,u,l,e.number,p):m(),c?Ga(n,u,l,e.number,p):m()]);o.comments=[...d,...g],s+=(ne(d)??0)+(ne(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}}if(bi(t))try{let{owner:u,repo:l}=Fr(t);if(u&&l){let p=await Na(n,u,l,e.number);s+=ne(p)??0,o.reviews=p}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(Si(t))try{let{owner:u,repo:l}=Fr(t);if(u&&l){let p=await va(u,l,e.number,t);p&&(s+=ne(p)??0,o.commits=p)}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return $(o,s)}async function Dr(e,t,n,r){let{prData:o,sanitizationWarnings:i}=ka(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,_n(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),_n(t))try{let p=await Fa(a,c,e.number,r);p&&(s+=ne(p)??0,p.files=vr(p.files,t),o.file_changes=p)}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${p instanceof Error?p.message:String(p)}`]}let u=yi(t),l=Ri(t);if(u||l){let p=Oa(t),m=()=>Promise.resolve({comments:$([],0)}),[{comments:d,note:f},{comments:g,note:R}]=await Promise.all([u?Ma(n,a,c,e.number,p):m(),l?Ga(n,a,c,e.number,p):m()]);o.comments=[...d,...g],s+=(ne(d)??0)+(ne(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}if(bi(t))try{let p=await Na(n,a,c,e.number);s+=ne(p)??0,o.reviews=p}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${p instanceof Error?p.message:String(p)}`]}if(Si(t))try{let p=await va(a,c,e.number,t,r);p&&(s+=ne(p)??0,o.commits=p)}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${p instanceof Error?p.message:String(p)}`]}return $(o,s)}function nb(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function wF(e,t,n){let r=await fe(t),o=ce("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode,auth:r},n);return await he(o,async()=>await Ba(e,t),{shouldCache:s=>!s.error})}async function Ba(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pullRequests:[],totalCount:0,error:Ee.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pullRequests:[],totalCount:0,error:Ee.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await Q(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Dr(a,e,i,t);return{pullRequests:[An(c,{includeFullBody:!0,includeFullCommentDetails:!0})],totalCount:1,rawResponseChars:N(s.data)+(ne(c)??0)}}catch(i){let s=V(i);return nb(s,Ee.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 Ua(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Qa(e){let t=Math.min(e.limit||30,100);return{pullRequests:[],totalCount:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function td(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 Dr(m,t,e))),c=a.reduce((m,d)=>m+(ne(d)??0),0),u=a.map(m=>An(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),l=s.data.length===o,p=(i-1)*o+u.length;return{pullRequests:u,totalCount:u.length,pagination:{currentPage:i,totalPages:l?i+1:i,perPage:o,totalMatches:p+(l?1:0),reachableTotalMatches:p,totalMatchesKind:l?"lowerBound":"exact",hasMore:l,...l?{nextPage:i+1}:{}},rawResponseChars:N(s.data)+c}}catch(n){if(nt(n))return Qa(t);let r=V(n);return Ua(r,Ee.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}async function rb(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function ob(e,t,n="anon"){return ce("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,project:e.project,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function nd(e,t,n){let r=await fe(t),o=ob(e,n,r);return await he(o,async()=>await ib(e,t,n),{shouldCache:s=>!s.error})}async function ib(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Ba(e,t);let r=await Q(t);if(!oa(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await td(r,e);let i=await rb(r,e),s=ra(i);if(!s)return{pullRequests:[],totalCount:0,error:Ee.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),u=i.page||1,l=s,p=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:u}),m=p.data.items?.filter(T=>!!T.pull_request)||[],d=await Promise.all(m.map(async T=>await Ha(T,i,r))),f=d.reduce((T,L)=>T+(ne(L)??0),0),g=d.map(T=>An(T,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),R=p.data.total_count,h=Math.min(R,1e3),y=Math.min(Math.ceil(h/c),10),S=Math.min(u,Math.max(1,y)),C=S<y,P=Math.min(h,y*c);return{pullRequests:g,totalCount:p.data.total_count,effectiveQuery:l,...p.data.incomplete_results&&{incompleteResults:!0},pagination:{currentPage:S,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:R,reachableTotalMatches:P,totalMatchesKind:"reported",totalMatchesCapped:R>h,hasMore:C,...C?{nextPage:S+1}:{}},rawResponseChars:N(p.data)+f}}catch(r){if(nt(r))return Qa(e);let o=V(r);return Ua(o,Ee.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var sb=/^(\d+)\s*([hdwmy])$/i;function $a(e){let t=e.trim(),n=sb.exec(t);if(n){let r=Number(n[1]),o=n[2].toLowerCase(),i=new Date;switch(o){case"h":i.setUTCHours(i.getUTCHours()-r);break;case"d":i.setUTCDate(i.getUTCDate()-r);break;case"w":i.setUTCDate(i.getUTCDate()-r*7);break;case"m":i.setUTCMonth(i.getUTCMonth()-r);break;case"y":i.setUTCFullYear(i.getUTCFullYear()-r);break}return{value:i.toISOString()}}return Number.isNaN(Date.parse(t))?{warning:`"${e}" is not a valid date or relative window \u2014 use e.g. "30d", "2w", "6m", "1y", or an ISO date like "2026-01-01". Filter skipped.`}:{value:t}}function ja(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function za(e,t){let n=e.map(l=>{let p=l.patch!==void 0?ja(l.patch,t.charOffset,t.charLength):void 0;return{filename:l.filename,status:l.status,additions:l.additions,deletions:l.deletions,...p!==void 0?{patch:p.patch,...p.patchPagination?{patchPagination:p.patchPagination}:{}}:{},...l.previous_filename?{previousFilename:l.previous_filename}:{}}}),r=Math.max(1,t.filePage??1),o=Math.max(1,t.itemsPerPage??20),i=n.length,s=Math.max(1,Math.ceil(i/o)),a=Math.min(r,s),c=(a-1)*o;return{files:n.slice(c,c+o),filesPagination:{currentPage:a,totalPages:s,itemsPerPage:o,totalFiles:i,hasMore:a<s,...a<s?{nextFilePage:a+1}:{}}}}var ab=5;function kn(e){return e?e.includes('rel="next"'):!1}async function cb(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function rd(e,t,n){let r=await fe(t),o=ce("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,committer:e.committer,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return he(o,()=>ub(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function ub(e,t){try{let n=await Q(t),r=[],o=e.since?$a(e.since):void 0,i=e.until?$a(e.until):void 0;o?.warning&&r.push(`since ${o.warning}`),i?.warning&&r.push(`until ${i.warning}`);let s={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...o?.value?{since:o.value}:{},...i?.value?{until:i.value}:{},...e.author?{author:e.author}:{},...e.committer?{committer:e.committer}:{}},a=await n.rest.repos.listCommits(s),c=a.headers.link,u=kn(c),l=a.data.map(h=>{let y=h.commit.author,S=h.commit.committer,C=S?.date??y?.date??"",P=h.commit.message,T=P.split(`
23
- `)[0]??P,L=P.slice(T.length).trim(),_=L.length>500,w=L.length===0?T:`${T}
24
- ${_?`${L.slice(0,500)}\u2026`:L}`,b=S?.name===y?.name&&S?.email===y?.email||h.committer?.login==="web-flow";return{sha:h.sha,date:C,...w===T?{}:{message:w},..._?{messageTruncated:!0}:{},messageHeadline:T,author:{name:y?.name??"unknown",email:y?.email??"",...h.author?.login?{login:h.author.login}:{}},...S&&!b?{committer:{name:S.name??"unknown",email:S.email??"",...h.committer?.login?{login:h.committer.login}:{}}}:{}}});l.length===0&&(o?.value!==void 0||i?.value!==void 0)&&r.push("no commits matched the since/until window \u2014 GitHub filters by committer date (not author date; rebases and squash-merges reset it), and a path-scoped walk does not follow renames. Widen or drop since/until and inspect commit dates directly.");let p={currentPage:e.page,perPage:e.perPage,hasMore:u,...u?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:p,...r.length?{warnings:r}:{}},status:200};let m=!1,d=!1,f=await cb(l,ab,async(h,y)=>{try{let S=a.data[y]?.sha??h.sha,C=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:S});if(e.type==="file"&&e.path){let P=e.path,T=C.data.files?.find(w=>w.filename===P||w.previous_filename===P);if(T){let w=T.patch!==void 0?ja(T.patch,e.charOffset,e.charLength):void 0;return{...h,additions:T.additions,deletions:T.deletions,status:T.status,...w!==void 0?{patch:w.patch,...w.patchPagination?{patchPagination:w.patchPagination}:{}}:{},...T.previous_filename?{previousFilename:T.previous_filename}:{}}}let L=P.endsWith("/")?P:`${P}/`,_=(C.data.files??[]).filter(w=>w.filename.startsWith(L));return _.length>0?(m=!0,{...h,...za(_,e)}):(d=!0,h)}else{let P=e.path,T=(C.data.files??[]).filter(L=>!P||L.filename.startsWith(P));return{...h,...za(T,e)}}}catch{}return h}),g=[];m&&g.push(`path '${e.path}' matched no single file in these commits but matches files under it \u2014 treated as a directory filter and returned per-commit changed files (append '/' to select directory mode explicitly).`),d&&g.push(`includeDiff: some commits contain no file matching '${e.path}' (rename or shallow diff?) \u2014 those commits are listed without a diff.`);let R=[...r,...g];return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:f,pagination:p,...R.length?{warnings:R}:{}},status:200}}catch(n){return V(n)}}var od=30;function id(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 sd(e,t,n){let r=await fe(t),o=e,i=ce("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await he(i,async()=>await pb(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function lb(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(d){if(d?.status!==404)return V(d);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return V(g)}}let a=i.map(d=>{let g=d.full_name.split("/"),R=g[0]||"",h=g[1]||"";return{owner:R,repo:h,defaultBranch:d.default_branch,stars:d.stargazers_count||0,description:d.description?d.description:"No description",url:d.html_url,createdAt:d.created_at,updatedAt:d.updated_at,pushedAt:d.pushed_at,visibility:d.visibility,...d.topics&&d.topics.length>0&&{topics:d.topics},...d.forks_count&&d.forks_count>0&&{forksCount:d.forks_count},...d.open_issues_count&&d.open_issues_count>0&&{openIssuesCount:d.open_issues_count},...d.language&&{language:d.language},...id(d)}}),c=a.length,u=c===n,l=(r-1)*n+c,p=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:p,reachableTotalMatches:l,totalMatchesKind:m,hasMore:u,...u?{nextPage:r+1}:{}}},status:200,rawResponseChars:N(i)}}async function pb(e,t){try{let n=await Q(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 lb({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=ta(e);if(!i.trim())return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||od,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),p=l.data.items.map(y=>{let C=y.full_name.split("/"),P=C[0]||"",T=C[1]||"";return{owner:P,repo:T,defaultBranch:y.default_branch,stars:y.stargazers_count||0,description:y.description?y.description:"No description",url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at,pushedAt:y.pushed_at,visibility:y.visibility,...y.topics&&y.topics.length>0&&{topics:y.topics},...y.forks_count&&y.forks_count>0&&{forksCount:y.forks_count},...y.open_issues_count&&y.open_issues_count>0&&{openIssuesCount:y.open_issues_count},...y.language&&{language:y.language},...id(y)}}),m=l.data.total_count,d=Math.min(m,1e3),f=Math.min(Math.ceil(d/s),10),g=Math.min(a,Math.max(1,f)),R=g<f,h=Math.min(d,f*s);return{data:{repositories:p,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:d,reportedTotalMatches:m,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:m>d,hasMore:R,...R?{nextPage:g+1}:{}}},status:200,headers:Cn(l.headers),rawResponseChars:N(l.data)}}catch(n){if(nt(n)){let r=Math.min(e.limit||od,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 V(n)}}var Mt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function db(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 mb(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 lv(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...db(e.estimatedTokens,n)),o.push(...mb(e)),o}function Pi(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function ad(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:w,...b}=e;return b}let r=t.itemsPerPage??Mt.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),p=e.path==="/"?"":e.path,m=w=>{let b=w;p&&w.startsWith(p)&&(b=w.slice(p.length),b.startsWith("/")&&(b=b.slice(1)));let A=b.lastIndexOf("/");return A===-1?".":b.slice(0,A)},d=w=>{let b=w.lastIndexOf("/");return b===-1?w:w.slice(b+1)};for(let w of u){let b=m(w.path);l[b]||(l[b]={files:[],folders:[]});let A=d(w.path);w.type==="file"?l[b].files.push(A):l[b].folders.push(A)}for(let w of Object.keys(l)){let b=l[w];b&&(b.files.sort(),b.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((w,b)=>w==="."?-1:b==="."?1:w.localeCompare(b));for(let w of g){let b=l[w];b&&(f[w]=b)}let R=u.filter(w=>w.type==="file").length,h=u.filter(w=>w.type==="dir").length,y=n.filter(w=>w.type==="file").length,S=n.filter(w=>w.type==="dir").length,C=o<s,P={currentPage:o,totalPages:s,hasMore:C,...C?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},T=Pi(P,{owner:e.owner,repo:e.repo,branch:e.branch,path:p,depth:t.maxDepth??1,pageFiles:R,pageFolders:h,allFiles:y,allFolders:S}),L,_=e._cachedFileSizeMap;if(_){let w=new Set(u.filter(M=>M.type==="file").map(M=>M.path)),b=e.path==="/"?"":e.path,A=Object.create(null);for(let[M,B]of Object.entries(_))for(let[k,U]of Object.entries(B)){let ee=M==="."?b?`${b}/${k}`:k:b?`${b}/${M}/${k}`:`${M}/${k}`;w.has(ee)&&(A[M]||(A[M]=Object.create(null)),A[M][k]=U)}Object.keys(A).length>0&&(L=A)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:y,totalFolders:S,truncated:C,filtered:!0,originalCount:i},structure:f,...L!==void 0&&{fileSizeMap:L},..._!==void 0&&{_cachedFileSizeMap:_},pagination:P,hints:T,rawResponseChars:e.rawResponseChars}}import{RequestError as fb}from"octokit";var ud=Symbol.for("octocode.recursiveFetchFailures"),hb=new Set([401,403,429]);function cd(e){return e instanceof fb&&hb.has(e.status)}function Wa(e,t){try{Object.defineProperty(e,ud,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Mr(e){if(typeof e!="object"||e===null)return 0;let t=e[ud];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Nr(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Wa($([],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(cd(f))throw f;return Wa($([],0),1)}let u=N(c.data),p=(Array.isArray(c.data)?c.data:[c.data]).filter(f=>f.type==="file"||f.type==="dir").map(f=>({name:f.name,path:f.path,type:f.type,size:"size"in f?f.size:void 0,download_url:"download_url"in f?f.download_url:void 0,url:f.url,html_url:f.html_url,git_url:f.git_url,sha:f.sha})),m=[...p],d=0;if(i<s){let f=p.filter(R=>R.type==="dir"),g=3;for(let R=0;R<f.length;R+=g){let h=f.slice(R,R+g),y=await Promise.allSettled(h.map(S=>Nr(e,t,n,r,S.path,i+1,s,a)));for(let S of y)if(S.status==="fulfilled"){let C=S.value;u+=ne(C)??0,d+=Mr(C),m.push(...C)}else{if(cd(S.reason))throw S.reason;d+=1}}}return Wa($(m,u),d)}import{RequestError as gb}from"octokit";function yb(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let u=a.lastIndexOf("/"),l=u===-1?a:a.slice(u+1);i.push({name:l,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function ld(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function pd(e,t){let{data:n}=await e.rest.repos.getBranch({owner:t.owner,repo:t.repo,branch:t.workingBranch}),r=n.commit.commit.tree.sha;if(!r)throw new Error(`Could not resolve tree SHA for ${t.owner}/${t.repo}@${t.workingBranch}`);let o;try{o=await e.rest.git.getTree({owner:t.owner,repo:t.repo,tree_sha:r,recursive:"true",...t.ifNoneMatch?{headers:{"If-None-Match":t.ifNoneMatch}}:{}})}catch(c){if(c instanceof gb&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=xn(o.headers);return{items:yb(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:N(n)+N(i),...s?{etag:s}:{}}}import{RequestError as dd}from"octokit";async function Va(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Ae(t,n,i),a=c)}catch(u){let l=V(u);return{error:xt.NOT_FOUND.message(t,n,l.error),status:l.status}}try{let u=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),l=xn(u.headers);return{data:u.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...l?{etag:l}:{}}}catch(u){if(u instanceof dd&&u.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(u instanceof dd&&u.status===404)){let p=V(u);return{error:xt.ACCESS_FAILED.message(t,n,p.error),status:p.status,rateLimitRemaining:p.rateLimitRemaining,rateLimitReset:p.rateLimitReset,retryAfter:p.retryAfter}}let l=V(u);return{error:xt.PATH_NOT_FOUND.message(r,t,n,a),status:l.status}}}function md(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 Rb(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 fd(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}function wi(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:u,includeSizes:l,extraHints:p=[]}=e,m=e.allItems.filter(k=>k.type==="dir"?!Cr(k.name):!bn(k.path));m.sort((k,U)=>{if(k.type!==U.type)return k.type==="dir"?-1:1;let ee=k.path.split("/").length,v=U.path.split("/").length;return ee!==v?ee-v:k.path.localeCompare(U.path)});let d=e.itemsPerPage??Mt.ENTRIES_PER_PAGE,f=e.page??1,g=m.length,R=Math.max(1,Math.ceil(g/d)),h=(f-1)*d,y=Math.min(h+d,g),S=m.slice(h,y),C=Rb(S,i),P=l?fd(m,i):void 0,T=P!==void 0?fd(S,i):void 0,L=S.filter(k=>k.type==="file").length,_=S.filter(k=>k.type==="dir").length,w=m.filter(k=>k.type==="file").length,b=m.filter(k=>k.type==="dir").length,A=f<R,M={currentPage:f,totalPages:R,hasMore:A,...A?{nextPage:f+1}:{},entriesPerPage:d,totalEntries:g},B=Pi(M,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:L,pageFolders:_,allFiles:w,allFolders:b});a>0&&B.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let k of p)B.unshift(k);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:w,totalFolders:b,truncated:A,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:C,...T!==void 0&&{fileSizeMap:T},...P!==void 0&&{_cachedFileSizeMap:P},pagination:M,hints:B,rawResponseChars:u,_cachedItems:m.map(k=>({path:k.path,type:k.type}))}}async function Ka(e,t,n){let r=await fe(t),o=ce("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await si(o,async({ifNoneMatch:s})=>{let a=await Sb({...e,itemsPerPage:e.itemsPerPage??Mt.ENTRIES_PER_PAGE,page:e.page??1},t,s);return{value:a.result,etag:a.etag,notModified:a.notModified}},{shouldCache:s=>!("error"in s)});return!("error"in i)&&i.structure?ad(i,e):i}async function Sb(e,t,n){try{let r=await Q(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,u=a.replace(/^\/+|\/+$/g,"");if(c>1&&ld())return await bb(r,e,u,c,t,n);let l=await Va(r,o,i,u,s,t,c===1?n:void 0);if("error"in l)return{result:l};if(l.notModified)return{result:{error:"not-modified",status:304},etag:l.etag??n,notModified:!0};let{data:p,workingBranch:m,repoDefaultBranch:d,etag:f}=l,g=N(p),R=Array.isArray(p)?p:[p],h=md(R),y=0;if(c>1){let S=await Nr(r,o,i,m,u,1,c);y=Mr(S),g=ne(S)??0,h=S}return{result:wi({owner:o,repo:i,workingBranch:m,repoDefaultBranch:d,cleanPath:u,depth:c,allItems:h,partialTreeFailures:y,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&f?{etag:f}:{}}}catch(r){let o=V(r);return{result:{error:xt.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function bb(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,u,l;try{c?u=c:(l=await Ae(s,a,o),u=l)}catch(h){let y=V(h);return{result:{error:xt.NOT_FOUND.message(s,a,y.error),status:y.status}}}let p;try{p=await pd(e,{owner:s,repo:a,workingBranch:u,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(h){let y=await Va(e,s,a,n,u,o);if("error"in y)return{result:y};let S=await Nr(e,s,a,y.workingBranch,n,1,r);return{result:wi({owner:s,repo:a,workingBranch:y.workingBranch,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:S,partialTreeFailures:Mr(S),incompleteTree:!1,rawResponseChars:ne(S)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${h instanceof Error?h.message:String(h)}); used Contents recursion instead.`]})}}if(p.notModified)return{result:{error:"not-modified",status:304},etag:p.etag??i,notModified:!0};let m=p.items,d=0,f=p.rawResponseChars,g=p.truncated,R=[];if(g){R.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let h=await Nr(e,s,a,u,n,1,r);d=Mr(h),f+=ne(h)??0,m=[...m,...h].filter((S,C,P)=>P.findIndex(T=>T.path===S.path)===C)}catch{}}return{result:wi({owner:s,repo:a,workingBranch:u,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:m,partialTreeFailures:d,incompleteTree:g,rawResponseChars:f,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:R}),...p.etag&&!g?{etag:p.etag}:{}}}var hd={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};function Oe(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function Cb(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function xb(e){return!!(e&&typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"full_name"in e&&typeof e.full_name=="string"&&"private"in e&&typeof e.private=="boolean")}function Re(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 Pb(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 mt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:Pb(e)}}function Ti(e){return wb(e)?mt({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 wb(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||Tb(n)}function Tb(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Gr(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Eb(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,...Gr(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function Lb(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,...Gr(e.pagination)},nonExistentScope:e.nonExistentScope}}async function gd(e,t,n=Re){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 yp(s,t);return Oe(a)?mt(a):a.data?{data:Eb(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function yd(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 sd(n,t);return"error"in r?Ti(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:Lb(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??N(r.data)}}function _b(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,matchedLines:e.matchedLines,warnings:kb(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function kb(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 Rd(e,t,n=Re){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 Kp(i,t);if(Oe(s))return mt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:_b(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s.data),...a?.length?{hints:a}:{}}}function Ob(e,t,n=Re){let r=(e.pullRequests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.bodyPagination&&{bodyPagination:a.bodyPagination},state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.headRef||"",targetBranch:a.baseRef||"",sourceSha:a.headSha,targetSha:a.baseSha,createdAt:a.createdAt,updatedAt:a.updatedAt,closedAt:a.closedAt,mergedAt:a.mergedAt,commentsCount:a.comments,changedFilesCount:a.changedFiles,additions:a.additions,deletions:a.deletions,comments:a.commentDetails?.map(c=>({id:c.id,author:c.user,body:c.body,...c.bodyPagination&&{bodyPagination:c.bodyPagination},createdAt:c.createdAt,updatedAt:c.updatedAt,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.inReplyToId!=null&&{inReplyToId:c.inReplyToId}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submittedAt,commitId:c.commitId})),commits:a.commitDetails?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.fileChanges?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a.sanitizationWarnings)&&a.sanitizationWarnings.length>0?{sanitizationWarnings:a.sanitizationWarnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.totalCount||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Gr(e.pagination)},...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}function Fb(e,t,n){return{owner:t,repo:n,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,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}}async function Sd(e,t,n=Re){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},i=r||e.owner,s=Fb(e,i,o),a=await nd(s,t);return a.error?mt({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:Ob(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a)}}async function Db(e,t,n){try{let o=await(await Q(n)).rest.repos.listLanguages({owner:e,repo:t}),i=Object.entries(o.data).sort((s,a)=>a[1]-s[1]);return i.length===0?void 0:{languages:Object.fromEntries(i),dominantLanguage:i[0][0]}}catch{return}}async function Mb(e,t,n){try{let i=(await(await Q(n)).rest.repos.listContributors({owner:e,repo:t,per_page:30})).data.filter(s=>typeof s.login=="string").map(s=>({login:s.login,contributions:s.contributions??0}));return i.length>0?{contributors:i}:void 0}catch{return}}async function Nb(e,t,n){try{let i=(await(await Q(n)).rest.repos.listBranches({owner:e,repo:t,per_page:100})).data.map(s=>s.name).filter(s=>typeof s=="string");return i.length>0?{branches:i}:void 0}catch{return}}async function Gb(e,t,n){try{let i=(await(await Q(n)).rest.repos.listTags({owner:e,repo:t,per_page:50})).data.filter(s=>typeof s.name=="string").map(s=>({name:s.name,sha:s.commit?.sha??""}));return i.length>0?{tags:i}:void 0}catch{return}}function Hb(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 bd(e,t,n=Re){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,a,c,u,l]=await Promise.all([Ka(i,t),e.includeLanguages?Db(r,o,t):Promise.resolve(void 0),e.includeContributors?Mb(r,o,t):Promise.resolve(void 0),e.includeBranches?Nb(r,o,t):Promise.resolve(void 0),e.includeTags?Gb(r,o,t):Promise.resolve(void 0)]);return"error"in s?Ti(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:{...Hb(s),...a?{languages:a.languages,dominantLanguage:a.dominantLanguage}:{},...c?{contributors:c.contributors}:{},...u?{branches:u.branches}:{},...l?{tags:l.tags}:{}},status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s)}}var Ei=class{type="github";capabilities=hd.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await gd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Rd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await yd(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Sd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await bd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Re(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ae(n,r,this.authInfo)}handleError(t){let n=V(t);return mt(n)}};import{createHash as Ub}from"crypto";var Qb=3600*1e3,Ya=20,We=new Map;function Cd(e){return Date.now()-e.createdAt<Qb}function $b(){for(let[e,t]of We.entries())Cd(t)||We.delete(e);if(We.size>Ya){let e=[...We.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=We.size-Ya;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&We.delete(r[0])}}}function jb(e){return e?Ub("sha256").update(e).digest("hex").slice(0,16):"default"}function zb(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 Wb(e,t){let n=zb(t?.baseUrl||"default"),r=jb(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Xa(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=Wb(e,t),r=We.get(n);if(r&&Cd(r))return r.lastAccessedAt=Date.now(),r.provider;r&&We.delete(n),We.size>=Ya&&$b();let o=new Ei({...t,type:e}),i=Date.now();return We.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function T0(){We.clear()}async function xd(){try{return Xa("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}
25
- `),[{provider:"github",ok:!1,error:t}]}}import{ContentSanitizer as Vb}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as Kb}from"@octocodeai/config";function Yb(){try{return Kb().output.format}catch{return"yaml"}}function k0(e){if(e==null||typeof e!="object")return{content:[{type:"text",text:`error: "Invalid result options"
26
- `}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:Nt({data:t,instructions:n})}],isError:!!r}}function Ve(e){if(e==null)return e;if(typeof e=="string")return Vb.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Ve(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))n!=="warnings"&&(t[n]=Ve(r));return t}return e}function I0(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(`
22
+ `).trim()}import{ContentSanitizer as Na}from"@octocodeai/octocode-engine/contentSanitizer";var nb=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function qt(e){let t=e.toLowerCase();return t.endsWith("[bot]")||nb.has(t)}async function Pi(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=N(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Da(e,t,n,r){let o=await Q(r),{items:i,rawResponseChars:s}=await Pi(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $({total_count:i.length,files:i},s)}async function rb(e,t,n,r){let o=await Q(r),{items:i,rawResponseChars:s}=await Pi(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $(i,s)}async function ob(e,t,n,r){try{let i=await(await Q(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return $(i.data.files||[],i.data)}catch{return null}}var ib=5;async function sb(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)break;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function Ma(e,t,n,r,o){let i=await rb(e,t,n,o);if(!i)return null;let s=ne(i)??0,a=[...i].sort((u,l)=>{let p=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)-p}),c=await sb(a,ib,async u=>{let l=await ob(e,t,u.sha,o),p=[];return l&&(s+=ne(l)??0,p=vr(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:p}});return $(c,s)}async function Ga(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let d=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=N(d.data),i.push(...d.data),c=d.data.length===100,a++}while(c);let u=o?i:i.filter(d=>!qt(d.user?.login??"")),l=i.length-u.length,p=u.map(d=>{let f=O.minifyMarkdownCore(xi(d.body??""));return{id:String(d.id),user:d.user?.login??"unknown",body:Na.sanitizeContent(f).content,createdAt:d.created_at??"",updatedAt:d.updated_at??"",commentType:"discussion"}}),m=[];return l>0&&m.push(`${l} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(p,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Ha(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Pi(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return $(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Na.sanitizeContent(O.minifyMarkdownCore(xi(s.body??""))).content,submittedAt:s.submitted_at??void 0,commitId:s.commit_id??void 0})),i)}catch{return $([],0)}}async function Ba(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let d=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=N(d.data),i.push(...d.data),c=d.data.length===100,a++}while(c);let u=o?i:i.filter(d=>!qt(d.user?.login??"")),l=i.length-u.length,p=u.map(d=>{let f=O.minifyMarkdownCore(xi(d.body??""));return{id:String(d.id),user:d.user?.login??"unknown",body:Na.sanitizeContent(f).content,createdAt:d.created_at??"",updatedAt:d.updated_at??"",commentType:"review_inline",path:d.path,line:d.line??d.original_line??void 0,...d.in_reply_to_id!=null?{inReplyToId:d.in_reply_to_id}:{}}}),m=[];return l>0&&m.push(`${l} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(p,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Ua(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Oa(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&Fa(t))try{let{owner:u,repo:l}=Fr(t);if(u&&l){let p=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(p.data&&(s+=N(p.data),o.head=p.data.head?.ref,o.head_sha=p.data.head?.sha,o.base=p.data.base?.ref,o.base_sha=p.data.base?.sha,o.draft=p.data.draft??!1,p.data.merged_at&&(o.merged_at=p.data.merged_at),o.additions=p.data.additions??0,o.deletions=p.data.deletions??0,kn(t)||(o.file_changes={total_count:p.data.changed_files??0,files:[]}),kn(t))){let m=await Da(u,l,e.number);m&&(s+=ne(m)??0,m.files=vr(m.files,t),o.file_changes=m)}}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let a=Ri(t),c=Si(t);if(a||c){let{owner:u,repo:l}=Fr(t);if(u&&l){let p=va(t),m=()=>Promise.resolve({comments:$([],0)}),[{comments:d,note:f},{comments:g,note:R}]=await Promise.all([a?Ga(n,u,l,e.number,p):m(),c?Ba(n,u,l,e.number,p):m()]);o.comments=[...d,...g],s+=(ne(d)??0)+(ne(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}}if(Ci(t))try{let{owner:u,repo:l}=Fr(t);if(u&&l){let p=await Ha(n,u,l,e.number);s+=ne(p)??0,o.reviews=p}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(bi(t))try{let{owner:u,repo:l}=Fr(t);if(u&&l){let p=await Ma(u,l,e.number,t);p&&(s+=ne(p)??0,o.commits=p)}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return $(o,s)}async function Dr(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Oa(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,kn(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),kn(t))try{let p=await Da(a,c,e.number,r);p&&(s+=ne(p)??0,p.files=vr(p.files,t),o.file_changes=p)}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${p instanceof Error?p.message:String(p)}`]}let u=Ri(t),l=Si(t);if(u||l){let p=va(t),m=()=>Promise.resolve({comments:$([],0)}),[{comments:d,note:f},{comments:g,note:R}]=await Promise.all([u?Ga(n,a,c,e.number,p):m(),l?Ba(n,a,c,e.number,p):m()]);o.comments=[...d,...g],s+=(ne(d)??0)+(ne(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}if(Ci(t))try{let p=await Ha(n,a,c,e.number);s+=ne(p)??0,o.reviews=p}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${p instanceof Error?p.message:String(p)}`]}if(bi(t))try{let p=await Ma(a,c,e.number,t,r);p&&(s+=ne(p)??0,o.commits=p)}catch(p){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${p instanceof Error?p.message:String(p)}`]}return $(o,s)}function ab(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function BF(e,t,n){let r=await fe(t),o=ce("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode,auth:r},n);return await he(o,async()=>await Qa(e,t),{shouldCache:s=>!s.error})}async function Qa(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pullRequests:[],totalCount:0,error:Ee.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pullRequests:[],totalCount:0,error:Ee.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await Q(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Dr(a,e,i,t);return{pullRequests:[An(c,{includeFullBody:!0,includeFullCommentDetails:!0})],totalCount:1,rawResponseChars:N(s.data)+(ne(c)??0)}}catch(i){let s=V(i);return ab(s,Ee.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 $a(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function ja(e){let t=Math.min(e.limit||30,100);return{pullRequests:[],totalCount:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function od(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 Dr(m,t,e))),c=a.reduce((m,d)=>m+(ne(d)??0),0),u=a.map(m=>An(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),l=s.data.length===o,p=(i-1)*o+u.length;return{pullRequests:u,totalCount:u.length,pagination:{currentPage:i,totalPages:l?i+1:i,perPage:o,totalMatches:p+(l?1:0),reachableTotalMatches:p,totalMatchesKind:l?"lowerBound":"exact",hasMore:l,...l?{nextPage:i+1}:{}},rawResponseChars:N(s.data)+c}}catch(n){if(nt(n))return ja(t);let r=V(n);return $a(r,Ee.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}async function cb(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function ub(e,t,n="anon"){return ce("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,project:e.project,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function id(e,t,n){let r=await fe(t),o=ub(e,n,r);return await he(o,async()=>await lb(e,t,n),{shouldCache:s=>!s.error})}async function lb(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Qa(e,t);let r=await Q(t);if(!sa(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await od(r,e);let i=await cb(r,e),s=ia(i);if(!s)return{pullRequests:[],totalCount:0,error:Ee.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),u=i.page||1,l=s,p=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:u}),m=p.data.items?.filter(T=>!!T.pull_request)||[],d=await Promise.all(m.map(async T=>await Ua(T,i,r))),f=d.reduce((T,L)=>T+(ne(L)??0),0),g=d.map(T=>An(T,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),R=p.data.total_count,h=Math.min(R,1e3),y=Math.min(Math.ceil(h/c),10),S=Math.min(u,Math.max(1,y)),C=S<y,P=Math.min(h,y*c);return{pullRequests:g,totalCount:p.data.total_count,effectiveQuery:l,...p.data.incomplete_results&&{incompleteResults:!0},pagination:{currentPage:S,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:R,reachableTotalMatches:P,totalMatchesKind:"reported",totalMatchesCapped:R>h,hasMore:C,...C?{nextPage:S+1}:{}},rawResponseChars:N(p.data)+f}}catch(r){if(nt(r))return ja(e);let o=V(r);return $a(o,Ee.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var pb=/^(\d+)\s*([hdwmy])$/i;function za(e){let t=e.trim(),n=pb.exec(t);if(n){let r=Number(n[1]),o=n[2].toLowerCase(),i=new Date;switch(o){case"h":i.setUTCHours(i.getUTCHours()-r);break;case"d":i.setUTCDate(i.getUTCDate()-r);break;case"w":i.setUTCDate(i.getUTCDate()-r*7);break;case"m":i.setUTCMonth(i.getUTCMonth()-r);break;case"y":i.setUTCFullYear(i.getUTCFullYear()-r);break}return{value:i.toISOString()}}return Number.isNaN(Date.parse(t))?{warning:`"${e}" is not a valid date or relative window \u2014 use e.g. "30d", "2w", "6m", "1y", or an ISO date like "2026-01-01". Filter skipped.`}:{value:t}}function Wa(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Mr(e,t){let n=e.map(l=>{let p=l.patch!==void 0?Wa(l.patch,t.charOffset,t.charLength):void 0;return{filename:l.filename,status:l.status,additions:l.additions,deletions:l.deletions,...p!==void 0?{patch:p.patch,...p.patchPagination?{patchPagination:p.patchPagination}:{}}:{},...l.previous_filename?{previousFilename:l.previous_filename}:{}}}),r=Math.max(1,t.filePage??1),o=Math.max(1,t.itemsPerPage??20),i=n.length,s=Math.max(1,Math.ceil(i/o)),a=Math.min(r,s),c=(a-1)*o;return{files:n.slice(c,c+o),filesPagination:{currentPage:a,totalPages:s,itemsPerPage:o,totalFiles:i,hasMore:a<s,...a<s?{nextFilePage:a+1}:{}}}}var db=5;function _n(e){return e?e.includes('rel="next"'):!1}async function mb(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function sd(e,t,n){let r=await fe(t),o=ce("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,committer:e.committer,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return he(o,()=>fb(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function fb(e,t){try{let n=await Q(t),r=[],o=e.since?za(e.since):void 0,i=e.until?za(e.until):void 0;o?.warning&&r.push(`since ${o.warning}`),i?.warning&&r.push(`until ${i.warning}`);let s={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...o?.value?{since:o.value}:{},...i?.value?{until:i.value}:{},...e.author?{author:e.author}:{},...e.committer?{committer:e.committer}:{}},a=await n.rest.repos.listCommits(s),c=a.headers.link,u=_n(c),l=a.data.map(h=>{let y=h.commit.author,S=h.commit.committer,C=S?.date??y?.date??"",P=h.commit.message,T=P.split(`
23
+ `)[0]??P,L=P.slice(T.length).trim(),k=L.length>500,w=L.length===0?T:`${T}
24
+ ${k?`${L.slice(0,500)}\u2026`:L}`,b=S?.name===y?.name&&S?.email===y?.email||h.committer?.login==="web-flow";return{sha:h.sha,date:C,...w===T?{}:{message:w},...k?{messageTruncated:!0}:{},messageHeadline:T,author:{name:y?.name??"unknown",email:y?.email??"",...h.author?.login?{login:h.author.login}:{}},...S&&!b?{committer:{name:S.name??"unknown",email:S.email??"",...h.committer?.login?{login:h.committer.login}:{}}}:{}}});l.length===0&&(o?.value!==void 0||i?.value!==void 0)&&r.push("no commits matched the since/until window \u2014 GitHub filters by committer date (not author date; rebases and squash-merges reset it), and a path-scoped walk does not follow renames. Widen or drop since/until and inspect commit dates directly.");let p={currentPage:e.page,perPage:e.perPage,hasMore:u,...u?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:p,...r.length?{warnings:r}:{}},status:200};let m=!1,d=!1,f=await mb(l,db,async(h,y)=>{try{let S=a.data[y]?.sha??h.sha,C=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:S});if(e.type==="file"&&e.path){let P=e.path,T=C.data.files?.find(w=>w.filename===P||w.previous_filename===P);if(T){let w=T.patch!==void 0?Wa(T.patch,e.charOffset,e.charLength):void 0;return{...h,additions:T.additions,deletions:T.deletions,status:T.status,...w!==void 0?{patch:w.patch,...w.patchPagination?{patchPagination:w.patchPagination}:{}}:{},...T.previous_filename?{previousFilename:T.previous_filename}:{}}}let L=P.endsWith("/")?P:`${P}/`,k=(C.data.files??[]).filter(w=>w.filename.startsWith(L));return k.length>0?(m=!0,{...h,...Mr(k,e)}):(d=!0,h)}else{let P=e.path,T=(C.data.files??[]).filter(L=>!P||L.filename.startsWith(P));return{...h,...Mr(T,e)}}}catch{}return h}),g=[];m&&g.push(`path '${e.path}' matched no single file in these commits but matches files under it \u2014 treated as a directory filter and returned per-commit changed files (append '/' to select directory mode explicitly).`),d&&g.push(`includeDiff: some commits contain no file matching '${e.path}' (rename or shallow diff?) \u2014 those commits are listed without a diff.`);let R=[...r,...g];return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:f,pagination:p,...R.length?{warnings:R}:{}},status:200}}catch(n){return V(n)}}var ad=30;function cd(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 ud(e,t,n){let r=await fe(t),o=e,i=ce("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await he(i,async()=>await gb(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function hb(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(d){if(d?.status!==404)return V(d);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return V(g)}}let a=i.map(d=>{let g=d.full_name.split("/"),R=g[0]||"",h=g[1]||"";return{owner:R,repo:h,defaultBranch:d.default_branch,stars:d.stargazers_count||0,description:d.description?d.description:"No description",url:d.html_url,createdAt:d.created_at,updatedAt:d.updated_at,pushedAt:d.pushed_at,visibility:d.visibility,...d.topics&&d.topics.length>0&&{topics:d.topics},...d.forks_count&&d.forks_count>0&&{forksCount:d.forks_count},...d.open_issues_count&&d.open_issues_count>0&&{openIssuesCount:d.open_issues_count},...d.language&&{language:d.language},...cd(d)}}),c=a.length,u=c===n,l=(r-1)*n+c,p=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:p,reachableTotalMatches:l,totalMatchesKind:m,hasMore:u,...u?{nextPage:r+1}:{}}},status:200,rawResponseChars:N(i)}}async function gb(e,t){try{let n=await Q(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 hb({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=ra(e);if(!i.trim())return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||ad,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),p=l.data.items.map(y=>{let C=y.full_name.split("/"),P=C[0]||"",T=C[1]||"";return{owner:P,repo:T,defaultBranch:y.default_branch,stars:y.stargazers_count||0,description:y.description?y.description:"No description",url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at,pushedAt:y.pushed_at,visibility:y.visibility,...y.topics&&y.topics.length>0&&{topics:y.topics},...y.forks_count&&y.forks_count>0&&{forksCount:y.forks_count},...y.open_issues_count&&y.open_issues_count>0&&{openIssuesCount:y.open_issues_count},...y.language&&{language:y.language},...cd(y)}}),m=l.data.total_count,d=Math.min(m,1e3),f=Math.min(Math.ceil(d/s),10),g=Math.min(a,Math.max(1,f)),R=g<f,h=Math.min(d,f*s);return{data:{repositories:p,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:d,reportedTotalMatches:m,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:m>d,hasMore:R,...R?{nextPage:g+1}:{}}},status:200,headers:Cn(l.headers),rawResponseChars:N(l.data)}}catch(n){if(nt(n)){let r=Math.min(e.limit||ad,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 V(n)}}var Mt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function yb(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 Rb(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 Ev(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...yb(e.estimatedTokens,n)),o.push(...Rb(e)),o}function wi(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function ld(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:w,...b}=e;return b}let r=t.itemsPerPage??Mt.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),p=e.path==="/"?"":e.path,m=w=>{let b=w;p&&w.startsWith(p)&&(b=w.slice(p.length),b.startsWith("/")&&(b=b.slice(1)));let A=b.lastIndexOf("/");return A===-1?".":b.slice(0,A)},d=w=>{let b=w.lastIndexOf("/");return b===-1?w:w.slice(b+1)};for(let w of u){let b=m(w.path);l[b]||(l[b]={files:[],folders:[]});let A=d(w.path);w.type==="file"?l[b].files.push(A):l[b].folders.push(A)}for(let w of Object.keys(l)){let b=l[w];b&&(b.files.sort(),b.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((w,b)=>w==="."?-1:b==="."?1:w.localeCompare(b));for(let w of g){let b=l[w];b&&(f[w]=b)}let R=u.filter(w=>w.type==="file").length,h=u.filter(w=>w.type==="dir").length,y=n.filter(w=>w.type==="file").length,S=n.filter(w=>w.type==="dir").length,C=o<s,P={currentPage:o,totalPages:s,hasMore:C,...C?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},T=wi(P,{owner:e.owner,repo:e.repo,branch:e.branch,path:p,depth:t.maxDepth??1,pageFiles:R,pageFolders:h,allFiles:y,allFolders:S}),L,k=e._cachedFileSizeMap;if(k){let w=new Set(u.filter(M=>M.type==="file").map(M=>M.path)),b=e.path==="/"?"":e.path,A=Object.create(null);for(let[M,B]of Object.entries(k))for(let[I,U]of Object.entries(B)){let ee=M==="."?b?`${b}/${I}`:I:b?`${b}/${M}/${I}`:`${M}/${I}`;w.has(ee)&&(A[M]||(A[M]=Object.create(null)),A[M][I]=U)}Object.keys(A).length>0&&(L=A)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:y,totalFolders:S,truncated:C,filtered:!0,originalCount:i},structure:f,...L!==void 0&&{fileSizeMap:L},...k!==void 0&&{_cachedFileSizeMap:k},pagination:P,hints:T,rawResponseChars:e.rawResponseChars}}import{RequestError as Sb}from"octokit";var dd=Symbol.for("octocode.recursiveFetchFailures"),bb=new Set([401,403,429]);function pd(e){return e instanceof Sb&&bb.has(e.status)}function Va(e,t){try{Object.defineProperty(e,dd,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Nr(e){if(typeof e!="object"||e===null)return 0;let t=e[dd];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Gr(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Va($([],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(pd(f))throw f;return Va($([],0),1)}let u=N(c.data),p=(Array.isArray(c.data)?c.data:[c.data]).filter(f=>f.type==="file"||f.type==="dir").map(f=>({name:f.name,path:f.path,type:f.type,size:"size"in f?f.size:void 0,download_url:"download_url"in f?f.download_url:void 0,url:f.url,html_url:f.html_url,git_url:f.git_url,sha:f.sha})),m=[...p],d=0;if(i<s){let f=p.filter(R=>R.type==="dir"),g=3;for(let R=0;R<f.length;R+=g){let h=f.slice(R,R+g),y=await Promise.allSettled(h.map(S=>Gr(e,t,n,r,S.path,i+1,s,a)));for(let S of y)if(S.status==="fulfilled"){let C=S.value;u+=ne(C)??0,d+=Nr(C),m.push(...C)}else{if(pd(S.reason))throw S.reason;d+=1}}}return Va($(m,u),d)}import{RequestError as Cb}from"octokit";function xb(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let u=a.lastIndexOf("/"),l=u===-1?a:a.slice(u+1);i.push({name:l,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function md(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function fd(e,t){let{data:n}=await e.rest.repos.getBranch({owner:t.owner,repo:t.repo,branch:t.workingBranch}),r=n.commit.commit.tree.sha;if(!r)throw new Error(`Could not resolve tree SHA for ${t.owner}/${t.repo}@${t.workingBranch}`);let o;try{o=await e.rest.git.getTree({owner:t.owner,repo:t.repo,tree_sha:r,recursive:"true",...t.ifNoneMatch?{headers:{"If-None-Match":t.ifNoneMatch}}:{}})}catch(c){if(c instanceof Cb&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=xn(o.headers);return{items:xb(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:N(n)+N(i),...s?{etag:s}:{}}}import{RequestError as hd}from"octokit";async function Ka(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Ae(t,n,i),a=c)}catch(u){let l=V(u);return{error:xt.NOT_FOUND.message(t,n,l.error),status:l.status}}try{let u=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),l=xn(u.headers);return{data:u.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...l?{etag:l}:{}}}catch(u){if(u instanceof hd&&u.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(u instanceof hd&&u.status===404)){let p=V(u);return{error:xt.ACCESS_FAILED.message(t,n,p.error),status:p.status,rateLimitRemaining:p.rateLimitRemaining,rateLimitReset:p.rateLimitReset,retryAfter:p.retryAfter}}let l=V(u);return{error:xt.PATH_NOT_FOUND.message(r,t,n,a),status:l.status}}}function gd(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 Pb(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 yd(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}function Ti(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:u,includeSizes:l,extraHints:p=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!Cr(I.name):!bn(I.path));m.sort((I,U)=>{if(I.type!==U.type)return I.type==="dir"?-1:1;let ee=I.path.split("/").length,v=U.path.split("/").length;return ee!==v?ee-v:I.path.localeCompare(U.path)});let d=e.itemsPerPage??Mt.ENTRIES_PER_PAGE,f=e.page??1,g=m.length,R=Math.max(1,Math.ceil(g/d)),h=(f-1)*d,y=Math.min(h+d,g),S=m.slice(h,y),C=Pb(S,i),P=l?yd(m,i):void 0,T=P!==void 0?yd(S,i):void 0,L=S.filter(I=>I.type==="file").length,k=S.filter(I=>I.type==="dir").length,w=m.filter(I=>I.type==="file").length,b=m.filter(I=>I.type==="dir").length,A=f<R,M={currentPage:f,totalPages:R,hasMore:A,...A?{nextPage:f+1}:{},entriesPerPage:d,totalEntries:g},B=wi(M,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:L,pageFolders:k,allFiles:w,allFolders:b});a>0&&B.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let I of p)B.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:w,totalFolders:b,truncated:A,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:C,...T!==void 0&&{fileSizeMap:T},...P!==void 0&&{_cachedFileSizeMap:P},pagination:M,hints:B,rawResponseChars:u,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}async function Ya(e,t,n){let r=await fe(t),o=ce("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await ai(o,async({ifNoneMatch:s})=>{let a=await wb({...e,itemsPerPage:e.itemsPerPage??Mt.ENTRIES_PER_PAGE,page:e.page??1},t,s);return{value:a.result,etag:a.etag,notModified:a.notModified}},{shouldCache:s=>!("error"in s)});return!("error"in i)&&i.structure?ld(i,e):i}async function wb(e,t,n){try{let r=await Q(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,u=a.replace(/^\/+|\/+$/g,"");if(c>1&&md())return await Tb(r,e,u,c,t,n);let l=await Ka(r,o,i,u,s,t,c===1?n:void 0);if("error"in l)return{result:l};if(l.notModified)return{result:{error:"not-modified",status:304},etag:l.etag??n,notModified:!0};let{data:p,workingBranch:m,repoDefaultBranch:d,etag:f}=l,g=N(p),R=Array.isArray(p)?p:[p],h=gd(R),y=0;if(c>1){let S=await Gr(r,o,i,m,u,1,c);y=Nr(S),g=ne(S)??0,h=S}return{result:Ti({owner:o,repo:i,workingBranch:m,repoDefaultBranch:d,cleanPath:u,depth:c,allItems:h,partialTreeFailures:y,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&f?{etag:f}:{}}}catch(r){let o=V(r);return{result:{error:xt.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function Tb(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,u,l;try{c?u=c:(l=await Ae(s,a,o),u=l)}catch(h){let y=V(h);return{result:{error:xt.NOT_FOUND.message(s,a,y.error),status:y.status}}}let p;try{p=await fd(e,{owner:s,repo:a,workingBranch:u,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(h){let y=await Ka(e,s,a,n,u,o);if("error"in y)return{result:y};let S=await Gr(e,s,a,y.workingBranch,n,1,r);return{result:Ti({owner:s,repo:a,workingBranch:y.workingBranch,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:S,partialTreeFailures:Nr(S),incompleteTree:!1,rawResponseChars:ne(S)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${h instanceof Error?h.message:String(h)}); used Contents recursion instead.`]})}}if(p.notModified)return{result:{error:"not-modified",status:304},etag:p.etag??i,notModified:!0};let m=p.items,d=0,f=p.rawResponseChars,g=p.truncated,R=[];if(g){R.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let h=await Gr(e,s,a,u,n,1,r);d=Nr(h),f+=ne(h)??0,m=[...m,...h].filter((S,C,P)=>P.findIndex(T=>T.path===S.path)===C)}catch{}}return{result:Ti({owner:s,repo:a,workingBranch:u,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:m,partialTreeFailures:d,incompleteTree:g,rawResponseChars:f,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:R}),...p.etag&&!g?{etag:p.etag}:{}}}var Rd={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};function Oe(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function Eb(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function Lb(e){return!!(e&&typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"full_name"in e&&typeof e.full_name=="string"&&"private"in e&&typeof e.private=="boolean")}function Re(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 Ab(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 mt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:Ab(e)}}function Ei(e){return kb(e)?mt({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 kb(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||_b(n)}function _b(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Hr(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Ib(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,...Hr(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function Ob(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,...Hr(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Sd(e,t,n=Re){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 bp(s,t);return Oe(a)?mt(a):a.data?{data:Ib(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function bd(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 ud(n,t);return"error"in r?Ei(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:Ob(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??N(r.data)}}function vb(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,matchedLines:e.matchedLines,warnings:Db(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function Db(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 Cd(e,t,n=Re){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 qp(i,t);if(Oe(s))return mt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:vb(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s.data),...a?.length?{hints:a}:{}}}function Nb(e,t,n=Re){let r=(e.pullRequests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.bodyPagination&&{bodyPagination:a.bodyPagination},state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.headRef||"",targetBranch:a.baseRef||"",sourceSha:a.headSha,targetSha:a.baseSha,createdAt:a.createdAt,updatedAt:a.updatedAt,closedAt:a.closedAt,mergedAt:a.mergedAt,commentsCount:a.comments,changedFilesCount:a.changedFiles,additions:a.additions,deletions:a.deletions,comments:a.commentDetails?.map(c=>({id:c.id,author:c.user,body:c.body,...c.bodyPagination&&{bodyPagination:c.bodyPagination},createdAt:c.createdAt,updatedAt:c.updatedAt,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.inReplyToId!=null&&{inReplyToId:c.inReplyToId}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submittedAt,commitId:c.commitId})),commits:a.commitDetails?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.fileChanges?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a.sanitizationWarnings)&&a.sanitizationWarnings.length>0?{sanitizationWarnings:a.sanitizationWarnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.totalCount||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Hr(e.pagination)},...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}function Gb(e,t,n){return{owner:t,repo:n,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,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}}async function xd(e,t,n=Re){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},i=r||e.owner,s=Gb(e,i,o),a=await id(s,t);return a.error?mt({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:Nb(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a)}}async function Bb(e,t,n){try{let o=await(await Q(n)).rest.repos.listLanguages({owner:e,repo:t}),i=Object.entries(o.data).sort((s,a)=>a[1]-s[1]);return i.length===0?void 0:{languages:Object.fromEntries(i),dominantLanguage:i[0][0]}}catch{return}}async function Ub(e,t,n){try{let i=(await(await Q(n)).rest.repos.listContributors({owner:e,repo:t,per_page:30})).data.filter(s=>typeof s.login=="string").map(s=>({login:s.login,contributions:s.contributions??0}));return i.length>0?{contributors:i}:void 0}catch{return}}async function Qb(e,t,n){try{let i=(await(await Q(n)).rest.repos.listBranches({owner:e,repo:t,per_page:100})).data.map(s=>s.name).filter(s=>typeof s=="string");return i.length>0?{branches:i}:void 0}catch{return}}async function $b(e,t,n){try{let i=(await(await Q(n)).rest.repos.listTags({owner:e,repo:t,per_page:50})).data.filter(s=>typeof s.name=="string").map(s=>({name:s.name,sha:s.commit?.sha??""}));return i.length>0?{tags:i}:void 0}catch{return}}function jb(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 Pd(e,t,n=Re){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,a,c,u,l]=await Promise.all([Ya(i,t),e.includeLanguages?Bb(r,o,t):Promise.resolve(void 0),e.includeContributors?Ub(r,o,t):Promise.resolve(void 0),e.includeBranches?Qb(r,o,t):Promise.resolve(void 0),e.includeTags?$b(r,o,t):Promise.resolve(void 0)]);return"error"in s?Ei(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:{...jb(s),...a?{languages:a.languages,dominantLanguage:a.dominantLanguage}:{},...c?{contributors:c.contributors}:{},...u?{branches:u.branches}:{},...l?{tags:l.tags}:{}},status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s)}}var Li=class{type="github";capabilities=Rd.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Sd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Cd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await bd(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await xd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Pd(t,this.authInfo,Re)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Re(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ae(n,r,this.authInfo)}handleError(t){let n=V(t);return mt(n)}};import{createHash as Wb}from"crypto";var Vb=3600*1e3,Xa=20,We=new Map;function wd(e){return Date.now()-e.createdAt<Vb}function Kb(){for(let[e,t]of We.entries())wd(t)||We.delete(e);if(We.size>Xa){let e=[...We.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=We.size-Xa;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&We.delete(r[0])}}}function Yb(e){return e?Wb("sha256").update(e).digest("hex").slice(0,16):"default"}function Xb(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 qb(e,t){let n=Xb(t?.baseUrl||"default"),r=Yb(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function qa(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=qb(e,t),r=We.get(n);if(r&&wd(r))return r.lastAccessedAt=Date.now(),r.provider;r&&We.delete(n),We.size>=Xa&&Kb();let o=new Li({...t,type:e}),i=Date.now();return We.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function U0(){We.clear()}async function Td(){try{return qa("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}
25
+ `),[{provider:"github",ok:!1,error:t}]}}import{ContentSanitizer as Jb}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as Zb}from"@octocodeai/config";function eC(){try{return Zb().output.format}catch{return"yaml"}}function W0(e){if(e==null||typeof e!="object")return{content:[{type:"text",text:`error: "Invalid result options"
26
+ `}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:Nt({data:t,instructions:n})}],isError:!!r}}function Ve(e){if(e==null)return e;if(typeof e=="string")return Jb.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Ve(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))n!=="warnings"&&(t[n]=Ve(r));return t}return e}function V0(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(`
27
27
 
28
- `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Nt(e,t){let n=Jt(e)??{},r=Ve(n),o=Yb(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Li(r,t||i),null,2):O.jsonToYamlString(r,{keysPriority:t||i})}function Li(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Li(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Li(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Li(n[o],t));return r}var Xb=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"]),qb=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"];function Jb(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=>Xb.has(r))||qb.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Jt(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=>Jt(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(s==="warnings"||Jb(a))continue;let c=(s==="files"||s==="repositories")&&!n,u=Jt(a,{inFilesObject:n||c,depth:c?0:r+1});u!==void 0&&(o[s]=u,i=!0)}return i?o:void 0}return e}import{z as Ai}from"zod";function I(e,t){return Ai.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Ai.number().int().min(e).max(t))}var q=I(1,1e3).optional().default(1),In=I(0,100).optional(),On=I(1,1e9).optional(),Zb={responseCharOffset:I(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:I(1,5e4).optional().describe("Full-response char window.")};function K(e,t={}){let{maxQueries:n=5}=t;return Ai.object({queries:Ai.array(e).min(1).max(n).describe("Parallel queries."),...Zb}).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 ie}from"zod";import{z as j}from"zod";var eC=j.object({currentPage:j.number(),totalPages:j.number(),hasMore:j.boolean(),nextPage:j.number().optional(),pageSize:j.number().optional(),totalItems:j.number().optional(),perPage:j.number().optional(),totalFound:j.number().optional(),returned:j.number().optional(),totalMatches:j.number().optional(),reportedTotalMatches:j.number().optional().describe("Provider-reported raw total (e.g. GitHub's match count) \u2014 may exceed what pagination can actually reach."),reachableTotalMatches:j.number().optional().describe("Matches reachable by walking pages (bounded by the provider's result window, e.g. GitHub caps at 1000); totalPages is computed from this, not from reportedTotalMatches."),totalMatchesKind:j.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:j.boolean().optional(),totalResults:j.number().optional(),itemsPerPage:j.number().optional()}),N0=j.object({charOffset:j.number(),charLength:j.number(),totalChars:j.number(),hasMore:j.boolean(),nextCharOffset:j.number().optional(),currentPage:j.number().optional(),totalPages:j.number().optional(),chunkMode:j.enum(["semantic","char-limit"]).optional()}),qa=j.object({tool:j.string(),query:j.record(j.string(),j.unknown()),why:j.string().optional(),confidence:j.enum(["exact","high","medium","low"]).optional()}),G0=eC.extend({filesPerPage:j.number().optional(),entriesPerPage:j.number().optional(),matchesPerPage:j.number().optional(),totalFiles:j.number().optional(),totalEntries:j.number().optional(),totalMatches:j.number().optional(),totalFilesFound:j.number().optional(),nextMatchPage:j.number().optional()}),tC=["id","mainResearchGoal","researchGoal","reasoning"];function nC(e){let t;for(let n of tC)n in e&&(t??={...e},delete t[n]);return t??e}function Fn(e,t,n="Continue to the next page of results."){return{tool:e,query:nC(t),why:n,confidence:"exact"}}function _i(e,t,n,r){if(!n||!n.hasMore||n.nextCharOffset===void 0)return;let o=r?.includeCharLength!==!1;return{continueChars:{tool:e,query:{...t,charOffset:n.nextCharOffset,...o&&n.charLength!==void 0?{charLength:n.charLength}:{}}}}}var rC=ie.object({currentPage:ie.number(),totalPages:ie.number(),hasMore:ie.boolean(),charOffset:ie.number(),charLength:ie.number(),totalChars:ie.number(),nextCharOffset:ie.number().optional()}).optional(),Pd={base:ie.string().optional(),shared:ie.record(ie.string(),ie.union([ie.string(),ie.number(),ie.boolean()])).optional(),responsePagination:rC,next:ie.record(ie.string(),qa).optional()};function Q0(e){return e.extend(Pd)}function oC(e){return ie.object({id:ie.string(),status:ie.enum(["empty","error"]).optional(),data:e,next:ie.record(ie.string(),qa).optional()})}var $0=oC(ie.record(ie.string(),ie.unknown()).optional()),j0=Pd;function iC(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function F(e,t,n={}){let{extra:r}=n,o={status:"error"};if(iC(e))o.error=e;else if(ws(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=qu(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:$(o,n.rawResponse)}function _e(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:F(i,t,{toolName:n.toolName})}}async function q0(e,t,n){if(e)try{await e(t,n)}catch{return}}function se(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:$(s,o.rawResponse)}function ki(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 F(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function be(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return F(i,t,{toolName:r})}async function Fe({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return be(o,t,r,e)}}import{existsSync as cC,mkdirSync as ec,renameSync as uC,rmSync as lC}from"fs";import{join as Br}from"path";import{createHash as pC}from"crypto";var tD=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Hr=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],vn=[...Hr,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],wd=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function Ii(e={},t=Hr){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}import{spawn as Ja}from"child_process";var sC=10*1024*1024,Za=5e3;function Zt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Hr,maxOutputSize:a=sC}=n;return new Promise(c=>{let u={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},l=()=>u.stdoutChunks.join(""),p=()=>u.stderrChunks.join(""),m={cwd:o,env:Ii(i,s),stdio:["ignore","pipe","pipe"]},d;try{d=Ja(e,t,m)}catch(y){c({stdout:"",stderr:"",exitCode:null,success:!1,error:y instanceof Error?y:new Error(`Failed to spawn command '${e}'`)});return}let f,g=setTimeout(()=>{if(!u.killed){u.killed=!0;try{d.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{d.kill("SIGKILL")}catch{}},Za),c({stdout:l(),stderr:p(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),R=()=>{clearTimeout(g),f!==void 0&&(clearTimeout(f),f=void 0)},h=()=>{if(u.totalOutputSize>a){if(!u.killed){u.killed=!0;try{d.kill("SIGKILL")}catch{}R(),c({stdout:l(),stderr:p(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};d.stdout?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stdoutChunks.push(S)}),d.stderr?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stderrChunks.push(S)}),d.on("close",y=>{u.killed||(R(),c({stdout:l(),stderr:p(),exitCode:y,success:y===0}))}),d.on("error",y=>{u.killed||(u.killed=!0,R(),c({stdout:l(),stderr:p(),exitCode:null,success:!1,error:y}))})})}function Td(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Hr}=r,a;try{a=Ja(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Ii({},s)})}catch{o(!1);return}let c,u=()=>{clearTimeout(l),c!==void 0&&(clearTimeout(c),c=void 0)},l=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Za),o(!1)}},n);a.on("close",p=>{u(),i||o(p===0)}),a.on("error",()=>{u(),i||o(!1)})})}var aC=1*1024*1024;function aD(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=vn,maxOutputSize:u=aC}=r,l;try{l=Ja(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Ii({},c)})}catch{o(null);return}let p,m=()=>{clearTimeout(d),p!==void 0&&(clearTimeout(p),p=void 0)};l.stdout?.on("data",f=>{if(i)return;let g=f.toString();if(a+=Buffer.byteLength(g),a>u){if(!i){i=!0;try{l.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(g)}),l.stderr?.on("data",()=>{});let d=setTimeout(()=>{if(!i){i=!0;try{l.kill("SIGTERM")}catch{}p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}},Za),o(null)}},n);l.on("close",f=>{if(m(),!i)if(f===0){let g=s.join("").trim();o(g||null)}else o(null)}),l.on("error",()=>{m(),i||o(null)})})}function Oi(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var Ed=120*1e3,dC=30*1e3,mC=300*1e3,fC=100,Ld="clone-locks",hC="clone-tmp",Ad=[...vn,"GIT_TERMINAL_PROMPT"];async function _d(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await wC();let a=e.branch??await Ae(r,o,t),c=zt(),u=ma(c,r,o,a,i);return gC(c,u,async()=>{let l=En(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};li(c),vt(u);let p=PC(t,n),m=RC(c,u);pi(m);try{if(i){if(await xC(r,o,a,m,i,p),!cC(Br(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await CC(r,o,a,m,p);let d=Ln(r,o,a,"clone",i);return Tn(m,d),SC(m,u),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(d){throw pi(m),d}})}async function gC(e,t,n){vt(t);let r=yC(e,t);ec(Br(e,"tmp",Ld),{recursive:!0,mode:448});let o=Date.now();for(;;)try{ec(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>mC)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await bC(fC)}try{return await n()}finally{lC(r,{recursive:!0,force:!0})}}function kd(e){return pC("sha256").update(e).digest("hex").slice(0,16)}function yC(e,t){return Br(e,"tmp",Ld,kd(t))}function RC(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Br(e,"tmp",hC);return ec(r,{recursive:!0,mode:448}),Br(r,`${kd(t)}-${n}`)}function SC(e,t){pi(t),vt(t),uC(e,t)}function bC(e){return new Promise(t=>setTimeout(t,e))}async function CC(e,t,n,r,o){let i=Od(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Id(e,t),r),await tc(i,Ed,`full clone of ${e}/${t}`,o)}async function xC(e,t,n,r,o,i){let s=Od(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Id(e,t),r),await tc(s,Ed,`sparse clone of ${e}/${t}`,i),await tc(["-C",r,"sparse-checkout","set","--skip-checks","--",o],dC,`sparse-checkout set ${o}`,void 0)}function Id(e,t){return`https://github.com/${e}/${t}.git`}function Od(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function PC(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function wC(){try{if(!(await Zt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Ad,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 TC(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 tc(e,t,n,r){let o=await Zt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Ad,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=TC(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}import{existsSync as EC,readdirSync as LC,lstatSync as AC}from"node:fs";import{join as _C}from"node:path";function Fd(e){if(!EC(e))return 0;let t;try{t=LC(e)}catch{return 0}let n=0;for(let r of t){if(r===".git")continue;let o=_C(e,r);try{let i=AC(o);if(i.isSymbolicLink())continue;i.isDirectory()?n+=hr(o):i.isFile()&&(n+=i.size)}catch{}}return n}async function vd(e,t={}){if(!Array.isArray(e))throw new Error(tr.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(tr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(tr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,u)=>typeof c=="function"?c:()=>Promise.reject(new Error(rr.NOT_A_FUNCTION.message(u))));if(r<i.length)return kC(i,r,n,o);let s=i.map((c,u)=>Dd(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 Dd(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,u)=>{o=setTimeout(()=>{u(new Error(rr.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 kC(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){o[c]={success:!1,error:new Error(rr.FUNCTION_UNDEFINED.message),index:c};continue}try{let l=await Dd(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}var Md=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,IC=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,OC=5e3;function Nd(e,t,n){if(e<=1)return Md;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(IC/o),s=Math.max(OC,Math.min(i,Md));return n?Math.max(s,n):s}async function Gd(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 vd(s,{timeout:Nd(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,u)=>{i.push({queryIndex:u,error:c.message})}})).forEach(c=>{if(c.success&&c.data){let u=c.data.result,l=u&&Object.keys(u).some(m=>m!=="status"&&m!=="error"&&m!=="data");if(u&&u.error===void 0&&(u.data===null||u.data===void 0)&&!l&&u.status!=="error"){i.push({queryIndex:c.data.queryIndex,error:"Query resolved without a payload (possible timeout or resource exhaustion) \u2014 retry this query alone, with tighter caps if it was large"});return}o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}else c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function Ur(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function Qr(e){let t=new Set;return e.map((n,r)=>{let o=Ur(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}import Hd from"node:path";import{fileURLToPath as FC}from"node:url";function vC(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 Bd=["path","uri","absolutePath"],Ud=new Set(["next","location"]);function nc(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)nc(i,t,n+1);return}let r=e,o=DC(r);o&&t.push({obj:r,abs:o});for(let[i,s]of Object.entries(r))Ud.has(i)||s&&typeof s=="object"&&nc(s,t,n+1)}function DC(e){let t=e.absolutePath;if(typeof t=="string"&&Hd.isAbsolute(t))return t;let n=e.uri;if(typeof n=="string"&&n.startsWith("file://"))try{return FC(n)}catch{return}let r=e.path;if(typeof r=="string"&&Hd.isAbsolute(r))return r}function Dn(e){let t=[];for(let i of e)nc(i?.data,t,0);if(t.length===0)return;let n=vC(t.map(i=>i.abs));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,abs:s}of t)s.startsWith(r)&&(i.path=s.slice(o),delete i.absolutePath,delete i.uri);return MC(e,r),n}function MC(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(Ud.has(s))continue;let a=i[s];typeof a=="string"?!Bd.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function NC(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 GC(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var HC=new Set([...Bd,"owner","repo","name","id","type","kind","reason"]);function Mn(e){let t=NC(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(HC.has(i))continue;let s=n[i];GC(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}function rc(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(`
29
- `,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 BC(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=rc(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function UC(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=rc(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 oc(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=rc(e,s,i),c=a<o,u=BC(e,s,i),l=UC(e,i),p=e.slice(s,a);return{text:`${c?`# Response page ${u}/${l}. Next: responseCharOffset=${a}
28
+ `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Nt(e,t){let n=Jt(e)??{},r=Ve(n),o=eC(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ai(r,t||i),null,2):O.jsonToYamlString(r,{keysPriority:t||i})}function Ai(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ai(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ai(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ai(n[o],t));return r}var tC=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"]),nC=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"];function rC(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=>tC.has(r))||nC.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Jt(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=>Jt(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(s==="warnings"||rC(a))continue;let c=(s==="files"||s==="repositories")&&!n,u=Jt(a,{inFilesObject:n||c,depth:c?0:r+1});u!==void 0&&(o[s]=u,i=!0)}return i?o:void 0}return e}import{z as ki}from"zod";function _(e,t){return ki.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,ki.number().int().min(e).max(t))}var K=_(1,1e3).optional().default(1),In=_(0,100).optional(),On=_(1,1e9).optional(),oC={responseCharOffset:_(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:_(1,5e4).optional().describe("Full-response char window.")};function Y(e,t={}){let{maxQueries:n=5}=t;return ki.object({queries:ki.array(e).min(1).max(n).describe("Parallel queries."),...oC}).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 ie}from"zod";import{z as j}from"zod";var iC=j.object({currentPage:j.number(),totalPages:j.number(),hasMore:j.boolean(),nextPage:j.number().optional(),pageSize:j.number().optional(),totalItems:j.number().optional(),perPage:j.number().optional(),totalFound:j.number().optional(),returned:j.number().optional(),totalMatches:j.number().optional(),reportedTotalMatches:j.number().optional().describe("Provider-reported raw total (e.g. GitHub's match count) \u2014 may exceed what pagination can actually reach."),reachableTotalMatches:j.number().optional().describe("Matches reachable by walking pages (bounded by the provider's result window, e.g. GitHub caps at 1000); totalPages is computed from this, not from reportedTotalMatches."),totalMatchesKind:j.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:j.boolean().optional(),totalResults:j.number().optional(),itemsPerPage:j.number().optional()}),Z0=j.object({charOffset:j.number(),charLength:j.number(),totalChars:j.number(),hasMore:j.boolean(),nextCharOffset:j.number().optional(),currentPage:j.number().optional(),totalPages:j.number().optional(),chunkMode:j.enum(["semantic","char-limit"]).optional()}),Ja=j.object({tool:j.string(),query:j.record(j.string(),j.unknown()),why:j.string().optional(),confidence:j.enum(["exact","high","medium","low"]).optional()}),eD=iC.extend({filesPerPage:j.number().optional(),entriesPerPage:j.number().optional(),matchesPerPage:j.number().optional(),totalFiles:j.number().optional(),totalEntries:j.number().optional(),totalMatches:j.number().optional(),totalFilesFound:j.number().optional(),nextMatchPage:j.number().optional()}),sC=["id","mainResearchGoal","researchGoal","reasoning"];function aC(e){let t;for(let n of sC)n in e&&(t??={...e},delete t[n]);return t??e}function Fn(e,t,n="Continue to the next page of results."){return{tool:e,query:aC(t),why:n,confidence:"exact"}}function _i(e,t,n,r){if(!n||!n.hasMore||n.nextCharOffset===void 0)return;let o=r?.includeCharLength!==!1;return{continueChars:{tool:e,query:{...t,charOffset:n.nextCharOffset,...o&&n.charLength!==void 0?{charLength:n.charLength}:{}}}}}var cC=ie.object({currentPage:ie.number(),totalPages:ie.number(),hasMore:ie.boolean(),charOffset:ie.number(),charLength:ie.number(),totalChars:ie.number(),nextCharOffset:ie.number().optional()}).optional(),Ed={base:ie.string().optional(),shared:ie.record(ie.string(),ie.union([ie.string(),ie.number(),ie.boolean()])).optional(),responsePagination:cC,next:ie.record(ie.string(),Ja).optional()};function oD(e){return e.extend(Ed)}function uC(e){return ie.object({id:ie.string(),status:ie.enum(["empty","error"]).optional(),data:e,next:ie.record(ie.string(),Ja).optional()})}var iD=uC(ie.record(ie.string(),ie.unknown()).optional()),sD=Ed;function lC(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function F(e,t,n={}){let{extra:r}=n,o={status:"error"};if(lC(e))o.error=e;else if(Es(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=el(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:$(o,n.rawResponse)}function ke(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:F(i,t,{toolName:n.toolName})}}async function mD(e,t,n){if(e)try{await e(t,n)}catch{return}}function se(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:$(s,o.rawResponse)}function Ii(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 F(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function be(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return F(i,t,{toolName:r})}async function Fe({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return be(o,t,r,e)}}import{existsSync as mC,mkdirSync as tc,renameSync as fC,rmSync as hC}from"fs";import{join as Ur}from"path";import{createHash as gC}from"crypto";var yD=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Br=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],vn=[...Br,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Ld=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function Oi(e={},t=Br){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}import{spawn as Za}from"child_process";var pC=10*1024*1024,ec=5e3;function Zt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Br,maxOutputSize:a=pC}=n;return new Promise(c=>{let u={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},l=()=>u.stdoutChunks.join(""),p=()=>u.stderrChunks.join(""),m={cwd:o,env:Oi(i,s),stdio:["ignore","pipe","pipe"]},d;try{d=Za(e,t,m)}catch(y){c({stdout:"",stderr:"",exitCode:null,success:!1,error:y instanceof Error?y:new Error(`Failed to spawn command '${e}'`)});return}let f,g=setTimeout(()=>{if(!u.killed){u.killed=!0;try{d.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{d.kill("SIGKILL")}catch{}},ec),c({stdout:l(),stderr:p(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),R=()=>{clearTimeout(g),f!==void 0&&(clearTimeout(f),f=void 0)},h=()=>{if(u.totalOutputSize>a){if(!u.killed){u.killed=!0;try{d.kill("SIGKILL")}catch{}R(),c({stdout:l(),stderr:p(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};d.stdout?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stdoutChunks.push(S)}),d.stderr?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stderrChunks.push(S)}),d.on("close",y=>{u.killed||(R(),c({stdout:l(),stderr:p(),exitCode:y,success:y===0}))}),d.on("error",y=>{u.killed||(u.killed=!0,R(),c({stdout:l(),stderr:p(),exitCode:null,success:!1,error:y}))})})}function Ad(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Br}=r,a;try{a=Za(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Oi({},s)})}catch{o(!1);return}let c,u=()=>{clearTimeout(l),c!==void 0&&(clearTimeout(c),c=void 0)},l=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},ec),o(!1)}},n);a.on("close",p=>{u(),i||o(p===0)}),a.on("error",()=>{u(),i||o(!1)})})}var dC=1*1024*1024;function PD(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=vn,maxOutputSize:u=dC}=r,l;try{l=Za(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Oi({},c)})}catch{o(null);return}let p,m=()=>{clearTimeout(d),p!==void 0&&(clearTimeout(p),p=void 0)};l.stdout?.on("data",f=>{if(i)return;let g=f.toString();if(a+=Buffer.byteLength(g),a>u){if(!i){i=!0;try{l.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(g)}),l.stderr?.on("data",()=>{});let d=setTimeout(()=>{if(!i){i=!0;try{l.kill("SIGTERM")}catch{}p=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}},ec),o(null)}},n);l.on("close",f=>{if(m(),!i)if(f===0){let g=s.join("").trim();o(g||null)}else o(null)}),l.on("error",()=>{m(),i||o(null)})})}function Fi(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var kd=120*1e3,yC=30*1e3,RC=300*1e3,SC=100,_d="clone-locks",bC="clone-tmp",Id=[...vn,"GIT_TERMINAL_PROMPT"];async function Od(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await kC();let a=e.branch??await Ae(r,o,t),c=zt(),u=ha(c,r,o,a,i);return CC(c,u,async()=>{let l=En(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};pi(c),vt(u);let p=AC(t,n),m=PC(c,u);di(m);try{if(i){if(await LC(r,o,a,m,i,p),!mC(Ur(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await EC(r,o,a,m,p);let d=Ln(r,o,a,"clone",i);return Tn(m,d),wC(m,u),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(d){throw di(m),d}})}async function CC(e,t,n){vt(t);let r=xC(e,t);tc(Ur(e,"tmp",_d),{recursive:!0,mode:448});let o=Date.now();for(;;)try{tc(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>RC)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await TC(SC)}try{return await n()}finally{hC(r,{recursive:!0,force:!0})}}function Fd(e){return gC("sha256").update(e).digest("hex").slice(0,16)}function xC(e,t){return Ur(e,"tmp",_d,Fd(t))}function PC(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Ur(e,"tmp",bC);return tc(r,{recursive:!0,mode:448}),Ur(r,`${Fd(t)}-${n}`)}function wC(e,t){di(t),vt(t),fC(e,t)}function TC(e){return new Promise(t=>setTimeout(t,e))}async function EC(e,t,n,r,o){let i=Dd(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",vd(e,t),r),await nc(i,kd,`full clone of ${e}/${t}`,o)}async function LC(e,t,n,r,o,i){let s=Dd(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",vd(e,t),r),await nc(s,kd,`sparse clone of ${e}/${t}`,i),await nc(["-C",r,"sparse-checkout","set","--skip-checks","--",o],yC,`sparse-checkout set ${o}`,void 0)}function vd(e,t){return`https://github.com/${e}/${t}.git`}function Dd(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function AC(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function kC(){try{if(!(await Zt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Id,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 _C(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 nc(e,t,n,r){let o=await Zt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Id,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=_C(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}import{existsSync as IC,readdirSync as OC,lstatSync as FC}from"node:fs";import{join as vC}from"node:path";function Md(e){if(!IC(e))return 0;let t;try{t=OC(e)}catch{return 0}let n=0;for(let r of t){if(r===".git")continue;let o=vC(e,r);try{let i=FC(o);if(i.isSymbolicLink())continue;i.isDirectory()?n+=hr(o):i.isFile()&&(n+=i.size)}catch{}}return n}async function Nd(e,t={}){if(!Array.isArray(e))throw new Error(tr.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(tr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(tr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,u)=>typeof c=="function"?c:()=>Promise.reject(new Error(rr.NOT_A_FUNCTION.message(u))));if(r<i.length)return DC(i,r,n,o);let s=i.map((c,u)=>Gd(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 Gd(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,u)=>{o=setTimeout(()=>{u(new Error(rr.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 DC(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){o[c]={success:!1,error:new Error(rr.FUNCTION_UNDEFINED.message),index:c};continue}try{let l=await Gd(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}var Hd=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,MC=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,NC=5e3;function Bd(e,t,n){if(e<=1)return Hd;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(MC/o),s=Math.max(NC,Math.min(i,Hd));return n?Math.max(s,n):s}async function Ud(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 Nd(s,{timeout:Bd(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,u)=>{i.push({queryIndex:u,error:c.message})}})).forEach(c=>{if(c.success&&c.data){let u=c.data.result,l=u&&Object.keys(u).some(m=>m!=="status"&&m!=="error"&&m!=="data");if(u&&u.error===void 0&&(u.data===null||u.data===void 0)&&!l&&u.status!=="error"){i.push({queryIndex:c.data.queryIndex,error:"Query resolved without a payload (possible timeout or resource exhaustion) \u2014 retry this query alone, with tighter caps if it was large"});return}o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}else c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function Qr(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function $r(e){let t=new Set;return e.map((n,r)=>{let o=Qr(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}import Qd from"node:path";import{fileURLToPath as GC}from"node:url";function HC(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 $d=["path","uri","absolutePath"],jd=new Set(["next","location"]);function rc(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)rc(i,t,n+1);return}let r=e,o=BC(r);o&&t.push({obj:r,abs:o});for(let[i,s]of Object.entries(r))jd.has(i)||s&&typeof s=="object"&&rc(s,t,n+1)}function BC(e){let t=e.absolutePath;if(typeof t=="string"&&Qd.isAbsolute(t))return t;let n=e.uri;if(typeof n=="string"&&n.startsWith("file://"))try{return GC(n)}catch{return}let r=e.path;if(typeof r=="string"&&Qd.isAbsolute(r))return r}function Dn(e){let t=[];for(let i of e)rc(i?.data,t,0);if(t.length===0)return;let n=HC(t.map(i=>i.abs));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,abs:s}of t)s.startsWith(r)&&(i.path=s.slice(o),delete i.absolutePath,delete i.uri);return UC(e,r),n}function UC(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(jd.has(s))continue;let a=i[s];typeof a=="string"?!$d.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function QC(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 $C(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var jC=new Set([...$d,"owner","repo","name","id","type","kind","reason"]);function Mn(e){let t=QC(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(jC.has(i))continue;let s=n[i];$C(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}function oc(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(`
29
+ `,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 zC(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=oc(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function WC(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=oc(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 ic(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=oc(e,s,i),c=a<o,u=zC(e,s,i),l=WC(e,i),p=e.slice(s,a);return{text:`${c?`# Response page ${u}/${l}. Next: responseCharOffset=${a}
30
30
  `:`# Response page ${u}/${l}.
31
- `}${p}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function ic(e,t){return t?{...e,responsePagination:t}:e}var QC=3;async function te(e,t,n,r){let o=n.concurrency??QC,{results:i,errors:s}=await Gd(e,t,o,n.minQueryTimeoutMs);return $C(n,i,s,e,r)}function $C(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),u=Qr(r);t.forEach(R=>{let h=R.result.status;c[R.queryIndex]={id:u[R.queryIndex]??Ur(R.originalQuery,R.queryIndex),...h!==void 0?{status:h}:{},data:jC(R.result)}}),n.forEach(R=>{let h=r[R.queryIndex];h&&(c[R.queryIndex]={id:u[R.queryIndex]??Ur(h,R.queryIndex),status:"error",data:{error:R.error}})});let l=c.filter(R=>R!==void 0);if(e.finalize){let R=e.finalize({queries:r,results:l,config:e}),h=oc(R.text,o),y=ic(R.structuredContent,h.pagination);return Qd(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:y,isError:R.isError??(l.length>0&&l.every(C=>C.status==="error"))}}let p={results:l};if(Array.isArray(p.results)){let R=Dn(p.results);R&&(p.base=R);let h=Mn(p.results);h&&(p.shared=h)}let m=Nt(p,a),d=oc(m,o),f=ic(Ve(Jt(p)??{}),d.pagination);return Qd(e.toolName,t,n,d.text.length),{content:[{type:"text",text:d.text}],structuredContent:f,isError:l.length>0&&l.every(R=>R.status==="error")}}function Qd(e,t,n,r){let o=t.reduce((i,s)=>i+(ne(s.result)??N(s.result)),0)+n.reduce((i,s)=>i+N(s),0);try{ei(e,o,r)}catch{}}function jC(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 Fi(e){return e.data!==void 0&&!e.error}function zC(e){return e.error!==void 0}import{maskSensitiveData as $d}from"@octocodeai/octocode-engine/mask";var sc=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function WC(){return zs().provider??js()}function VC(e){let t=zs(),n=t.provider??js(),{baseUrl:r,token:o}=t;try{let i=Xa(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=$d(s);throw new sc(n,`Failed to initialize ${n} provider: ${a}`)}}function Be(e){let t;return()=>t??=VC(e)}function vi(e,t){return e.capabilities[t]}async function ft(e,t){let n=await t();return Fi(n)?{ok:!0,response:n}:{ok:!1,result:ki(n,e)}}async function jd(e,t){let n=t??WC(),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:$d(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Fi(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}async function zd(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>Fe({toolName:x.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!vi(s,"cloneRepo"))return be(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",x.GITHUB_CLONE_REPO);let a;try{a=await _d(o,n,s.token)}catch(m){let d=m instanceof Error?m.message:String(m);return F(`Clone failed for ${o.owner}/${o.repo}: ${d}`,o)}let c=Fd(a.localPath),u={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},l={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},p={owner:o.owner,repo:o.repo,totalSize:c,location:u,next:l};return se(o,p,!0,x.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:x.GITHUB_CLONE_REPO,keysPriority:["totalSize","location","error"]},e)}import{CloneRepoQuerySchema as XC}from"@octocodeai/octocode-core/schemas";import{z as Wd}from"zod";function KC(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Vd(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=KC(e.shape[r],o);return n}function YC(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Kd(e,t){if(!t?.length)return e;let n=new Set(t);return Wd.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function Y(e,t={},n={}){let r=Kd(e,n.omit),o=YC(r,Vd(r,t));return n.strict?o.strict():o}function Z(e,t={},n={}){let r=Kd(e,n.omit),o=Wd.object({...r.shape,...Vd(r,t)});return n.strict?o.strict():o}var Nn=Y(XC),$r=K(Nn);import{z as qC}from"zod";import{FileContentQuerySchema as Yd}from"@octocodeai/octocode-core/schemas";var JC=qC.enum(["none","standard","symbols"]).optional(),Xd={startLine:On,endLine:On,contextLines:In,charOffset:I(0,1e8).optional(),charLength:I(1,5e4).optional(),minify:JC},ZC=Z(Yd,Xd),en=Y(Yd,Xd),jr=K(ZC);function Di(e,t){return e&&t?`${e}/${t}`:void 0}function Mi(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Ni(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 ex(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 qd(e){return{keywords:e.keywords??[],projectId:Di(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 Jd(e,t){let n=t.match==="path",r=new Map;for(let i of e.items){let s=i.repository.name||"",{owner:a,repo:c}=Mi(s),u=`${a}/${c}`,l=r.get(u);if(l||(l={id:u,owner:a,repo:c,matches:[]},r.set(u,l)),n||!i.matches?.length){l.matches.push({path:i.path,...n?{}:{pathOnly:!0}});continue}let p=!1;for(let m of i.matches){if(!m.context)continue;let d=ex(m.context),f={path:i.path,value:d};if(m.positions?.length>0){let g=m.positions.filter(([,R])=>R<=d.length);g.length>0&&(f.matchIndices=g.map(([R,h])=>({start:R,end:h,lineOffset:(m.context??"").substring(0,R).split(`
32
- `).length-1})))}l.matches.push(f),p=!0}p||l.matches.push({path:i.path,pathOnly:!0})}let o={results:Array.from(r.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(o.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Ni(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),o}function Zd(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,license:t.license,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function em(e){return e.map(t=>{let{owner:n,repo:r}=Mi(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function Gi(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function tm(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Gi),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Di(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,draft:e.draft,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,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 tx(e,t){let n=[];t.some(o=>o.state==="APPROVED")&&n.push("approval"),t.some(o=>o.state==="CHANGES_REQUESTED")&&n.push("changes-requested");let r=e.filter(o=>!qt(o.author??"")).map(o=>o.body.toLowerCase());return n.length===0&&r.some(o=>/\b(lgtm|looks good|approved|ship it)\b/.test(o))&&n.push("approval"),!n.includes("changes-requested")&&r.some(o=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(o))&&n.push("changes-requested"),r.some(o=>o.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function nx(e,t){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(i=>i.author))),r=e.map(i=>i.updatedAt||i.createdAt).filter(Boolean).sort().at(-1),o=e.filter(i=>i.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:o,discussionComments:e.length-o,commenters:n.slice(0,8),...r?{latestCommentAt:r}:{},themes:tx(e,t??[])}}function nm(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,u=nx(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(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}:{},...Ni(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pullRequests:r,...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},...o?{pagination:o}:{totalCount:e.totalCount||r.length}},pagination:o}}function rm(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 om(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.matchedLines?.length&&{matchedLines:e.matchedLines},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function ac(e,t){let n=e.include??[];return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Mt.ENTRIES_PER_PAGE,page:(()=>{let r=e.page;return typeof r=="number"?r:void 0})(),includeSizes:n.includes("sizes"),includeLanguages:n.includes("languages"),includeContributors:n.includes("contributors"),includeBranches:n.includes("branches"),includeTags:n.includes("tags"),mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function im(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[f])=>d==="."?-1:f==="."?1:d.localeCompare(f)).map(([d,f])=>({dir:d,files:f.files,folders:f.folders})),c=e.fileSizeMap,u={};if(c){for(let[d,f]of Object.entries(c))if(n[d]){let g=new Set(n[d].files);for(let[R,h]of Object.entries(f))if(g.has(R)){let y=d==="."?R:`${d}/${R}`;u[y]=h}}}let l=Object.values(n).reduce((d,f)=>(d.totalFiles+=f.files.length,d.totalFolders+=f.folders.length,d),{totalFiles:0,totalFolders:0}),p=e,m={structure:a,...Object.keys(u).length>0&&{fileSizes:u},...p.languages?{languages:p.languages,dominantLanguage:p.dominantLanguage}:{},...p.contributors?{contributors:p.contributors,totalContributors:p.contributors.length}:{},...p.branches?{branches:p.branches,totalBranches:p.branches.length}:{},...p.tags?{tags:p.tags,totalTags:p.tags.length}:{},summary:{totalFiles:l.totalFiles,totalFolders:l.totalFolders}};return i&&(m.resolvedBranch=i),s&&(m.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)&&(m.pagination=e.pagination),m}function Hi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function rx(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:Hi(t.status),retryAfterSeconds:Hi(t.retryAfter),rateLimitRemaining:Hi(t.rateLimitRemaining),rateLimitReset:Hi(t.rateLimitReset)}}return{message:"Provider error"}}function Bi(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=rx(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function Ui(e,t,n){let r=t,o=e.results;if(Array.isArray(o)){let s=o,a=Dn(s);a&&(e.base=a);let c=Mn(s);c&&(e.shared=c),(a||c)&&(r=[...a?["base"]:[],...c?["shared"]:[],...t])}let i=Nt(e,[...r]);return{structuredContent:Ve(Jt(e)??{}),text:i,isError:n}}function Qi(e){return typeof e=="object"&&e!==null}function Ue(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function sm(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function Ke(e,t){return Ye(e[t])??0}function ox(e){if(Qi(e))return{nonFile:Ke(e,"nonFile"),missingDownloadUrl:Ke(e,"missingDownloadUrl"),oversized:Ke(e,"oversized"),binary:Ke(e,"binary"),fileLimit:Ke(e,"fileLimit"),fetchFailed:Ke(e,"fetchFailed"),totalSizeLimit:Ke(e,"totalSizeLimit"),pathTraversal:Ke(e,"pathTraversal")}}function ix(e){if(Qi(e))return{maxDirectoryFiles:Ke(e,"maxDirectoryFiles"),maxTotalSize:Ke(e,"maxTotalSize"),maxFileSize:Ke(e,"maxFileSize")}}var sx=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function ax(e){if(!Qi(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 sx){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function cx(e,t){return _i("ghGetFileContent",{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,...t.minify!==void 0?{minify:t.minify}:{}},e)}function ux(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"lspGetSemantics (definitions/references) only works on local files \u2014 clone this path locally, then run localSearchCode or lspGetSemantics on it",confidence:"exact"}}function am(e,t){let n=ax(e.pagination),r=!1;try{r=ql()}catch{r=!1}let o={...cx(n,t),...r?{cloneForSemantics:ux(t)}:{}};return{path:Ue(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:Ue(e.localPath),repoRoot:Ue(e.repoRoot),contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:Ye(e.totalLines),sourceChars:Ye(e.sourceChars),resolvedBranch:Ue(e.resolvedBranch),pagination:n,...Object.keys(o).length>0?{next:o}:{},...e.isPartial===!0||n?.hasMore===!0?{isPartial:!0}:{},startLine:Ye(e.startLine),endLine:Ye(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},...Array.isArray(e.matchedLines)&&e.matchedLines.length>0?{matchedLines:e.matchedLines}:{},lastModified:Ue(e.lastModified),lastModifiedBy:Ue(e.lastModifiedBy),warnings:sm(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Ue(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function cm(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Qi).map(c=>({path:Ue(c.path)??"",size:Ye(c.size)??0,type:Ue(c.type)??"file"})),o=ox(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:Ue(e.localPath)??"",repoRoot:Ue(e.repoRoot),fileCount:Ye(e.fileCount)??r.length,totalSize:Ye(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ye(e.directoryEntryCount),eligibleFileCount:Ye(e.eligibleFileCount),savedFileCount:Ye(e.savedFileCount),skipped:o,limits:ix(e.limits),warnings:sm(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Ue(e.resolvedBranch)}}function lx(e,t){return`${e}/${t}`}function px(e,t,n){let r=lx(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 dx(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=px(n,i,s),c=r.data;if(o.type==="directory"){let l=a.directories??[];l.push(cm(c,o)),a.directories=l;return}let u=a.files??[];u.push(am(c,o)),a.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function mx(e,t){return Bi(e).map(r=>{let o=t.get(r.id),s=/\b404\b|not found/i.test(r.error)&&o?.owner&&o?.repo?`${r.error} \u2014 verify the path (exact case, no leading slash) and the branch (a bad ref also 404s); list the tree with ghViewRepoStructure(owner:"${o.owner}", repo:"${o.repo}")`:r.error;return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:s}})}function um(){return({queries:e,results:t})=>{let n=new Map,r=Qr(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=dx(t,n),i=mx(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Ui(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}async function lm(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{let s=_e(en,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=a.minify??(a.fullContent===!0?"none":"standard"),u={...a,minify:c},l=r();return u.type==="directory"?fx(u,n,l):hx(u,n,l)}catch(s){return be(s,o,void 0,x.GITHUB_FETCH_CONTENT)}},{toolName:x.GITHUB_FETCH_CONTENT,finalize:um()},e)}async function fx(e,t,n){if(!vi(n,"fetchDirectoryToDisk"))return be(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",x.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return F("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Ae(e.owner,e.repo,t),o=await ga(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,l])=>l>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return se(e,u,!0,x.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??N(o)})}async function hx(e,t,n){let r=await ft(e,()=>n.provider.getFileContent(rm(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await gx(e,t):void 0,i={...om(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return se(e,i,s,x.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function gx(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ae(e.owner,e.repo,t);return wa(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function zr(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function pm(e,t){let n=zr(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function dm(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{},...t?.repoState?{repoState:t.repoState}:{}}}function yx(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function Rx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sx(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${Rx(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function bx(e,t){return{...e,matches:t}}function cc(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?yx(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:Sx(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:bx(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 fm(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 mm(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function hm(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:mm(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:mm(r.get(i)),...s?{pagination:s}:{}}}})}function gm(e,t,n){let r=zr(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),u=(Array.isArray(a?.keywords)?a.keywords.filter(p=>typeof p=="string"):[])[0]??n[0];if(!u)continue;let l=e.length===1?"getLines":`getLines:${i.id}`;o[l]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:u},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"low"}}return Object.keys(o).length>0?o:void 0}function uc(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=zr(e);t.forEach((S,C)=>{if(S.status==="error")return;let P=dm(S);P.repoState&&s.push({id:S.id,state:P.repoState,query:a.get(S.id)}),P.incompleteResults&&(i=!0),P.results.reduce((_,w)=>_+w.matches.length,0)===0&&o.push({id:S.id,...P.nonExistentScope?{nonExistentScope:!0}:{},...P.incompleteResults?{incompleteResults:!0}:{}});let L=P.results;n.push({id:S.id,groups:L}),P.pagination&&r.set(S.id,P.pagination)});let c=Array.from(new Set(e.flatMap(S=>{let C=S.keywords;return Array.isArray(C)?C.filter(P=>typeof P=="string"):[]}))),u=cc(fm(n),c),l=Bi(t),p=e.some(S=>S.concise===!0),m=hm(e,u,r),d=gm(m,e,c);if(p)for(let S of m)S.data.files=S.data.files.map(C=>`${C.owner}/${C.repo}:${C.path}`);let f={results:m,...d?{next:d}:{}};o.length>0&&(f.emptyQueries=o.map(({id:S,nonExistentScope:C,incompleteResults:P})=>({id:S,...C?{nonExistentScope:C}:{},...P?{incompleteResults:P}:{}}))),l.length>0&&(f.errors=l);let g=[],R=(S,C)=>{g.push(C)};i&&R("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&pm(o,e)&&R("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let h=8,y=o.filter(({id:S,nonExistentScope:C,incompleteResults:P})=>{if(C||P)return!1;let T=a.get(S)?.keywords;return Array.isArray(T)&&T.length>h});y.length>0&&R("ghQueryPossiblyTooComplex",`Quer${y.length>1?"ies":"y"} ${y.map(S=>S.id).join(", ")} used more than ${h} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:S,state:C,query:P}of s)if(C.kind==="renamed"){let[T,L]=C.fullName.split("/");R("ghRepoRenamed",`Query ${S}: the repository was RENAMED to ${C.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let _=P?.keywords;f.next={...f.next??{},[`retryRenamed:${S}`]:{tool:"ghSearchCode",query:{owner:T,repo:L,...Array.isArray(_)?{keywords:_}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else C.kind==="archived"?R("ghRepoArchived",`Query ${S}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):R("ghRepoNotFound",`Query ${S}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`);return Ui(f,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","errors"],u.length===0&&l.length>0)}}function Cx(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function xx(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 Px(e,t,n){try{let r=await Q(n),{data:o}=await r.rest.repos.get({owner:e,repo:t}),i=`${e}/${t}`.toLowerCase();return o.full_name&&o.full_name.toLowerCase()!==i?{kind:"renamed",fullName:o.full_name}:o.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function ym(e){let{queries:t}=e,n=Be(e.authInfo);return te(t,async(r,o)=>{try{let i=xx(r);if(i)return F(i.error,r);if(!Cx(r))return F("At least one search term or scope filter is required.",r);let s=n(),a=await ft(r,()=>s.provider.searchCode(qd(r)));if(a.ok===!1)return a.result;let c=Jd(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let u=await Px(String(r.owner),String(r.repo),e.authInfo);u&&(c.repoState=u)}return se(r,c,c.results.length>0,x.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return be(i,r,void 0,x.GITHUB_SEARCH_CODE)}},{toolName:x.GITHUB_SEARCH_CODE,finalize:uc()},e)}import{z as wx}from"zod";import{GitHubCodeSearchQuerySchema as Rm}from"@octocodeai/octocode-core/schemas";var Sm={limit:I(1,100).optional(),page:q.default(1),match:wx.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghSearchPullRequests, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},Wr=Y(Rm,Sm),Vr=K(Z(Rm,Sm));function Tx(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 Ex(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 Lx(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function bm(e){let{content:t,reviewMode:n}=e,r=Tx(t,n),o=Ex(t,n),i=Lx(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 AN(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function Kr(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Gn(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Yr(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 tn(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 $i(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function lc(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function Ax(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Xr(e,t,n){return Ax({...lc(e,t),...n})}function pc(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Xr(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function ji(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Xr(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Hn(e){return typeof e=="object"&&e!==null}function zi(e){if(Hn(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Wi(e){if(Hn(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function _x(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 Cm(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=_x(r,n.comments),i=Kr(t),s=i?o.filter(u=>Gn(u.body,i)):o,{items:a,pagination:c}=Yr(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(u=>{let l=tn(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:$i(typeof u.body=="string"?u.body:"")},createdAt:u.createdAt,updatedAt:u.updatedAt}}),commentPagination:c}}function xm(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Kr(t);return{reviews:(o?r.filter(s=>Gn(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=tn(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 Pm(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Yr(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 Vi(e){return String(e.path??e.filename??"")}function kx(e,t){return{path:Vi(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function Ix(e){return e.split(`
33
- `).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(`
34
- `)}function wm(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(d=>i.includes(Vi(d))):o,a=Kr(t),c=a?s.filter(d=>Gn(Vi(d),a)||Gn(d.patch,a)):s,{items:u,pagination:l}=Yr(c,t.filePage??t.page??1,t.itemsPerPage??20),p=n.patches.mode!=="none",m=u.map(d=>{let f=kx(d,!1);if(!p||typeof d.patch!="string")return f;let g=r&&!a?Ix(d.patch):d.patch,R=tn(g,t.charOffset??0,t.charLength??12e3);return{...f,patch:R?.content??"",...R?{patchPagination:R.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:l}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(Vi).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function nn(e,t){return{...e,content:t}}function Ox(e,t){return{...e,...t}}function Tm(e,t,n,r){let o=lc(e,t);return{target:o,...n.body?{}:{getBody:nn(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:nn(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:nn(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:nn(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:nn(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:nn(o,{reviews:!0})},...n.commits?{}:{getCommits:nn(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:Ox(o,{reviewMode:"full"})}}}function Fx(e){return e.replace(/\n{3,}/g,`
31
+ `}${p}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function sc(e,t){return t?{...e,responsePagination:t}:e}var VC=3;async function te(e,t,n,r){let o=n.concurrency??VC,{results:i,errors:s}=await Ud(e,t,o,n.minQueryTimeoutMs);return KC(n,i,s,e,r)}function KC(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),u=$r(r);t.forEach(R=>{let h=R.result.status;c[R.queryIndex]={id:u[R.queryIndex]??Qr(R.originalQuery,R.queryIndex),...h!==void 0?{status:h}:{},data:YC(R.result)}}),n.forEach(R=>{let h=r[R.queryIndex];h&&(c[R.queryIndex]={id:u[R.queryIndex]??Qr(h,R.queryIndex),status:"error",data:{error:R.error}})});let l=c.filter(R=>R!==void 0);if(e.finalize){let R=e.finalize({queries:r,results:l,config:e}),h=ic(R.text,o),y=sc(R.structuredContent,h.pagination);return zd(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:y,isError:R.isError??(l.length>0&&l.every(C=>C.status==="error"))}}let p={results:l};if(Array.isArray(p.results)){let R=Dn(p.results);R&&(p.base=R);let h=Mn(p.results);h&&(p.shared=h)}let m=Nt(p,a),d=ic(m,o),f=sc(Ve(Jt(p)??{}),d.pagination);return zd(e.toolName,t,n,d.text.length),{content:[{type:"text",text:d.text}],structuredContent:f,isError:l.length>0&&l.every(R=>R.status==="error")}}function zd(e,t,n,r){let o=t.reduce((i,s)=>i+(ne(s.result)??N(s.result)),0)+n.reduce((i,s)=>i+N(s),0);try{ti(e,o,r)}catch{}}function YC(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 vi(e){return e.data!==void 0&&!e.error}function XC(e){return e.error!==void 0}import{maskSensitiveData as Wd}from"@octocodeai/octocode-engine/mask";var ac=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function qC(){return Vs().provider??Ws()}function JC(e){let t=Vs(),n=t.provider??Ws(),{baseUrl:r,token:o}=t;try{let i=qa(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=Wd(s);throw new ac(n,`Failed to initialize ${n} provider: ${a}`)}}function Be(e){let t;return()=>t??=JC(e)}function Di(e,t){return e.capabilities[t]}async function ft(e,t){let n=await t();return vi(n)?{ok:!0,response:n}:{ok:!1,result:Ii(n,e)}}async function Vd(e,t){let n=t??qC(),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:Wd(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)vi(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}async function Kd(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>Fe({toolName:x.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Di(s,"cloneRepo"))return be(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",x.GITHUB_CLONE_REPO);let a;try{a=await Od(o,n,s.token)}catch(m){let d=m instanceof Error?m.message:String(m);return F(`Clone failed for ${o.owner}/${o.repo}: ${d}`,o)}let c=Md(a.localPath),u={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},l={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},p={owner:o.owner,repo:o.repo,totalSize:c,location:u,next:l};return se(o,p,!0,x.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:x.GITHUB_CLONE_REPO,keysPriority:["totalSize","location","error"]},e)}import{CloneRepoQuerySchema as tx}from"@octocodeai/octocode-core/schemas";import{z as Yd}from"zod";function ZC(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Xd(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=ZC(e.shape[r],o);return n}function ex(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function qd(e,t){if(!t?.length)return e;let n=new Set(t);return Yd.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function X(e,t={},n={}){let r=qd(e,n.omit),o=ex(r,Xd(r,t));return n.strict?o.strict():o}function Z(e,t={},n={}){let r=qd(e,n.omit),o=Yd.object({...r.shape,...Xd(r,t)});return n.strict?o.strict():o}var Nn=X(tx),jr=Y(Nn);import{z as nx}from"zod";import{FileContentQuerySchema as Jd}from"@octocodeai/octocode-core/schemas";var rx=nx.enum(["none","standard","symbols"]).optional(),Zd={startLine:On,endLine:On,contextLines:In,charOffset:_(0,1e8).optional(),charLength:_(1,5e4).optional(),minify:rx},ox=Z(Jd,Zd),en=X(Jd,Zd),zr=Y(ox);function Mi(e,t){return e&&t?`${e}/${t}`:void 0}function Ni(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Gi(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function ix(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 em(e){return{keywords:e.keywords??[],projectId:Mi(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 tm(e,t){let n=t.match==="path",r=new Map;for(let i of e.items){let s=i.repository.name||"",{owner:a,repo:c}=Ni(s),u=`${a}/${c}`,l=r.get(u);if(l||(l={id:u,owner:a,repo:c,matches:[]},r.set(u,l)),n||!i.matches?.length){l.matches.push({path:i.path,...n?{}:{pathOnly:!0}});continue}let p=!1;for(let m of i.matches){if(!m.context)continue;let d=ix(m.context),f={path:i.path,value:d};if(m.positions?.length>0){let g=m.positions.filter(([,R])=>R<=d.length);g.length>0&&(f.matchIndices=g.map(([R,h])=>({start:R,end:h,lineOffset:(m.context??"").substring(0,R).split(`
32
+ `).length-1})))}l.matches.push(f),p=!0}p||l.matches.push({path:i.path,pathOnly:!0})}let o={results:Array.from(r.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(o.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Gi(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),o}function nm(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,license:t.license,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function rm(e){return e.map(t=>{let{owner:n,repo:r}=Ni(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function Hi(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function om(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Hi),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Mi(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,draft:e.draft,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,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 sx(e,t){let n=[];t.some(o=>o.state==="APPROVED")&&n.push("approval"),t.some(o=>o.state==="CHANGES_REQUESTED")&&n.push("changes-requested");let r=e.filter(o=>!qt(o.author??"")).map(o=>o.body.toLowerCase());return n.length===0&&r.some(o=>/\b(lgtm|looks good|approved|ship it)\b/.test(o))&&n.push("approval"),!n.includes("changes-requested")&&r.some(o=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(o))&&n.push("changes-requested"),r.some(o=>o.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function ax(e,t){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(i=>i.author))),r=e.map(i=>i.updatedAt||i.createdAt).filter(Boolean).sort().at(-1),o=e.filter(i=>i.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:o,discussionComments:e.length-o,commenters:n.slice(0,8),...r?{latestCommentAt:r}:{},themes:sx(e,t??[])}}function im(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,u=ax(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(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}:{},...Gi(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pullRequests:r,...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},...o?{pagination:o}:{totalCount:e.totalCount||r.length}},pagination:o}}function sm(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 am(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.matchedLines?.length&&{matchedLines:e.matchedLines},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function cc(e,t){let n=e.include??[];return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Mt.ENTRIES_PER_PAGE,page:(()=>{let r=e.page;return typeof r=="number"?r:void 0})(),includeSizes:n.includes("sizes"),includeLanguages:n.includes("languages"),includeContributors:n.includes("contributors"),includeBranches:n.includes("branches"),includeTags:n.includes("tags"),mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function cm(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[f])=>d==="."?-1:f==="."?1:d.localeCompare(f)).map(([d,f])=>({dir:d,files:f.files,folders:f.folders})),c=e.fileSizeMap,u={};if(c){for(let[d,f]of Object.entries(c))if(n[d]){let g=new Set(n[d].files);for(let[R,h]of Object.entries(f))if(g.has(R)){let y=d==="."?R:`${d}/${R}`;u[y]=h}}}let l=Object.values(n).reduce((d,f)=>(d.totalFiles+=f.files.length,d.totalFolders+=f.folders.length,d),{totalFiles:0,totalFolders:0}),p=e,m={structure:a,...Object.keys(u).length>0&&{fileSizes:u},...p.languages?{languages:p.languages,dominantLanguage:p.dominantLanguage}:{},...p.contributors?{contributors:p.contributors,totalContributors:p.contributors.length}:{},...p.branches?{branches:p.branches,totalBranches:p.branches.length}:{},...p.tags?{tags:p.tags,totalTags:p.tags.length}:{},summary:{totalFiles:l.totalFiles,totalFolders:l.totalFolders}};return i&&(m.resolvedBranch=i),s&&(m.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)&&(m.pagination=e.pagination),m}function Bi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function cx(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:Bi(t.status),retryAfterSeconds:Bi(t.retryAfter),rateLimitRemaining:Bi(t.rateLimitRemaining),rateLimitReset:Bi(t.rateLimitReset)}}return{message:"Provider error"}}function Ui(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=cx(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function Qi(e,t,n){let r=t,o=e.results;if(Array.isArray(o)){let s=o,a=Dn(s);a&&(e.base=a);let c=Mn(s);c&&(e.shared=c),(a||c)&&(r=[...a?["base"]:[],...c?["shared"]:[],...t])}let i=Nt(e,[...r]);return{structuredContent:Ve(Jt(e)??{}),text:i,isError:n}}var ux=["package.json",".yarnrc.yml","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","turbo.json","lerna.json","nx.json","babel.config.js","vite.config.ts","vite.config.js","webpack.config.js","rollup.config.js","jest.config.js","vitest.config.ts","commitlint.config.js","deno.json","deno.jsonc",".npmrc",".nvmrc",".node-version",".prettierrc",".prettierignore",".eslintignore",".stylelintrc",".editorconfig",".tool-versions","requirements.txt","pyproject.toml","setup.py","setup.cfg","Pipfile","tox.ini","environment.yml",".python-version","Gemfile",".ruby-version","composer.json","Cargo.toml","go.mod","go.work","mix.exs","rebar.config","pubspec.yaml","build.sbt","deps.edn","project.clj","Package.swift","CMakeLists.txt","Makefile.am","configure.ac","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","global.json","Directory.Build.props","Directory.Build.targets","packages.config","nuget.config","Dockerfile","docker-compose.yml","docker-compose.yaml",".dockerignore","Makefile","Vagrantfile","Chart.yaml","Procfile","Brewfile","serverless.yml","netlify.toml","vercel.json","renovate.json",".gitlab-ci.yml",".travis.yml","Jenkinsfile",".gitignore",".gitattributes",".gitmodules",".env",".env.example"],lx=new Set(ux),px=["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","deno.lock","Pipfile.lock","poetry.lock","uv.lock","pdm.lock","pixi.lock","Gemfile.lock","composer.lock","Cargo.lock","Cargo.toml.orig","go.sum","Gopkg.lock","glide.lock","Package.resolved","pubspec.lock","flake.lock","MODULE.bazel.lock",".terraform.lock.hcl","mise.lock"],dx=new Set(px),mx=[/\.lock$/],fx=[/^\.eslintrc(\..+)?$/,/^\.prettierrc(\..+)?$/,/^\.babelrc(\..+)?$/,/^eslint\.config\.(c|m)?js$/,/^\.env(\..+)?$/,/^tsconfig\..+\.json$/,/^\.stylelintrc(\..+)?$/,/^\.renovaterc(\..+)?$/,/\.csproj$/,/\.fsproj$/,/\.vbproj$/,/\.sln$/,/\.gemspec$/,/\.tf(vars)?$/],hx=[".toml",".ini",".cfg",".conf",".properties"],lm=new Set(hx),gx=new Set(".md .mdx .markdown .rst .adoc .asciidoc .txt .text .rtf .org .textile .rdoc .pod .creole .wiki".split(" ")),um=new Set(["readme","license","licence","copying","notice","changelog","changes","history","authors","contributors","contributing","code_of_conduct","codeowners","install","citation"]),pm=new Set(".js .jsx .mjs .cjs .ts .tsx .mts .cts .py .pyi .pyx .rb .rake .php .go .rs .java .kt .kts .scala .groovy .clj .cljs .cljc .c .h .cc .cpp .cxx .hpp .hh .m .mm .cs .fs .vb .swift .dart .sh .bash .zsh .fish .ps1 .bat .cmd .vue .svelte .css .scss .sass .less .html .htm .sql .graphql .gql .proto .ex .exs .erl .lua .hs .pl .pm .r .jl".split(" "));function uc(e){let t=e.replace(/\\/g,"/"),n=t.lastIndexOf("/");return n===-1?t:t.slice(n+1)}function lc(e){let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""}function yx(e){if(!e)return!1;let t=uc(e);if(!t)return!1;if(lx.has(t))return!0;for(let r of fx)if(r.test(t))return!0;let n=lc(t);return!!(n&&lm.has(n))}function Rx(e){if(!e)return!1;let t=uc(e);if(!t)return!1;if(dx.has(t))return!0;for(let n of mx)if(n.test(t))return!0;return!1}function Sx(e){let t=lc(e);if(t&&gx.has(t))return!0;if(t&&(pm.has(t)||lm.has(t)))return!1;let n=(t?e.slice(0,e.length-t.length):e).toLowerCase().replace(/\..*$/,""),r=n.split(/[-_.]/)[0]??n;return um.has(n)||um.has(r)}function bx(e){let t=lc(e);return t!==""&&pm.has(t)}function $i(e){if(!e)return;let t=uc(e);if(t){if(Rx(t))return"lock";if(yx(t))return"config";if(Sx(t))return"doc";if(bx(t))return"code"}}function ji(e){return typeof e=="object"&&e!==null}function Ue(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function dm(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function Ke(e,t){return Ye(e[t])??0}function Cx(e){if(ji(e))return{nonFile:Ke(e,"nonFile"),missingDownloadUrl:Ke(e,"missingDownloadUrl"),oversized:Ke(e,"oversized"),binary:Ke(e,"binary"),fileLimit:Ke(e,"fileLimit"),fetchFailed:Ke(e,"fetchFailed"),totalSizeLimit:Ke(e,"totalSizeLimit"),pathTraversal:Ke(e,"pathTraversal")}}function xx(e){if(ji(e))return{maxDirectoryFiles:Ke(e,"maxDirectoryFiles"),maxTotalSize:Ke(e,"maxTotalSize"),maxFileSize:Ke(e,"maxFileSize")}}var Px=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function wx(e){if(!ji(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 Px){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Tx(e,t){return _i("ghGetFileContent",{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,...t.minify!==void 0?{minify:t.minify}:{}},e)}function Ex(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"lspGetSemantics (definitions/references) only works on local files \u2014 clone this path locally, then run localSearchCode or lspGetSemantics on it",confidence:"exact"}}function mm(e,t){let n=wx(e.pagination),r=!1;try{r=ep()}catch{r=!1}let o={...Tx(n,t),...r?{cloneForSemantics:Ex(t)}:{}},i=Ue(e.path)??String(t.path??""),s=i?$i(i):void 0;return{path:i,content:typeof e.content=="string"?e.content:"",...s?{fileType:s}:{},localPath:Ue(e.localPath),repoRoot:Ue(e.repoRoot),contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:Ye(e.totalLines),sourceChars:Ye(e.sourceChars),resolvedBranch:Ue(e.resolvedBranch),pagination:n,...Object.keys(o).length>0?{next:o}:{},...e.isPartial===!0||n?.hasMore===!0?{isPartial:!0}:{},startLine:Ye(e.startLine),endLine:Ye(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},...Array.isArray(e.matchedLines)&&e.matchedLines.length>0?{matchedLines:e.matchedLines}:{},lastModified:Ue(e.lastModified),lastModifiedBy:Ue(e.lastModifiedBy),warnings:dm(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Ue(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function fm(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(ji).map(c=>({path:Ue(c.path)??"",size:Ye(c.size)??0,type:Ue(c.type)??"file"})),o=Cx(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:Ue(e.localPath)??"",repoRoot:Ue(e.repoRoot),fileCount:Ye(e.fileCount)??r.length,totalSize:Ye(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ye(e.directoryEntryCount),eligibleFileCount:Ye(e.eligibleFileCount),savedFileCount:Ye(e.savedFileCount),skipped:o,limits:xx(e.limits),warnings:dm(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Ue(e.resolvedBranch)}}function Lx(e,t){return`${e}/${t}`}function Ax(e,t,n){let r=Lx(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 kx(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=Ax(n,i,s),c=r.data;if(o.type==="directory"){let l=a.directories??[];l.push(fm(c,o)),a.directories=l;return}let u=a.files??[];u.push(mm(c,o)),a.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function _x(e,t){return Ui(e).map(r=>{let o=t.get(r.id),s=/\b404\b|not found/i.test(r.error)&&o?.owner&&o?.repo?`${r.error} \u2014 verify the path (exact case, no leading slash) and the branch (a bad ref also 404s); list the tree with ghViewRepoStructure(owner:"${o.owner}", repo:"${o.repo}")`:r.error;return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:s}})}function hm(){return({queries:e,results:t})=>{let n=new Map,r=$r(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=kx(t,n),i=_x(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Qi(s,["results","id","owner","repo","files","directories","path","content","fileType","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}async function gm(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{let s=ke(en,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=a.minify??(a.fullContent===!0?"none":"standard"),u={...a,minify:c},l=r();return u.type==="directory"?Ix(u,n,l):Ox(u,n,l)}catch(s){return be(s,o,void 0,x.GITHUB_FETCH_CONTENT)}},{toolName:x.GITHUB_FETCH_CONTENT,finalize:hm()},e)}async function Ix(e,t,n){if(!Di(n,"fetchDirectoryToDisk"))return be(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",x.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return F("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Ae(e.owner,e.repo,t),o=await Ra(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,l])=>l>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return se(e,u,!0,x.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??N(o)})}async function Ox(e,t,n){let r=await ft(e,()=>n.provider.getFileContent(sm(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await Fx(e,t):void 0,i={...am(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return se(e,i,s,x.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function Fx(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ae(e.owner,e.repo,t);return Ea(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function Wr(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function ym(e,t){let n=Wr(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function Rm(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{},...t?.repoState?{repoState:t.repoState}:{}}}function vx(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function Dx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mx(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${Dx(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function Nx(e,t){return{...e,matches:t}}function pc(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?vx(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:Mx(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:Nx(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 bm(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 Sm(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function Cm(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:Sm(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:Sm(r.get(i)),...s?{pagination:s}:{}}}})}function xm(e,t,n){let r=Wr(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),u=(Array.isArray(a?.keywords)?a.keywords.filter(p=>typeof p=="string"):[])[0]??n[0];if(!u)continue;let l=e.length===1?"getLines":`getLines:${i.id}`;o[l]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:u},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"low"}}return Object.keys(o).length>0?o:void 0}function dc(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Wr(e);t.forEach((S,C)=>{if(S.status==="error")return;let P=Rm(S);P.repoState&&s.push({id:S.id,state:P.repoState,query:a.get(S.id)}),P.incompleteResults&&(i=!0),P.results.reduce((k,w)=>k+w.matches.length,0)===0&&o.push({id:S.id,...P.nonExistentScope?{nonExistentScope:!0}:{},...P.incompleteResults?{incompleteResults:!0}:{}});let L=P.results;n.push({id:S.id,groups:L}),P.pagination&&r.set(S.id,P.pagination)});let c=Array.from(new Set(e.flatMap(S=>{let C=S.keywords;return Array.isArray(C)?C.filter(P=>typeof P=="string"):[]}))),u=pc(bm(n),c),l=Ui(t),p=e.some(S=>S.concise===!0),m=Cm(e,u,r),d=xm(m,e,c);if(p)for(let S of m)S.data.files=S.data.files.map(C=>`${C.owner}/${C.repo}:${C.path}`);let f={results:m,...d?{next:d}:{}};o.length>0&&(f.emptyQueries=o.map(({id:S,nonExistentScope:C,incompleteResults:P})=>({id:S,...C?{nonExistentScope:C}:{},...P?{incompleteResults:P}:{}}))),l.length>0&&(f.errors=l);let g=[],R=(S,C)=>{g.push(C)};i&&R("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&ym(o,e)&&R("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let h=8,y=o.filter(({id:S,nonExistentScope:C,incompleteResults:P})=>{if(C||P)return!1;let T=a.get(S)?.keywords;return Array.isArray(T)&&T.length>h});y.length>0&&R("ghQueryPossiblyTooComplex",`Quer${y.length>1?"ies":"y"} ${y.map(S=>S.id).join(", ")} used more than ${h} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:S,state:C,query:P}of s)if(C.kind==="renamed"){let[T,L]=C.fullName.split("/");R("ghRepoRenamed",`Query ${S}: the repository was RENAMED to ${C.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let k=P?.keywords;f.next={...f.next??{},[`retryRenamed:${S}`]:{tool:"ghSearchCode",query:{owner:T,repo:L,...Array.isArray(k)?{keywords:k}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else C.kind==="archived"?R("ghRepoArchived",`Query ${S}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):R("ghRepoNotFound",`Query ${S}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`);return Qi(f,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","errors"],u.length===0&&l.length>0)}}function Gx(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function Hx(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 Bx(e,t,n){try{let r=await Q(n),{data:o}=await r.rest.repos.get({owner:e,repo:t}),i=`${e}/${t}`.toLowerCase();return o.full_name&&o.full_name.toLowerCase()!==i?{kind:"renamed",fullName:o.full_name}:o.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function Pm(e){let{queries:t}=e,n=Be(e.authInfo);return te(t,async(r,o)=>{try{let i=Hx(r);if(i)return F(i.error,r);if(!Gx(r))return F("At least one search term or scope filter is required.",r);let s=n(),a=await ft(r,()=>s.provider.searchCode(em(r)));if(a.ok===!1)return a.result;let c=tm(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let u=await Bx(String(r.owner),String(r.repo),e.authInfo);u&&(c.repoState=u)}return se(r,c,c.results.length>0,x.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return be(i,r,void 0,x.GITHUB_SEARCH_CODE)}},{toolName:x.GITHUB_SEARCH_CODE,finalize:dc()},e)}import{z as Ux}from"zod";import{GitHubCodeSearchQuerySchema as wm}from"@octocodeai/octocode-core/schemas";var Tm={limit:_(1,100).optional(),page:K.default(1),match:Ux.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghSearchPullRequests, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},Vr=X(wm,Tm),Kr=Y(Z(wm,Tm));function Qx(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 $x(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 jx(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Em(e){let{content:t,reviewMode:n}=e,r=Qx(t,n),o=$x(t,n),i=jx(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 WN(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function Yr(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Gn(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Xr(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 tn(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 zi(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function mc(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function zx(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function qr(e,t,n){return zx({...mc(e,t),...n})}function fc(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return qr(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function Wi(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return qr(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Hn(e){return typeof e=="object"&&e!==null}function Vi(e){if(Hn(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Ki(e){if(Hn(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function Wx(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 Lm(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=Wx(r,n.comments),i=Yr(t),s=i?o.filter(u=>Gn(u.body,i)):o,{items:a,pagination:c}=Xr(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(u=>{let l=tn(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:zi(typeof u.body=="string"?u.body:"")},createdAt:u.createdAt,updatedAt:u.updatedAt}}),commentPagination:c}}function Am(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Yr(t);return{reviews:(o?r.filter(s=>Gn(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=tn(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 km(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Xr(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 Yi(e){return String(e.path??e.filename??"")}function Vx(e,t){return{path:Yi(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function _m(e,t,n){let r=Array.isArray(e.fileChanges)?e.fileChanges:[],o=n.patches.files,i=o&&o.length>0?r.filter(m=>o.includes(Yi(m))):r,s=Yr(t),a=s?i.filter(m=>Gn(Yi(m),s)||Gn(m.patch,s)):i,{items:c,pagination:u}=Xr(a,t.filePage??t.page??1,t.itemsPerPage??20),l=n.patches.mode!=="none",p=c.map(m=>{let d=Vx(m,!1);if(!l||typeof m.patch!="string")return d;let f=tn(m.patch,t.charOffset??0,t.charLength??12e3);return{...d,patch:f?.content??"",...f?{patchPagination:f.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:r.length===0?{}:{filePathsPreview:r.slice(0,20).map(Yi).filter(Boolean),filePathsPagination:{totalFiles:r.length,filesPerPage:20,hasMore:r.length>20,...r.length>20?{nextFilePage:2}:{}}}}function nn(e,t){return{...e,content:t}}function Kx(e,t){return{...e,...t}}function Im(e,t,n,r){let o=mc(e,t);return{target:o,...n.body?{}:{getBody:nn(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:nn(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:nn(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:nn(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:nn(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:nn(o,{reviews:!0})},...n.commits?{}:{getCommits:nn(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:Kx(o,{reviewMode:"full"})}}}function Yx(e){return e.replace(/\n{3,}/g,`
35
33
 
36
- `)}function vx(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function Dx(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Hn(n))continue;let r=Wi(n.patchPagination);if(r?.hasMore)return r}}function Mx(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Hn(n))continue;let r=Wi(n.bodyPagination);if(r?.hasMore)return r}}function Nx(e,t,n,r){let o={},i=Wi(e.bodyPagination),s=zi(e.filePagination),a=zi(e.commentPagination),c=zi(e.commitPagination),u=Dx(e),l=Mx(e),p=vx(n);i&&(o.body={...i,nextQuery:pc(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:ji(t,r,p,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:ji(t,r,{comments:n.comments},"commentPage",a)}),l?.hasMore&&l.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...l,nextQuery:Xr(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:ji(t,r,{commits:n.commits},"commitPage",c)}),u&&n.patches.mode!=="none"&&(o.patches={...u,nextQuery:pc(t,r,{patches:n.patches},u,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return Hn(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Xr(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function Gx(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Em(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?Fx(s):s,c=n.body?tn(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,d=wm(e,t,n,r),f=Array.isArray(d.changedFiles)?d.changedFiles.find(y=>y.path)?.path:void 0,R={...{number:e.number,title:e.title,state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...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:$i(typeof e.body=="string"?e.body:void 0)}:{},...l?{next:Tm(t,i,n,f)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...d,...Cm(e,t,n),...xm(e,t,n),...Pm(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},h=Nx(R,t,n,i);return Gx(R),h&&(R.contentPagination=h),R}async function Lm(e,t,n){let r=await fe(t),o=ce("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,includeAssets:e.includeAssets===!0,auth:r},n);return he(o,()=>Hx(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function Hx(e,t){try{let n=await Q(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},...e.includeAssets&&c.assets&&c.assets.length>0?{assets:c.assets.map(u=>({name:u.name,size:u.size,downloadCount:u.download_count,url:u.browser_download_url}))}:{}})),a=kn(r.headers.link);return{data:{type:"releases",owner:e.owner,repo:e.repo,releases:s,...i?{latest:{tagName:i.tag_name,...i.published_at?{publishedAt:i.published_at}:{}}}:{},pagination:{currentPage:e.page,perPage:e.perPage,hasMore:a,...a?{nextPage:e.page+1}:{}}},status:200}}catch(n){return V(n)}}var Bx=30;async function Am(e,t,n){let r=t;if(!r.owner||!r.repo)return F("owner and repo are required for releases mode.",e);let o=e.limit,i=Number(typeof o=="number"?o:r.itemsPerPage)||Bx,s=await Lm({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:i,includeAssets:r.includeAssets===!0},n);if(Oe(s))return F(s,e,{toolName:x.GITHUB_RELEASES});let a=s.data.releases.length>0||s.data.latest!==void 0,c=s.data.pagination?.nextPage,u={...s.data,...c!==void 0?{next:{nextPage:{tool:"ghListReleases",query:{owner:r.owner,repo:r.repo,page:c,itemsPerPage:i},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return se(e,u,a,x.GITHUB_RELEASES,{rawResponse:s.rawResponseChars})}function ot(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function dc(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Gi),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function _m(e,t,n){if(!n&&!t)return{text:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{text:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Ki(e){return e.pull_request!=null}function Ux(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function Yi(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:Ux(e.labels),createdAt:e.created_at??"",updatedAt:e.updated_at??"",...e.closed_at?{closedAt:e.closed_at}:{}}}function Bn(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function mc(e,t,n="anon"){return ce("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:dc(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,locked:e.locked,visibility:e.visibility,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}import{ContentSanitizer as km}from"@octocodeai/octocode-engine/contentSanitizer";async function Xi(e,t,n){try{let r=await e.rest.repos.get({owner:t,repo:n}),[o,i]=r.data.full_name?.split("/")??[];return!o||!i?{owner:t,repo:n,renamed:!1}:{owner:o,repo:i,renamed:o!==t||i!==n}}catch{return{owner:t,repo:n,renamed:!1}}}async function Im(e,t){let n=ot(e.owner),r=ot(e.repo),o=e.issueNumber;if(!n||!r||o==null)return Bn("owner, repo, and issueNumber are required for issue detail mode.");let i=await Q(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(Ki(s.data))return Bn(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,u=e.content?.comments?.includeBots===!0,l=Yi(s.data),p={};if(a){let m=km.sanitizeContent(s.data.body??"").content,d=_m(m,e.charOffset,e.charLength);l.body=d.text,d.pagination&&(p.body=d.pagination)}if(c){let m=Math.max(1,e.commentPage??1),d=Math.max(1,e.itemsPerPage??30),f=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:d,page:m}),g=u?f.data:f.data.filter(h=>!qt(h.user?.login??""));l.comments=g.map(h=>({id:String(h.id),user:h.user?.login??"unknown",body:km.sanitizeContent(h.body??"").content,createdAt:h.created_at??"",updatedAt:h.updated_at??"",commentType:"discussion"}));let R=kn(f.headers.link);p.comments={currentPage:m,itemsPerPage:d,totalComments:l.comments.length,hasMore:R,...R?{nextCommentPage:m+1}:{}}}return Object.keys(p).length>0&&(l.contentPagination=p),{data:{type:"issues",owner:n,repo:r,issues:[l],totalCount:1},status:200}}async function Om(e,t,n){let r=ot(t.owner)??"",o=ot(t.repo)??"",i=await Q(n),s=[],a=e;if(r&&o){let h=await Xi(i,r,o);h.renamed&&(s.push(`Repository ${r}/${o} was renamed to ${h.owner}/${h.repo} \u2014 GitHub search does not follow renames, so the canonical name was searched instead.`),a={...e,owner:h.owner,repo:h.repo})}let c=sa(a),u=Math.min(t.limit??30,100),l=t.page??1,p=t.sort&&t.sort!=="best-match"?t.sort:void 0,m=await i.rest.search.issuesAndPullRequests({q:c,sort:p,order:t.order||"desc",per_page:u,page:l}),d=fp(m.headers);d&&s.push(d);let f=(m.data.items??[]).filter(h=>!Ki(h)).map(h=>Yi(h)),g=m.data.total_count??f.length,R=l*u<g&&f.length===u;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?f.map(h=>`#${h.number} ${h.title}`):f,totalCount:g,effectiveQuery:c,...s.length?{warnings:s}:{},...m.data.incomplete_results?{incompleteResults:!0}:{},pagination:{currentPage:l,perPage:u,hasMore:R,...R?{nextPage:l+1}:{},...g>1e3?{totalMatchesCapped:!0}:{}}},status:200}}async function Fm(e,t){let n=ot(e.owner),r=ot(e.repo);if(!n||!r)return Bn("owner and repo are required for issues mode.");let o=await Q(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),u=c.data.filter(d=>!Ki(d)).map(d=>Yi(d)),l=kn(c.headers.link),p=!l&&s===1,m=[];return u.length===0&&l&&m.push("This page contained only pull requests (the GitHub issues endpoint returns both; PRs are filtered out) \u2014 follow pagination.nextPage, later pages may contain issues."),{data:{type:"issues",owner:n,repo:r,issues:e.concise?u.map(d=>`#${d.number} ${d.title}`):u,...p?{totalCount:u.length}:{},...m.length?{warnings:m}:{},pagination:{currentPage:s,perPage:i,hasMore:l,...l?{nextPage:s+1}:{}}},status:200}}async function fc(e,t,n){let r=await fe(t),o=mc(e,n,r);return he(o,()=>Qx(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function Qx(e,t){try{if(e.state==="merged")return Bn('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await Im(e,t);let n={...e,query:dc(e)};return aa(n)?await Om(n,e,t):await Fm(e,t)}catch(n){return nt(n)?{data:{type:"issues",owner:ot(e.owner)??"",repo:ot(e.repo)??"",issues:[],totalCount:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:V(n)}}async function vm(e,t,n){let r=t;if(!r.owner||!r.repo)return F("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await fc({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,locked:r.locked,visibility:r.visibility,match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(Oe(i))return F(i,e,{toolName:x.GITHUB_ISSUES});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let l=a[0];if(typeof l=="number")return l;if(typeof l=="string"){let p=l.match(/^#(\d+)\b/);return p?Number(p[1]):void 0}if(l&&typeof l=="object"&&typeof l.number=="number")return l.number})(),u={};return o==null&&c!=null&&(u.readIssue={tool:"ghSearchIssues",query:{owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"low"}),u.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"low"},se(e,{...i.data,next:u},s,x.GITHUB_ISSUES,{rawResponse:i.rawResponseChars})}async function Dm(e,t){try{let o=(await(await Q(t)).rest.repos.compareCommitsWithBasehead({owner:e.owner,repo:e.repo,basehead:`${e.base}...${e.head}`})).data,i=(o.commits??[]).map(a=>({sha:a.sha,messageHeadline:(a.commit.message??"").split(`
37
- `)[0]??"",author:a.commit.author?.name??a.author?.login??"unknown",date:a.commit.author?.date??""})),s=o.files??[];return{data:{type:"compare",owner:e.owner,repo:e.repo,base:e.base,head:e.head,status:o.status,aheadBy:o.ahead_by,behindBy:o.behind_by,totalCommits:o.total_commits,commits:i,...e.includeDiff?{files:s.map(a=>({filename:a.filename,status:a.status,additions:a.additions,deletions:a.deletions,...a.patch?{patch:a.patch}:{}}))}:{changedFiles:s.length}},status:200}}catch(n){return V(n)}}async function Mm(e,t,n){let r=t;if(!r.owner||!r.repo)return F("owner and repo are required for commits mode.",e);if(r.base&&r.head){let f=await Dm({owner:r.owner,repo:r.repo,base:r.base,head:r.head,includeDiff:!!r.includeDiff},n);return Oe(f)?F(f,e,{toolName:x.GITHUB_COMMITS}):se(e,f.data,f.data.totalCommits>0||f.data.status!=="identical",x.GITHUB_COMMITS)}let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return F("path is required when querying a specific file in commits mode.",e);let s=e.limit,a=typeof s=="number"?s:r.itemsPerPage,c=await rd({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,committer:r.committer,page:Number(r.page)||1,perPage:Number(a)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof a=="number"?a:void 0,includeDiff:!!r.includeDiff,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);if(Oe(c))return F(c,e,{toolName:x.GITHUB_COMMITS});let{commits:u}=c.data,l=u.length>0,p=u.map(f=>f.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),m=!l&&c.data.warnings?.length?{hints:c.data.warnings}:{},d={...c.data,...m,...p?{next:{prDetail:{tool:"ghSearchPullRequests",query:{owner:r.owner,repo:r.repo,prNumber:Number(p)},why:`Open PR #${p} referenced by the first commit for review context`,confidence:"low"}}}:{}};return se(e,d,l,x.GITHUB_COMMITS,{rawResponse:c.rawResponseChars})}async function Nm(e,t,n){let r=n(),o={...t},i=bm(o),s=o.prNumber!==void 0;if(s||(o.content=void 0,o.reviewMode=void 0),!(o.keywordsToSearch?.length||o.owner||o.repo||o.author||o.assignee||o.prNumber&&o.owner&&o.repo))return F("At least one valid search parameter, filter, or PR number is required.",e);let c=await ft(o,()=>r.provider.searchPullRequests(tm(o)));if(c.ok===!1)return c.result;let u=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:l,resultData:p}=nm(c.response.data,{includeFileChanges:u});o.prNumber!==void 0&&delete p.pagination;let m=!s&&(!!e.content||!!e.reviewMode),d={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},f=o.minify==="standard",g=s,R=l.map(y=>Em(y,o,m?d:i,f,g));p.pullRequests=R,!s&&o.concise===!0&&(p.pullRequests=R.map(y=>{let S=y;return`#${S.number} ${S.title}`}));let h=R.length>0;if(!s&&h){let y=R[0].number,S=o.owner,C=o.repo;y!=null&&S&&C&&(p.next={readPr:{tool:"ghSearchPullRequests",query:{owner:S,repo:C,prNumber:y,content:{body:!0,changedFiles:!0,comments:{discussion:!0}}},why:"Read any PR from this list \u2014 swap prNumber for the # you want.",confidence:"low"}})}return se(o,p,h,x.GITHUB_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}import{z as hc}from"zod";import{GitHubPullRequestSearchQuerySchema as Gm}from"@octocodeai/octocode-core/schemas";var Hm={type:hc.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),prNumber:I(1,1e9).optional(),issueNumber:I(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:I(1,100).optional().default(30),match:hc.array(hc.enum(["title","body","comments"])).optional().describe('Fields to match keywords against: "title", "body", "comments". Default searches all three. Use ["title"] for the most precise and fastest match. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)'),page:q.default(1),filePage:q.optional(),commentPage:q.optional(),commitPage:q.optional(),itemsPerPage:I(1,100).optional().default(20),charOffset:I(0,1e8).optional(),commentBodyOffset:I(0,1e8).optional(),charLength:I(1,5e4).optional()},$x=Z(Gm,Hm),gc=Y(Gm,Hm),jx=K($x);async function qr(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{let s=_e(gc,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?await Am(o,s.data,n):a==="issues"?await vm(o,s.data,n):a==="commits"?await Mm(o,s.data,n):await Nm(o,s.data,r)}catch(s){return be(s,o,void 0,x.GITHUB_PULL_REQUESTS)}},{toolName:x.GITHUB_PULL_REQUESTS,keysPriority:["pullRequests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","totalCount","error"]},e)}import{SearchPullRequestsQuerySchema as Bm,SearchIssuesQuerySchema as Um,SearchCommitsQuerySchema as Qm,ListReleasesQuerySchema as $m}from"@octocodeai/octocode-core/schemas";var jm={limit:I(1,100).optional().default(30),page:q.default(1),itemsPerPage:I(1,100).optional().default(20)},zm={...jm,filePage:q.optional(),commentPage:q.optional(),commitPage:q.optional(),charOffset:I(0,1e8).optional(),commentBodyOffset:I(0,1e8).optional(),charLength:I(1,1e5).optional()},Jr=Y(Bm,zm),Zr=K(Z(Bm,zm)),Wm={...jm,commentPage:q.optional(),charOffset:I(0,1e8).optional(),commentBodyOffset:I(0,1e8).optional(),charLength:I(1,1e5).optional()},eo=Y(Um,Wm),to=K(Z(Um,Wm)),Vm={page:q.default(1),limit:I(1,100).optional().describe("Commits per page \u2014 alias of itemsPerPage (preferred when both are set).")},no=Y(Qm,Vm),ro=K(Z(Qm,Vm)),Km={page:q.default(1),limit:I(1,100).optional().describe("Releases per page \u2014 alias of itemsPerPage (preferred when both are set).")},Un=Y($m,Km),Qn=K(Z($m,Km));function qi(e,t){return{...e,queries:e.queries.map(n=>({...n,type:t}))}}function Ym(e){return qr(qi(e,"prs"))}function Xm(e){return qr(qi(e,"issues"))}function qm(e){return qr(qi(e,"commits"))}function Jm(e){return qr(qi(e,"releases"))}import{SearchDiscussionsQuerySchema as Zm}from"@octocodeai/octocode-core/schemas";var ef={itemsPerPage:I(1,100).optional().default(20),limit:I(1,100).optional()},$n=Y(Zm,ef),jn=K(Z(Zm,ef));var zx=`
34
+ `)}function Xx(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function qx(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Hn(n))continue;let r=Ki(n.patchPagination);if(r?.hasMore)return r}}function Jx(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Hn(n))continue;let r=Ki(n.bodyPagination);if(r?.hasMore)return r}}function Zx(e,t,n,r){let o={},i=Ki(e.bodyPagination),s=Vi(e.filePagination),a=Vi(e.commentPagination),c=Vi(e.commitPagination),u=qx(e),l=Jx(e),p=Xx(n);i&&(o.body={...i,nextQuery:fc(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:Wi(t,r,p,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:Wi(t,r,{comments:n.comments},"commentPage",a)}),l?.hasMore&&l.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...l,nextQuery:qr(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:Wi(t,r,{commits:n.commits},"commitPage",c)}),u&&n.patches.mode!=="none"&&(o.patches={...u,nextQuery:fc(t,r,{patches:n.patches},u,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return Hn(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?qr(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function eP(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Om(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?Yx(s):s,c=n.body?tn(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,d=_m(e,t,n),f=Array.isArray(d.changedFiles)?d.changedFiles.find(y=>y.path)?.path:void 0,R={...{number:e.number,title:e.title,state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...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:zi(typeof e.body=="string"?e.body:void 0)}:{},...l?{next:Im(t,i,n,f)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...d,...Lm(e,t,n),...Am(e,t,n),...km(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},h=Zx(R,t,n,i);return eP(R),h&&(R.contentPagination=h),R}async function Fm(e,t,n){let r=await fe(t),o=ce("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,includeAssets:e.includeAssets===!0,auth:r},n);return he(o,()=>tP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function tP(e,t){try{let n=await Q(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},...e.includeAssets&&c.assets&&c.assets.length>0?{assets:c.assets.map(u=>({name:u.name,size:u.size,downloadCount:u.download_count,url:u.browser_download_url}))}:{}})),a=_n(r.headers.link);return{data:{type:"releases",owner:e.owner,repo:e.repo,releases:s,...i?{latest:{tagName:i.tag_name,...i.published_at?{publishedAt:i.published_at}:{}}}:{},pagination:{currentPage:e.page,perPage:e.perPage,hasMore:a,...a?{nextPage:e.page+1}:{}}},status:200}}catch(n){return V(n)}}var nP=30;async function vm(e,t,n){let r=t;if(!r.owner||!r.repo)return F("owner and repo are required for releases mode.",e);let o=e.limit,i=Number(typeof o=="number"?o:r.itemsPerPage)||nP,s=await Fm({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:i,includeAssets:r.includeAssets===!0},n);if(Oe(s))return F(s,e,{toolName:x.GITHUB_RELEASES});let a=s.data.releases.length>0||s.data.latest!==void 0,c=s.data.pagination?.nextPage,u={...s.data,...c!==void 0?{next:{nextPage:{tool:"ghListReleases",query:{owner:r.owner,repo:r.repo,page:c,itemsPerPage:i},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return se(e,u,a,x.GITHUB_RELEASES,{rawResponse:s.rawResponseChars})}function ot(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function hc(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Hi),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function Dm(e,t,n){if(!n&&!t)return{text:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{text:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Xi(e){return e.pull_request!=null}function rP(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function qi(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:rP(e.labels),createdAt:e.created_at??"",updatedAt:e.updated_at??"",...e.closed_at?{closedAt:e.closed_at}:{}}}function Bn(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function gc(e,t,n="anon"){return ce("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:hc(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,locked:e.locked,visibility:e.visibility,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}import{ContentSanitizer as Mm}from"@octocodeai/octocode-engine/contentSanitizer";async function Ji(e,t,n){try{let r=await e.rest.repos.get({owner:t,repo:n}),[o,i]=r.data.full_name?.split("/")??[];return!o||!i?{owner:t,repo:n,renamed:!1}:{owner:o,repo:i,renamed:o!==t||i!==n}}catch{return{owner:t,repo:n,renamed:!1}}}async function Nm(e,t){let n=ot(e.owner),r=ot(e.repo),o=e.issueNumber;if(!n||!r||o==null)return Bn("owner, repo, and issueNumber are required for issue detail mode.");let i=await Q(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(Xi(s.data))return Bn(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,u=e.content?.comments?.includeBots===!0,l=qi(s.data),p={};if(a){let m=Mm.sanitizeContent(s.data.body??"").content,d=Dm(m,e.charOffset,e.charLength);l.body=d.text,d.pagination&&(p.body=d.pagination)}if(c){let m=Math.max(1,e.commentPage??1),d=Math.max(1,e.itemsPerPage??30),f=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:d,page:m}),g=u?f.data:f.data.filter(h=>!qt(h.user?.login??""));l.comments=g.map(h=>({id:String(h.id),user:h.user?.login??"unknown",body:Mm.sanitizeContent(h.body??"").content,createdAt:h.created_at??"",updatedAt:h.updated_at??"",commentType:"discussion"}));let R=_n(f.headers.link);p.comments={currentPage:m,itemsPerPage:d,totalComments:l.comments.length,hasMore:R,...R?{nextCommentPage:m+1}:{}}}return Object.keys(p).length>0&&(l.contentPagination=p),{data:{type:"issues",owner:n,repo:r,issues:[l],totalCount:1},status:200}}async function Gm(e,t,n){let r=ot(t.owner)??"",o=ot(t.repo)??"",i=await Q(n),s=[],a=e;if(r&&o){let h=await Ji(i,r,o);h.renamed&&(s.push(`Repository ${r}/${o} was renamed to ${h.owner}/${h.repo} \u2014 GitHub search does not follow renames, so the canonical name was searched instead.`),a={...e,owner:h.owner,repo:h.repo})}let c=ca(a),u=Math.min(t.limit??30,100),l=t.page??1,p=t.sort&&t.sort!=="best-match"?t.sort:void 0,m=await i.rest.search.issuesAndPullRequests({q:c,sort:p,order:t.order||"desc",per_page:u,page:l}),d=yp(m.headers);d&&s.push(d);let f=(m.data.items??[]).filter(h=>!Xi(h)).map(h=>qi(h)),g=m.data.total_count??f.length,R=l*u<g&&f.length===u;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?f.map(h=>`#${h.number} ${h.title}`):f,totalCount:g,effectiveQuery:c,...s.length?{warnings:s}:{},...m.data.incomplete_results?{incompleteResults:!0}:{},pagination:{currentPage:l,perPage:u,hasMore:R,...R?{nextPage:l+1}:{},...g>1e3?{totalMatchesCapped:!0}:{}}},status:200}}async function Hm(e,t){let n=ot(e.owner),r=ot(e.repo);if(!n||!r)return Bn("owner and repo are required for issues mode.");let o=await Q(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),u=c.data.filter(d=>!Xi(d)).map(d=>qi(d)),l=_n(c.headers.link),p=!l&&s===1,m=[];return u.length===0&&l&&m.push("This page contained only pull requests (the GitHub issues endpoint returns both; PRs are filtered out) \u2014 follow pagination.nextPage, later pages may contain issues."),{data:{type:"issues",owner:n,repo:r,issues:e.concise?u.map(d=>`#${d.number} ${d.title}`):u,...p?{totalCount:u.length}:{},...m.length?{warnings:m}:{},pagination:{currentPage:s,perPage:i,hasMore:l,...l?{nextPage:s+1}:{}}},status:200}}async function yc(e,t,n){let r=await fe(t),o=gc(e,n,r);return he(o,()=>oP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function oP(e,t){try{if(e.state==="merged")return Bn('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await Nm(e,t);let n={...e,query:hc(e)};return ua(n)?await Gm(n,e,t):await Hm(e,t)}catch(n){return nt(n)?{data:{type:"issues",owner:ot(e.owner)??"",repo:ot(e.repo)??"",issues:[],totalCount:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:V(n)}}async function Bm(e,t,n){let r=t;if(!r.owner||!r.repo)return F("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await yc({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,locked:r.locked,visibility:r.visibility,match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(Oe(i))return F(i,e,{toolName:x.GITHUB_ISSUES});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let l=a[0];if(typeof l=="number")return l;if(typeof l=="string"){let p=l.match(/^#(\d+)\b/);return p?Number(p[1]):void 0}if(l&&typeof l=="object"&&typeof l.number=="number")return l.number})(),u={};return o==null&&c!=null&&(u.readIssue={tool:"ghSearchIssues",query:{owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"low"}),u.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"low"},se(e,{...i.data,next:u},s,x.GITHUB_ISSUES,{rawResponse:i.rawResponseChars})}async function Um(e,t){try{let o=(await(await Q(t)).rest.repos.compareCommitsWithBasehead({owner:e.owner,repo:e.repo,basehead:`${e.base}...${e.head}`})).data,i=(o.commits??[]).map(u=>({sha:u.sha,messageHeadline:(u.commit.message??"").split(`
35
+ `)[0]??"",author:u.commit.author?.name??u.author?.login??"unknown",date:u.commit.author?.date??""})),s=o.files??[],a=e.path?s.filter(u=>u.filename===e.path):s,c;if(e.includeDiff){let u=Mr(a,{filePage:e.filePage,itemsPerPage:e.itemsPerPage,charOffset:e.charOffset,charLength:e.charLength});c={files:u.files,filesPagination:u.filesPagination}}else c={changedFiles:a.length};return{data:{type:"compare",owner:e.owner,repo:e.repo,base:e.base,head:e.head,status:o.status,aheadBy:o.ahead_by,behindBy:o.behind_by,totalCommits:o.total_commits,commits:i,...c},status:200}}catch(n){return V(n)}}async function Qm(e,t,n){let r=t;if(!r.owner||!r.repo)return F("owner and repo are required for commits mode.",e);if(r.base&&r.head){let f=e.limit,g=await Um({owner:r.owner,repo:r.repo,base:r.base,head:r.head,includeDiff:!!r.includeDiff,path:r.path,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof f=="number"?f:r.itemsPerPage,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);return Oe(g)?F(g,e,{toolName:x.GITHUB_COMMITS}):se(e,g.data,g.data.totalCommits>0||g.data.status!=="identical",x.GITHUB_COMMITS)}let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return F("path is required when querying a specific file in commits mode.",e);let s=e.limit,a=typeof s=="number"?s:r.itemsPerPage,c=await sd({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,committer:r.committer,page:Number(r.page)||1,perPage:Number(a)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof a=="number"?a:void 0,includeDiff:!!r.includeDiff,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);if(Oe(c))return F(c,e,{toolName:x.GITHUB_COMMITS});let{commits:u}=c.data,l=u.length>0,p=u.map(f=>f.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),m=!l&&c.data.warnings?.length?{hints:c.data.warnings}:{},d={...c.data,...m,...p?{next:{prDetail:{tool:"ghSearchPullRequests",query:{owner:r.owner,repo:r.repo,prNumber:Number(p)},why:`Open PR #${p} referenced by the first commit for review context`,confidence:"low"}}}:{}};return se(e,d,l,x.GITHUB_COMMITS,{rawResponse:c.rawResponseChars})}async function $m(e,t,n){let r=n(),o={...t},i=Em(o),s=o.prNumber!==void 0;if(s||(o.content=void 0,o.reviewMode=void 0),!(o.keywordsToSearch?.length||o.owner||o.repo||o.author||o.assignee||o.prNumber&&o.owner&&o.repo))return F("At least one valid search parameter, filter, or PR number is required.",e);let c=await ft(o,()=>r.provider.searchPullRequests(om(o)));if(c.ok===!1)return c.result;let u=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:l,resultData:p}=im(c.response.data,{includeFileChanges:u});o.prNumber!==void 0&&delete p.pagination;let m=!s&&(!!e.content||!!e.reviewMode),d={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},f=o.minify==="standard",g=s,R=l.map(y=>Om(y,o,m?d:i,f,g));p.pullRequests=R,!s&&o.concise===!0&&(p.pullRequests=R.map(y=>{let S=y;return`#${S.number} ${S.title}`}));let h=R.length>0;if(!s&&h){let y=R[0].number,S=o.owner,C=o.repo;y!=null&&S&&C&&(p.next={readPr:{tool:"ghSearchPullRequests",query:{owner:S,repo:C,prNumber:y,content:{body:!0,changedFiles:!0,comments:{discussion:!0}}},why:"Read any PR from this list \u2014 swap prNumber for the # you want.",confidence:"low"}})}return se(o,p,h,x.GITHUB_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}import{z as Rc}from"zod";import{GitHubPullRequestSearchQuerySchema as jm}from"@octocodeai/octocode-core/schemas";var zm={type:Rc.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),prNumber:_(1,1e9).optional(),issueNumber:_(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:_(1,100).optional().default(30),match:Rc.array(Rc.enum(["title","body","comments"])).optional().describe('Fields to match keywords against: "title", "body", "comments". Default searches all three. Use ["title"] for the most precise and fastest match. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)'),page:K.default(1),filePage:K.optional(),commentPage:K.optional(),commitPage:K.optional(),itemsPerPage:_(1,100).optional().default(20),charOffset:_(0,1e8).optional(),commentBodyOffset:_(0,1e8).optional(),charLength:_(1,5e4).optional()},iP=Z(jm,zm),Sc=X(jm,zm),sP=Y(iP);async function Jr(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{let s=ke(Sc,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?await vm(o,s.data,n):a==="issues"?await Bm(o,s.data,n):a==="commits"?await Qm(o,s.data,n):await $m(o,s.data,r)}catch(s){return be(s,o,void 0,x.GITHUB_PULL_REQUESTS)}},{toolName:x.GITHUB_PULL_REQUESTS,keysPriority:["pullRequests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","totalCount","error"]},e)}import{SearchPullRequestsQuerySchema as Wm,SearchIssuesQuerySchema as Vm,SearchCommitsQuerySchema as Km,ListReleasesQuerySchema as Ym}from"@octocodeai/octocode-core/schemas";var Xm={limit:_(1,100).optional().default(30),page:K.default(1),itemsPerPage:_(1,100).optional().default(20)},qm={...Xm,filePage:K.optional(),commentPage:K.optional(),commitPage:K.optional(),charOffset:_(0,1e8).optional(),commentBodyOffset:_(0,1e8).optional(),charLength:_(1,1e5).optional()},Zr=X(Wm,qm),eo=Y(Z(Wm,qm)),Jm={...Xm,commentPage:K.optional(),charOffset:_(0,1e8).optional(),commentBodyOffset:_(0,1e8).optional(),charLength:_(1,1e5).optional()},to=X(Vm,Jm),no=Y(Z(Vm,Jm)),Zm={page:K.default(1),limit:_(1,100).optional().describe("Commits per page \u2014 alias of itemsPerPage (preferred when both are set)."),filePage:K.optional(),charOffset:_(0,1e8).optional(),charLength:_(1,1e5).optional()},ro=X(Km,Zm),oo=Y(Z(Km,Zm)),ef={page:K.default(1),limit:_(1,100).optional().describe("Releases per page \u2014 alias of itemsPerPage (preferred when both are set).")},Un=X(Ym,ef),Qn=Y(Z(Ym,ef));function Zi(e,t){return{...e,queries:e.queries.map(n=>({...n,type:t}))}}function tf(e){return Jr(Zi(e,"prs"))}function nf(e){return Jr(Zi(e,"issues"))}function rf(e){return Jr(Zi(e,"commits"))}function of(e){return Jr(Zi(e,"releases"))}import{SearchDiscussionsQuerySchema as sf}from"@octocodeai/octocode-core/schemas";var af={itemsPerPage:_(1,100).optional().default(20),limit:_(1,100).optional()},$n=X(sf,af),jn=Y(Z(sf,af));var aP=`
38
36
  query($q: String!, $first: Int!, $after: String, $owner: String!, $repo: String!) {
39
37
  search(query: $q, type: DISCUSSION, first: $first, after: $after) {
40
38
  discussionCount
@@ -57,13 +55,13 @@ query($q: String!, $first: Int!, $after: String, $owner: String!, $repo: String!
57
55
  repository(owner: $owner, name: $repo) {
58
56
  hasDiscussionsEnabled
59
57
  }
60
- }`;async function tf(e,t,n){let r=await fe(t),o=ce("gh-api-discussions",{owner:e.owner,repo:e.repo,keywords:(e.keywords??[]).join(" "),perPage:e.perPage,after:e.after??"",auth:r},n);return he(o,()=>Wx(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function Wx(e,t){try{let n=await Q(t),r=(e.keywords??[]).map(l=>l.trim()).filter(Boolean).join(" "),o=`repo:${e.owner}/${e.repo}${r?` ${r}`:""}`,i=await n.graphql(zx,{q:o,first:e.perPage,owner:e.owner,repo:e.repo,...e.after?{after:e.after}:{}}),a=(i.search.nodes??[]).filter(l=>typeof l.number=="number").map(l=>({number:l.number,title:l.title,url:l.url,...l.author?.login?{author:l.author.login}:{},...l.category?.name?{category:l.category.name}:{},...l.createdAt?{createdAt:l.createdAt}:{},...l.updatedAt?{updatedAt:l.updatedAt}:{},...l.answerChosenAt?{answered:!0}:{},...typeof l.upvoteCount=="number"?{upvotes:l.upvoteCount}:{},...typeof l.comments?.totalCount=="number"?{comments:l.comments.totalCount}:{}})),c=i.search.pageInfo.hasNextPage===!0,u=i.search.pageInfo.endCursor??void 0;return{data:{type:"discussions",owner:e.owner,repo:e.repo,totalCount:i.search.discussionCount,discussions:a,pagination:{perPage:e.perPage,hasMore:c,...c&&u?{nextCursor:u}:{}},...typeof i.repository?.hasDiscussionsEnabled=="boolean"?{hasDiscussionsEnabled:i.repository.hasDiscussionsEnabled}:{}},status:200}}catch(n){return V(n)}}var Vx=30;async function nf(e){let{queries:t,authInfo:n,sessionId:r}=e;return te(t,async(o,i)=>{try{if(!o.owner||!o.repo)return F("owner and repo are required to search discussions.",o);let s=Number(o.limit??o.itemsPerPage)||Vx,a=await tf({owner:o.owner,repo:o.repo,keywords:o.keywordsToSearch,perPage:s,...o.after?{after:o.after}:{}},n,r);if(Oe(a))return F(a,o,{toolName:x.GITHUB_DISCUSSIONS});let c=a.data.discussions.length>0,u=!c&&a.data.hasDiscussionsEnabled===!1?["This repository has Discussions disabled \u2014 an empty result here means the feature is off, not that no matching discussions exist."]:[],l=a.data.pagination.nextCursor,p={...a.data,...u.length>0?{warnings:u}:{},...l?{next:{nextPage:{tool:"ghSearchDiscussions",query:{owner:o.owner,repo:o.repo,...o.keywordsToSearch?{keywordsToSearch:o.keywordsToSearch}:{},itemsPerPage:s,after:l},why:"Fetch the next page of discussions",confidence:"exact"}}}:{}};return se(o,p,c,x.GITHUB_DISCUSSIONS,{rawResponse:a.rawResponseChars})}catch(s){return be(s,o,"Failed to search repository discussions",x.GITHUB_DISCUSSIONS)}},{toolName:x.GITHUB_DISCUSSIONS,keysPriority:["totalCount","discussions","pagination","error"]},e)}function of(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function Ji(e){return!!(e.keywords&&e.keywords.length>0)}function sf(e){return!!(Ji(e)||of(e)||e.owner||e.language||e.stars||e.updated||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function rf(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function af(e){let t=of(e),n=Ji(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:rf(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:rf(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function cf(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 lf(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 pf(e,t){return[...e].sort((n,r)=>{let o=Kx(n,r,t.sort);if(o!==0)return o;let i=uf(r,t)-uf(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:yc(n).localeCompare(yc(r))})}function Kx(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 cf(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function uf(e,t){let n=Yx(t),r=yc(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,p)=>o===p||r===p?l+80:o.includes(p)||r.includes(p)?l+40:s.includes(p)?l+35:i.includes(p)?l+10:l,0)+(c&&a===c?20:0)}function Yx(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function yc(e){return`${e.owner}/${e.repo}`}function Rc(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function Sc(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function bc(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function df(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??N(n.response.data??n.response)),0)}function Xx(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt?t.createdAt.slice(0,10):void 0,updatedAt:t.updatedAt?t.updatedAt.slice(0,10):void 0,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function qx(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"low"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"low"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(Xx),...o?{next:o}:{}}}}async function mf(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{if(!sf(o))return F("At least one repository search term or filter is required.",o);let s=r(),a=af(o),{successes:c,failures:u}=await jd(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(Zd(w.query))}))),l=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),p=u.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(l.length===0){let w=p[0];return w?ki(w.response,o):be(new Error("Repository search produced no provider results"),o,void 0,x.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,d=pf(lf(l.flatMap(w=>em(w.response.data.repositories))),o),f=m!=null?d.slice(0,m):d,g=l.length===1?l[0]:void 0,h=l.length>1?bc(l,d.length):g?.response.data.pagination,y=h?Rc(h):void 0,S=f.length>0,C=qx({repositories:f,pagination:y},o),P=Sc(p),T;if(o.owner&&Ji(o)){let w=(Array.isArray(o.keywords)?o.keywords:[o.keywords]).filter(A=>typeof A=="string"&&A.trim().length>0).slice(0,3),b=w.some(A=>f.some(M=>M.repo?.toLowerCase()===A.toLowerCase()));if(w.length>0&&!b)try{let A=await Q(n);for(let M of w){let B=await Xi(A,String(o.owner),M);if(B.renamed){T={warning:`No repositories matched under owner "${o.owner}", but "${o.owner}/${M}" now resolves to "${B.owner}/${B.repo}" \u2014 the repository may have been transferred. Retry scoped to owner:"${B.owner}" (see next.retryUnderCanonicalOwner).`,next:{retryUnderCanonicalOwner:{tool:"ghSearchRepos",query:{...o,owner:B.owner,keywords:[B.repo]},why:"Re-run scoped to the repository's current owner after a detected transfer.",confidence:"exact"}}};break}}}catch{}}let L=[...P??[],...T?[T.warning]:[],...!S&&!T?['No repositories matched. Keywords are ANDed \u2014 try fewer or broader keywords, drop a topic/filter (topics are sparse), or add match:"readme" for full-text search.']:[]],_={...C.data,...L.length>0?{warnings:L}:{},...T?{next:T.next}:{}};return se(o,_,S,x.GITHUB_SEARCH_REPOSITORIES,{rawResponse:df([...l,...p])})}catch(s){return be(s,o,void 0,x.GITHUB_SEARCH_REPOSITORIES)}},{toolName:x.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}import{z as ff}from"zod";import{GitHubReposSearchSingleQuerySchema as hf}from"@octocodeai/octocode-core/schemas";var gf={limit:I(1,100).optional(),page:q.default(1),match:ff.array(ff.enum(["name","description","readme"])).optional().describe("Which text fields to search: name, description, and/or readme. Defaults to name+description; add 'readme' for broader, slower full-text search. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)")},oo=Y(hf,gf),io=K(Z(hf,gf));function Jx(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0,o=typeof r?.status=="number"?r.status:void 0,i=typeof t.path=="string"?t.path.replace(/\/+$/,""):"",s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):"",a=i.split("/").pop()||t.repo,c=o===404?{retryParent:{tool:"ghViewRepoStructure",query:{owner:t.owner,repo:t.repo,...s?{path:s}:{},...t.branch?{branch:t.branch}:{}},why:"Retry at the parent directory \u2014 the path or branch may be wrong.",confidence:"low"},searchPath:{tool:"ghSearchCode",query:{owner:t.owner,repo:t.repo,match:"path",keywords:[a]},why:"Locate the path by name in case it moved or was renamed.",confidence:"low"}}:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...c?{next:c}:{}}}function Zx(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Cr(o))continue;let i=r.files.filter(a=>!bn(a)),s=r.folders.filter(a=>!Cr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function yf(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,u=c??await s.provider.resolveDefaultBranch(a),l=await ft(o,()=>s.provider.getRepoStructure(ac(o,u))),p=u,m;if(l.ok===!1&&c){let C=l.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let T=await s.provider.resolveDefaultBranch(a);if(T!==c){let L=await ft(o,()=>s.provider.getRepoStructure(ac(o,T)));L.ok!==!1&&(l=L,p=T,m=`Branch/ref '${c}' was not found. Showing '${T}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(l.ok===!1)return Jx(l.result,o);let d=Zx(l.response.data.structure),f=Object.keys(d).length>0,g=im(l.response.data,o,d,p);m&&(g.branchFallback={requestedBranch:c,actualBranch:p,warning:m});let h=g.structure?.find(C=>(C.files?.length??0)>0),y=String(o.path??"").replace(/\/+$/,""),S=h?(()=>{let C=h.dir==="."?h.files[0]:`${h.dir}/${h.files[0]}`;return y?`${y}/${C}`:C})():void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...p?{branch:p}:{}},why:"Read the first listed file",confidence:"low"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...p?{branch:p}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},se(o,g,f,x.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return be(s,o,"Failed to explore repository structure",x.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:x.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}import{GitHubViewRepoStructureQuerySchema as Rf}from"@octocodeai/octocode-core/schemas";var Sf={maxDepth:I(0,20).optional(),page:q.default(1),itemsPerPage:I(1,200).optional()},so=Y(Rf,Sf),ao=K(Z(Rf,Sf));import{ContentSanitizer as cP}from"@octocodeai/octocode-engine/contentSanitizer";import bf from"path";import{pathValidator as Cf}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as xf}from"@octocodeai/config";function eP(e=xf().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&Cf.addAllowedRoot(t)}function ve(e,t){if(!e.path?.trim()){let s=Le.pathValidationFailed("","path is required");return{isValid:!1,errorResult:F(s,e,{toolName:t})}}eP();let n=process.env.WORKSPACE_ROOT?.trim()||xf().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=bf.isAbsolute(r)?r:bf.resolve(n,r),i=Cf.validate(o);if(!i.isValid){let s=Le.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:F(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function bB(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:Le.outputTooLarge(e,r).errorCode,hints:[`Found ${e} ${o}${e===1?"":"s"} - exceeds safe limit of ${r}`,"Use charLength to paginate through results",i?"Detailed results increase size - consider using charLength for pagination":"Consider using charLength to paginate large result sets"]}:{shouldBlock:!1}}import{open as tP,readFile as nP,stat as rP}from"fs/promises";var xB={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},Gt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500};function wB(e){return t=>{}}function Pf(e,t){return n=>t}function Cc(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function xc(e,t,n){return{...e,...Cc(t,n)}}function wf(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function Tf(e,t){try{return{fileStats:await rP(t)}}catch(n){let r=Le.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:F(r,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Ef(e){let t=e.startLine!==void 0&&e.endLine!==void 0;return e.minify??(e.fullContent===!0||t?"none":"standard")}function Lf(e,t,n){return n!=="none"?!1:t>Gt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.charLength}function Af(e,t,n){let r=Le.fileTooLarge(e.path,n,Gt.LARGE_FILE_THRESHOLD_KB);return F(r,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function _f(e,t){let n=Le.binaryFileUnsupported(e.path);return F(n,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function kf(e){let n=Buffer.alloc(8192),r;try{r=await tP(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(Pf("binary sample handle close",void 0))}}async function If(e,t){try{return{content:await nP(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?Le.fileAccessFailed(e.path,r):Le.fileReadFailed(e.path,r);return{errorResult:F(i,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Of(e,t){return{status:"empty",errorCode:H.NO_MATCHES,totalLines:t}}function oP(e,t,n){let r=di(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Of(e,n)};let o=r.lines.join(`
61
- `),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,p;if(r.matchRanges.length>0){let m=r.matchRanges[0],d=r.matchRanges[r.matchRanges.length-1];m&&d&&(u=m.start,l=d.end,p=r.matchRanges)}return{resultContent:o,isPartial:!0,actualStartLine:u,actualEndLine:l,matchRanges:p,matchedLines:r.matchingLines,warnings:[c]}}function iP(e){return e.startLine!==void 0&&e.endLine!==void 0}function sP(e,t,n){let r=String(n).length;return e.slice(t-1,n).map((o,i)=>`${String(t+i).padStart(r," ")}\u2192 ${o}`).join(`
62
- `)}function aP(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:sP(t,i,s),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function Ff(e,t,n){let r=t.split(`
63
- `),o=rt(t);return e.matchString?oP(e,r,o):iP(e)?aP(e,r,o):{resultContent:t,isPartial:!1}}async function vf(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,u=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let l="char-limit",p=s;if(s!==void 0){let g=await gi(e,u,s,r);l=g.chunkMode,p=g.length}let m=hi(e,u,p,s!==void 0?{pageSize:s}:void 0),d;if(m.hasMore&&l==="char-limit"&&kr(m.paginatedContent)){let g=m.charOffset+m.charLength;d=await Ir(e,g,r)}let f=_i("localGetFileContent",{path:r,charLength:s??m.charLength,minify:t.minify},m);return{windowedContent:m.paginatedContent,pagination:m,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:l,nextBlockChar:d,next:f,showPagination:s!==void 0||i>0||a}}async function Df(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=await vf(u,e,o);l.autoPaginateWarning&&a.push(l.autoPaginateWarning);let p=t.isPartial||l.pagination.hasMore;return{path:c,content:l.windowedContent,contentView:s,returnedChars:l.windowedContent.length,...p&&{isPartial:p},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges},...t.matchedLines!==void 0&&{matchedLines:t.matchedLines}},...n.mtime&&{modified:n.mtime.toISOString()},...l.showPagination&&{pagination:{...Ea(l.pagination),chunkMode:l.chunkMode,...l.nextBlockChar!==void 0&&{nextBlockChar:l.nextBlockChar}}},...l.next?{next:l.next}:{},...a.length>0&&{warnings:a}}}async function Pc(e,t,n,r,o,i,s){let a=await vf(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",returnedChars:a.windowedContent.length,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...Cc(r,o),...a.showPagination&&{pagination:{...Ea(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function Mf(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}function wc(e,t){let n=cP.sanitizeContent(e,t);return{text:n.content,warning:n.hasSecrets?`Secrets detected and redacted: ${n.secretsDetected.join(", ")}`:void 0}}async function Nf(e){let t=Dt();try{let n=ve(e,x.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=wf(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await Tf(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,u=c/1024;if(await kf(o))return $(_f(e,o),c);let l=Ef(e);if(Lf(e,u,l))return $(Af(e,o,u),c);let{content:p,errorResult:m}=await If(e,o);if(m||p===void 0)return m;let d=p.length,f=Buffer.byteLength(p,"utf-8"),g=p,R=e.matchString!==void 0&&l!=="none",h=R?"none":l,y=R&&e.minify!==void 0?`minify:"${e.minify}" is not applied to matchString extractions \u2014 matched slices are returned verbatim so the content always contains the matched text.`:void 0,S=h==="standard"||h==="symbols",C=S?"standard":"none",P;if(h==="symbols"){let b=O.extractSignatures(g,i);if(b===null){let A=mi(g,i);if(A!==null){let M=wc(A,i);return $(await Pc(e,M.text,rt(g),d,f,M.warning,t),d)}P=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(b!==null){let A=rt(g),M=O.applyContentViewMinification(b,i),B=wc(M,i);return $(await Pc(e,B.text,A,d,f,B.warning,t),d)}}let T=rt(g),L=Ff(e,g,t),_=b=>{let A=b.content;if(typeof A!="string")return b;let M=wc(A,i),B=[...P?[P]:[],...y?[y]:[],...M.warning?[M.warning]:[]],k=b.warnings??[];return{...b,content:M.text,...B.length>0&&{warnings:[...k,...B]}}};if(L.earlyResult){let b=L.earlyResult.content,A=S&&typeof b=="string"?{...L.earlyResult,content:O.applyContentViewMinification(b,i)}:L.earlyResult;return $(xc(_(Mf(A,C)),d,f),d)}let w=await Df(e,L,s,T,t,S,C);return $(xc(_(w),d,f),d)}catch(n){return F(n,e,{toolName:x.LOCAL_FETCH_CONTENT})}}import{z as uP}from"zod";import{FetchContentQuerySchema as Gf}from"@octocodeai/octocode-core/schemas";var lP=uP.enum(["none","standard","symbols"]).optional(),Hf={startLine:On,endLine:On,contextLines:In.default(5),charOffset:I(0,1e8).optional(),charLength:I(1,5e4).optional(),minify:lP},pP=Z(Gf,Hf),rn=Y(Gf,Hf),co=K(pP,{maxQueries:5});async function Bf(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=_e(rn,n);return r.ok===!1?r.error:await Nf(r.data)}}),{toolName:x.LOCAL_FETCH_CONTENT,finalize:dP()},e)}function dP(){return({results:e})=>{let t={results:mP(e)},n=Dn(t.results);n&&(t.base=n);let r=Mn(t.results);return r&&(t.shared=r),{structuredContent:Ve(t),text:fP(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function mP(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function fP(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=Nt({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","returnedChars","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Nt({shared:e.shared},["shared"]).trimEnd()),t.join(`
58
+ }`;async function cf(e,t,n){let r=await fe(t),o=ce("gh-api-discussions",{owner:e.owner,repo:e.repo,keywords:(e.keywords??[]).join(" "),perPage:e.perPage,after:e.after??"",auth:r},n);return he(o,()=>cP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function cP(e,t){try{let n=await Q(t),r=(e.keywords??[]).map(l=>l.trim()).filter(Boolean).join(" "),o=`repo:${e.owner}/${e.repo}${r?` ${r}`:""}`,i=await n.graphql(aP,{q:o,first:e.perPage,owner:e.owner,repo:e.repo,...e.after?{after:e.after}:{}}),a=(i.search.nodes??[]).filter(l=>typeof l.number=="number").map(l=>({number:l.number,title:l.title,url:l.url,...l.author?.login?{author:l.author.login}:{},...l.category?.name?{category:l.category.name}:{},...l.createdAt?{createdAt:l.createdAt}:{},...l.updatedAt?{updatedAt:l.updatedAt}:{},...l.answerChosenAt?{answered:!0}:{},...typeof l.upvoteCount=="number"?{upvotes:l.upvoteCount}:{},...typeof l.comments?.totalCount=="number"?{comments:l.comments.totalCount}:{}})),c=i.search.pageInfo.hasNextPage===!0,u=i.search.pageInfo.endCursor??void 0;return{data:{type:"discussions",owner:e.owner,repo:e.repo,totalCount:i.search.discussionCount,discussions:a,pagination:{perPage:e.perPage,hasMore:c,...c&&u?{nextCursor:u}:{}},...typeof i.repository?.hasDiscussionsEnabled=="boolean"?{hasDiscussionsEnabled:i.repository.hasDiscussionsEnabled}:{}},status:200}}catch(n){return V(n)}}var uP=30;async function uf(e){let{queries:t,authInfo:n,sessionId:r}=e;return te(t,async(o,i)=>{try{if(!o.owner||!o.repo)return F("owner and repo are required to search discussions.",o);let s=Number(o.limit??o.itemsPerPage)||uP,a=await cf({owner:o.owner,repo:o.repo,keywords:o.keywordsToSearch,perPage:s,...o.after?{after:o.after}:{}},n,r);if(Oe(a))return F(a,o,{toolName:x.GITHUB_DISCUSSIONS});let c=a.data.discussions.length>0,u=!c&&a.data.hasDiscussionsEnabled===!1?["This repository has Discussions disabled \u2014 an empty result here means the feature is off, not that no matching discussions exist."]:[],l=a.data.pagination.nextCursor,p={...a.data,...u.length>0?{warnings:u}:{},...l?{next:{nextPage:{tool:"ghSearchDiscussions",query:{owner:o.owner,repo:o.repo,...o.keywordsToSearch?{keywordsToSearch:o.keywordsToSearch}:{},itemsPerPage:s,after:l},why:"Fetch the next page of discussions",confidence:"exact"}}}:{}};return se(o,p,c,x.GITHUB_DISCUSSIONS,{rawResponse:a.rawResponseChars})}catch(s){return be(s,o,"Failed to search repository discussions",x.GITHUB_DISCUSSIONS)}},{toolName:x.GITHUB_DISCUSSIONS,keysPriority:["totalCount","discussions","pagination","error"]},e)}function pf(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function es(e){return!!(e.keywords&&e.keywords.length>0)}function df(e){return!!(es(e)||pf(e)||e.owner||e.language||e.stars||e.updated||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function lf(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function mf(e){let t=pf(e),n=es(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:lf(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:lf(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function ff(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 gf(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 yf(e,t){return[...e].sort((n,r)=>{let o=lP(n,r,t.sort);if(o!==0)return o;let i=hf(r,t)-hf(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:bc(n).localeCompare(bc(r))})}function lP(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 ff(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function hf(e,t){let n=pP(t),r=bc(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,p)=>o===p||r===p?l+80:o.includes(p)||r.includes(p)?l+40:s.includes(p)?l+35:i.includes(p)?l+10:l,0)+(c&&a===c?20:0)}function pP(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function bc(e){return`${e.owner}/${e.repo}`}function Cc(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function xc(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function Pc(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function Rf(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??N(n.response.data??n.response)),0)}function dP(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt?t.createdAt.slice(0,10):void 0,updatedAt:t.updatedAt?t.updatedAt.slice(0,10):void 0,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function mP(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"low"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"low"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(dP),...o?{next:o}:{}}}}async function Sf(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{if(!df(o))return F("At least one repository search term or filter is required.",o);let s=r(),a=mf(o),{successes:c,failures:u}=await Vd(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(nm(w.query))}))),l=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),p=u.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(l.length===0){let w=p[0];return w?Ii(w.response,o):be(new Error("Repository search produced no provider results"),o,void 0,x.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,d=yf(gf(l.flatMap(w=>rm(w.response.data.repositories))),o),f=m!=null?d.slice(0,m):d,g=l.length===1?l[0]:void 0,h=l.length>1?Pc(l,d.length):g?.response.data.pagination,y=h?Cc(h):void 0,S=f.length>0,C=mP({repositories:f,pagination:y},o),P=xc(p),T;if(o.owner&&es(o)){let w=(Array.isArray(o.keywords)?o.keywords:[o.keywords]).filter(A=>typeof A=="string"&&A.trim().length>0).slice(0,3),b=w.some(A=>f.some(M=>M.repo?.toLowerCase()===A.toLowerCase()));if(w.length>0&&!b)try{let A=await Q(n);for(let M of w){let B=await Ji(A,String(o.owner),M);if(B.renamed){T={warning:`No repositories matched under owner "${o.owner}", but "${o.owner}/${M}" now resolves to "${B.owner}/${B.repo}" \u2014 the repository may have been transferred. Retry scoped to owner:"${B.owner}" (see next.retryUnderCanonicalOwner).`,next:{retryUnderCanonicalOwner:{tool:"ghSearchRepos",query:{...o,owner:B.owner,keywords:[B.repo]},why:"Re-run scoped to the repository's current owner after a detected transfer.",confidence:"exact"}}};break}}}catch{}}let L=[...P??[],...T?[T.warning]:[],...!S&&!T?['No repositories matched. Keywords are ANDed \u2014 try fewer or broader keywords, drop a topic/filter (topics are sparse), or add match:"readme" for full-text search.']:[]],k={...C.data,...L.length>0?{warnings:L}:{},...T?{next:T.next}:{}};return se(o,k,S,x.GITHUB_SEARCH_REPOSITORIES,{rawResponse:Rf([...l,...p])})}catch(s){return be(s,o,void 0,x.GITHUB_SEARCH_REPOSITORIES)}},{toolName:x.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}import{z as bf}from"zod";import{GitHubReposSearchSingleQuerySchema as Cf}from"@octocodeai/octocode-core/schemas";var xf={limit:_(1,100).optional(),page:K.default(1),match:bf.array(bf.enum(["name","description","readme"])).optional().describe("Which text fields to search: name, description, and/or readme. Defaults to name+description; add 'readme' for broader, slower full-text search. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)")},io=X(Cf,xf),so=Y(Z(Cf,xf));function fP(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0,o=typeof r?.status=="number"?r.status:void 0,i=typeof t.path=="string"?t.path.replace(/\/+$/,""):"",s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):"",a=i.split("/").pop()||t.repo,c=o===404?{retryParent:{tool:"ghViewRepoStructure",query:{owner:t.owner,repo:t.repo,...s?{path:s}:{},...t.branch?{branch:t.branch}:{}},why:"Retry at the parent directory \u2014 the path or branch may be wrong.",confidence:"low"},searchPath:{tool:"ghSearchCode",query:{owner:t.owner,repo:t.repo,match:"path",keywords:[a]},why:"Locate the path by name in case it moved or was renamed.",confidence:"low"}}:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...c?{next:c}:{}}}function hP(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Cr(o))continue;let i=r.files.filter(a=>!bn(a)),s=r.folders.filter(a=>!Cr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function Pf(e){let{queries:t,authInfo:n}=e,r=Be(n);return te(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,u=c??await s.provider.resolveDefaultBranch(a),l=await ft(o,()=>s.provider.getRepoStructure(cc(o,u))),p=u,m;if(l.ok===!1&&c){let C=l.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let T=await s.provider.resolveDefaultBranch(a);if(T!==c){let L=await ft(o,()=>s.provider.getRepoStructure(cc(o,T)));L.ok!==!1&&(l=L,p=T,m=`Branch/ref '${c}' was not found. Showing '${T}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(l.ok===!1)return fP(l.result,o);let d=hP(l.response.data.structure),f=Object.keys(d).length>0,g=cm(l.response.data,o,d,p);m&&(g.branchFallback={requestedBranch:c,actualBranch:p,warning:m});let h=g.structure?.find(C=>(C.files?.length??0)>0),y=String(o.path??"").replace(/\/+$/,""),S=h?(()=>{let C=h.dir==="."?h.files[0]:`${h.dir}/${h.files[0]}`;return y?`${y}/${C}`:C})():void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...p?{branch:p}:{}},why:"Read the first listed file",confidence:"low"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...p?{branch:p}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},se(o,g,f,x.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return be(s,o,"Failed to explore repository structure",x.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:x.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}import{GitHubViewRepoStructureQuerySchema as wf}from"@octocodeai/octocode-core/schemas";var Tf={maxDepth:_(0,20).optional(),page:K.default(1),itemsPerPage:_(1,200).optional()},ao=X(wf,Tf),co=Y(Z(wf,Tf));import{ContentSanitizer as wP}from"@octocodeai/octocode-engine/contentSanitizer";import Ef from"path";import{pathValidator as Lf}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as Af}from"@octocodeai/config";function gP(e=Af().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&Lf.addAllowedRoot(t)}function ve(e,t){if(!e.path?.trim()){let s=Le.pathValidationFailed("","path is required");return{isValid:!1,errorResult:F(s,e,{toolName:t})}}gP();let n=process.env.WORKSPACE_ROOT?.trim()||Af().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Ef.isAbsolute(r)?r:Ef.resolve(n,r),i=Lf.validate(o);if(!i.isValid){let s=Le.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:F(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function HB(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:Le.outputTooLarge(e,r).errorCode,hints:[`Found ${e} ${o}${e===1?"":"s"} - exceeds safe limit of ${r}`,"Use charLength to paginate through results",i?"Detailed results increase size - consider using charLength for pagination":"Consider using charLength to paginate large result sets"]}:{shouldBlock:!1}}import{open as yP,readFile as RP,stat as SP}from"fs/promises";var UB={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},Gt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500};function $B(e){return t=>{}}function kf(e,t){return n=>t}function wc(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Tc(e,t,n){return{...e,...wc(t,n)}}function _f(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function If(e,t){try{return{fileStats:await SP(t)}}catch(n){let r=Le.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:F(r,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Of(e){let t=e.startLine!==void 0&&e.endLine!==void 0;return e.minify??(e.fullContent===!0||t?"none":"standard")}function Ff(e,t,n){return n!=="none"?!1:t>Gt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.charLength}function vf(e,t,n){let r=Le.fileTooLarge(e.path,n,Gt.LARGE_FILE_THRESHOLD_KB);return F(r,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function Df(e,t){let n=Le.binaryFileUnsupported(e.path);return F(n,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function Mf(e){let n=Buffer.alloc(8192),r;try{r=await yP(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(kf("binary sample handle close",void 0))}}async function Nf(e,t){try{return{content:await RP(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?Le.fileAccessFailed(e.path,r):Le.fileReadFailed(e.path,r);return{errorResult:F(i,e,{toolName:x.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Gf(e,t){return{status:"empty",errorCode:H.NO_MATCHES,totalLines:t}}function bP(e,t,n){let r=mi(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Gf(e,n)};let o=r.lines.join(`
59
+ `),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,p;if(r.matchRanges.length>0){let m=r.matchRanges[0],d=r.matchRanges[r.matchRanges.length-1];m&&d&&(u=m.start,l=d.end,p=r.matchRanges)}return{resultContent:o,isPartial:!0,actualStartLine:u,actualEndLine:l,matchRanges:p,matchedLines:r.matchingLines,warnings:[c]}}function CP(e){return e.startLine!==void 0&&e.endLine!==void 0}function xP(e,t,n){let r=String(n).length;return e.slice(t-1,n).map((o,i)=>`${String(t+i).padStart(r," ")}\u2192 ${o}`).join(`
60
+ `)}function PP(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:xP(t,i,s),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function Hf(e,t,n){let r=t.split(`
61
+ `),o=rt(t);return e.matchString?bP(e,r,o):CP(e)?PP(e,r,o):{resultContent:t,isPartial:!1}}async function Bf(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,u=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let l="char-limit",p=s;if(s!==void 0){let g=await yi(e,u,s,r);l=g.chunkMode,p=g.length}let m=gi(e,u,p,s!==void 0?{pageSize:s}:void 0),d;if(m.hasMore&&l==="char-limit"&&_r(m.paginatedContent)){let g=m.charOffset+m.charLength;d=await Ir(e,g,r)}let f=_i("localGetFileContent",{path:r,charLength:s??m.charLength,minify:t.minify},m);return{windowedContent:m.paginatedContent,pagination:m,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:l,nextBlockChar:d,next:f,showPagination:s!==void 0||i>0||a}}async function Uf(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=await Bf(u,e,o);l.autoPaginateWarning&&a.push(l.autoPaginateWarning);let p=t.isPartial||l.pagination.hasMore;return{path:c,content:l.windowedContent,contentView:s,returnedChars:l.windowedContent.length,...p&&{isPartial:p},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges},...t.matchedLines!==void 0&&{matchedLines:t.matchedLines}},...n.mtime&&{modified:n.mtime.toISOString()},...l.showPagination&&{pagination:{...Aa(l.pagination),chunkMode:l.chunkMode,...l.nextBlockChar!==void 0&&{nextBlockChar:l.nextBlockChar}}},...l.next?{next:l.next}:{},...a.length>0&&{warnings:a}}}async function Ec(e,t,n,r,o,i,s){let a=await Bf(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",returnedChars:a.windowedContent.length,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...wc(r,o),...a.showPagination&&{pagination:{...Aa(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function Qf(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}function Lc(e,t){let n=wP.sanitizeContent(e,t);return{text:n.content,warning:n.hasSecrets?`Secrets detected and redacted: ${n.secretsDetected.join(", ")}`:void 0}}async function $f(e){let t=Dt();try{let n=ve(e,x.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=_f(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await If(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,u=c/1024;if(await Mf(o))return $(Df(e,o),c);let l=Of(e);if(Ff(e,u,l))return $(vf(e,o,u),c);let{content:p,errorResult:m}=await Nf(e,o);if(m||p===void 0)return m;let d=p.length,f=Buffer.byteLength(p,"utf-8"),g=p,R=e.matchString!==void 0&&l!=="none",h=R?"none":l,y=R&&e.minify!==void 0?`minify:"${e.minify}" is not applied to matchString extractions \u2014 matched slices are returned verbatim so the content always contains the matched text.`:void 0,S=h==="standard"||h==="symbols",C=S?"standard":"none",P;if(h==="symbols"){let b=O.extractSignatures(g,i);if(b===null){let A=fi(g,i);if(A!==null){let M=Lc(A,i);return $(await Ec(e,M.text,rt(g),d,f,M.warning,t),d)}P=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(b!==null){let A=rt(g),M=O.applyContentViewMinification(b,i),B=Lc(M,i);return $(await Ec(e,B.text,A,d,f,B.warning,t),d)}}let T=rt(g),L=Hf(e,g,t),k=b=>{let A=b.content;if(typeof A!="string")return b;let M=Lc(A,i),B=[...P?[P]:[],...y?[y]:[],...M.warning?[M.warning]:[]],I=b.warnings??[];return{...b,content:M.text,...B.length>0&&{warnings:[...I,...B]}}};if(L.earlyResult){let b=L.earlyResult.content,A=S&&typeof b=="string"?{...L.earlyResult,content:O.applyContentViewMinification(b,i)}:L.earlyResult;return $(Tc(k(Qf(A,C)),d,f),d)}let w=await Uf(e,L,s,T,t,S,C);return $(Tc(k(w),d,f),d)}catch(n){return F(n,e,{toolName:x.LOCAL_FETCH_CONTENT})}}import{z as TP}from"zod";import{FetchContentQuerySchema as jf}from"@octocodeai/octocode-core/schemas";var EP=TP.enum(["none","standard","symbols"]).optional(),zf={startLine:On,endLine:On,contextLines:In.default(5),charOffset:_(0,1e8).optional(),charLength:_(1,5e4).optional(),minify:EP},LP=Z(jf,zf),rn=X(jf,zf),uo=Y(LP,{maxQueries:5});async function Wf(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=ke(rn,n);return r.ok===!1?r.error:await $f(r.data)}}),{toolName:x.LOCAL_FETCH_CONTENT,finalize:AP()},e)}function AP(){return({results:e})=>{let t={results:kP(e)},n=Dn(t.results);n&&(t.base=n);let r=Mn(t.results);return r&&(t.shared=r),{structuredContent:Ve(t),text:_P(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function kP(e){return e.map(t=>{let n=structuredClone(t.data),r=typeof n.path=="string"?n.path:void 0;if(t.status!=="error"&&r){let o=$i(r);o&&(n.fileType=o)}return{...t,data:n}})}function _P(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=Nt({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","returnedChars","fileType","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Nt({shared:e.shared},["shared"]).trimEnd()),t.join(`
64
62
  `).trimEnd()+`
65
- `}import{z as Tc}from"zod";import{FindFilesQuerySchema as hP}from"@octocodeai/octocode-core/schemas";var Uf={maxDepth:I(0,100).optional(),minDepth:I(0,100).optional(),limit:I(1,1e4).optional().describe("Discovery cap applied after sort, before pagination \u2014 total results are capped here; itemsPerPage/page page within that cap."),page:q.default(1),itemsPerPage:I(1,50).optional(),excludeDir:Tc.array(Tc.string()).optional().describe("Directory names to prune from the walk. Common generated/vendor dirs are pruned by default (node_modules, .git, dist, build, out, coverage, target, .next, .cache); pass [] to prune nothing, or pass an explicit list to choose pruned dirs.")},Qf=Tc.object(Object.fromEntries(Object.entries(hP.shape).filter(([e])=>e!=="regexType")));function gP(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 yP=Z(Qf,Uf),on=Y(Qf,Uf).superRefine(gP),uo=K(yP,{maxQueries:5});function zn(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 lo(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}function Ec(e){let t=e.indexOf("{");if(t===-1)return[e];let n=e.indexOf("}",t);if(n===-1)return[e];let r=e.slice(0,t),o=e.slice(t+1,n).split(","),i=e.slice(n+1);return o.flatMap(s=>Ec(`${r}${s}${i}`))}function $f(e){let t=new Map,n=0,r=!1,o=0,i=0,s=new Set;for(let a of e){for(let c of a.entries)t.has(c.path)||t.set(c.path,c);n+=a.totalDiscovered,r=r||a.wasCapped,o+=a.skipped,i+=a.permissionDenied;for(let c of a.warnings)s.add(c)}return{entries:[...t.values()],totalDiscovered:n,wasCapped:r,skipped:o,permissionDenied:i,warnings:[...s]}}function Lc(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+lo(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${zn(r)})`}function Ac(e,t){let n=e.length,r=t.itemsPerPage||20,o=Math.max(1,Math.ceil(n/r)),i=t.page||1,s=Math.min(i,o),a=i>o,c=(s-1)*r,u=Math.min(c+r,n),l=s<o;return{paginatedEntries:e.slice(c,u),endIdx:u,pagination:{currentPage:s,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:l,...l?{nextPage:s+1}:{},...a?{outOfRange:!0}:{}}}}function RP(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 po(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}function jf(e){let t=e.find(r=>r.type==="file");if(t)return{fetch:{tool:"localGetFileContent",query:{path:t.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"}};let n=e.find(r=>r.type==="directory");if(n)return{viewStructure:{tool:"localViewStructure",query:{path:n.path},why:"Orient inside the first matched directory before reading files.",confidence:"exact"}}}var SP=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function bP(e,t){let n=t??SP,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function zf(e){let t=e.detail==="full",n=e.detail==="modified"||t,r=n||(e.sortBy||"modified")==="modified";try{let o=ve(e,x.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:bP(i.path,i.excludeDir)},{warnings:a,query:c}=TP(s),u=e.limit??1e4,l={path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,extensions:c.extensions,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.time?.modifiedWithin,modifiedBefore:c.time?.modifiedBefore,accessedWithin:c.time?.accessedWithin,sizeGreater:c.size?.greater,sizeLess:c.size?.less,permissions:c.permissions,executable:c.access==="executable",readable:c.access==="readable",writable:c.access==="writable",excludeDir:c.excludeDir,limit:1e4},p=c.pathPattern?Ec(c.pathPattern):void 0,m=p&&p.length>1?$f(p.map(X=>O.queryFileSystem({...l,pathPattern:X}))):O.queryFileSystem({...l,pathPattern:c.pathPattern}),d=m.totalDiscovered,f=m.wasCapped,g=m.entries.map(X=>CP(X,r)),R=e.sortBy||"modified";xP(g,R,r);let h=g.slice(0,u),y=PP(h,t,n),S=y.length,C=e.itemsPerPage||20,P=e.page||1,T=Math.max(1,Math.ceil(S/C)),L=(P-1)*C,_=Math.min(L+C,S),w=y.slice(L,_),b=S>0&&L>=S,A=w,M=[...m.warnings,...po(m),...f?[`results capped at ${1e4} during the walk before sorting \u2014 sortBy:"${R}" only orders that partial set, not the true top-N across the whole tree`]:[],...b?[`page:${P} is out of range (only ${T} page(s), ${S} total file(s)) \u2014 returned 0 files. Use page:1..${T}.`]:[]],B=[...a,...M],k=P<T,ee={...jf(A)??{},...k?{nextPage:Fn(x.LOCAL_FIND_FILES,{...i,page:P+1},"Continue to the next page of matched files.")}:{}},v={...S===0?{status:"empty"}:{},path:i.path,files:A,pagination:{currentPage:P,totalPages:T,filesPerPage:C,totalFiles:S,hasMore:k,...k?{nextPage:P+1}:{},...f||d>S?{totalFilesFound:d}:{},...b?{outOfRange:!0}:{}},...Object.keys(ee).length>0?{next:ee}:{},...B.length>0&&{warnings:B}};return $(v,m.entries.reduce((X,le)=>X+le.path.length,0))}catch(o){return F(o,e,{toolName:x.LOCAL_FIND_FILES})}}function CP(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 xP(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 PP(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(t?o.size=r.size:o.sizeFormatted=zn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var wP=/^\d+[hdwm]$/;function TP(e){let t=[],n=e.time;if(!n)return{warnings:t,query:e};let r={...n},o=[{key:"modifiedBefore",value:n.modifiedBefore},{key:"modifiedWithin",value:n.modifiedWithin},{key:"accessedWithin",value:n.accessedWithin}];for(let{key:i,value:s}of o)s&&!wP.test(s)&&(t.push(`time.${i}="${s}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete r[i]);return{warnings:t,query:{...e,time:r}}}async function Wf(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=_e(on,n);return r.ok===!1?r.error:await zf(r.data)}}),{toolName:x.LOCAL_FIND_FILES},e)}import{FindDeadCodeQuerySchema as Vf}from"@octocodeai/octocode-core/schemas";var Kf={maxFiles:I(1,5e4).optional(),limit:I(1,5e3).optional(),page:q.default(1),itemsPerPage:I(1,50).optional()},EP=Z(Vf,Kf),sn=Y(Vf,Kf),mo=K(EP,{maxQueries:5});import{completeMetadata as LP}from"@octocodeai/octocode-core";var D=LP.toolNames,ge=D.LSP_GET_SEMANTIC_CONTENT;function fo(e=process.env){let t=e.ENABLE_RELEASES;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function Wn(e=process.env){let t=e.ENABLE_DISCUSSIONS;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var AP=new Set([D.LOCAL_RIPGREP,D.LOCAL_FETCH_CONTENT,D.LOCAL_FIND_FILES,D.LOCAL_VIEW_STRUCTURE,ge]);function eQ(e){return AP.has(e)}import{readFileSync as IP}from"node:fs";import{posix as Xf}from"node:path";var _P=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","async","await"]);function Zi(e){return e?!_P.has(e):!1}import{posix as es}from"node:path";var _c=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],kP={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function Yf(e){return e.split("\\").join("/")}function an(e,t,n){let r=Yf(e);if(!r.startsWith(".")&&!r.startsWith("/"))return null;let o=es.dirname(Yf(t)),i=r.startsWith("/")?r.slice(1):es.normalize(es.join(o,r)),s=[];if(_c.some(c=>i.endsWith(c))){s.push(i);for(let[c,u]of Object.entries(kP))if(i.endsWith(c)){s.push(i.slice(0,-c.length)+u);break}}else{s.push(i);for(let c of _c)s.push(`${i}${c}`);for(let c of _c)s.push(es.join(i,`index${c}`))}for(let c of s)if(n.has(c))return c;return null}var OP=1e6,qf=["node_modules","dist","build","out","coverage",".git","target",".next",".cache"];function FP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vP(e,t){let n=e.match(new RegExp(`\\b${FP(t)}\\b`,"g"));return n?n.length:0}function Jf(e,t,n){let r=O.getSupportedGraphFactExtensions(),i=O.queryFileSystem({path:e,recursive:!0,showHidden:!1,entryType:"f",extensions:r,excludeDir:t,stopAtLimit:!0,limit:n}).entries,s=i.length>=n,a=new Set(i.map(f=>Xf.normalize(f.relativePath.split("\\").join("/")))),c=new Map,u=new Map,l=new Set,p=new Set,m=new Map,d=0;for(let f of i){let g=Xf.normalize(f.relativePath.split("\\").join("/"));if((f.size??0)>OP){d++;continue}let R;try{R=IP(f.path,"utf-8")}catch{d++;continue}let h=O.extractGraphFacts(R,g);if(!h){d++;continue}let y;try{y=JSON.parse(h)}catch{d++;continue}let S=(y.declarations??[]).filter(b=>Zi(b.name)).map(b=>({id:b.id,name:b.name,kind:b.kind,line:b.line,exported:b.exported??!1})),C=new Map;for(let b of S)!b.exported||C.has(b.name)||C.set(b.name,vP(R,b.name));let P=(y.exports??[]).filter(b=>b.source&&b.name!=="*").map(b=>({specifier:b.source,localName:b.localName??b.name,importedName:b.name,line:b.line})),T=(y.calls??[]).filter(b=>b.kind==="dynamic-import").map(b=>b.callee),L={relativePath:g,declarations:S,imports:(y.imports??[]).map(b=>({specifier:b.specifier,localName:b.localName,importedName:b.importedName,line:b.line})),namedReexports:P,calls:(y.calls??[]).filter(b=>b.kind!=="dynamic-import").map(b=>({caller:b.caller,callee:b.callee})),referenceCounts:C};c.set(g,L);let _=new Set,w=new Set;for(let b of[...L.imports,...L.namedReexports]){let A=an(b.specifier,g,a);A&&A!==g&&_.add(A)}for(let b of T){let A=an(b,g,a);A&&A!==g&&(_.add(A),w.add(A),p.add(A))}for(let b of y.exports??[]){if(!b.source||b.name!=="*")continue;let A=an(b.source,g,a);if(A&&A!==g){_.add(A),l.add(A);let M=m.get(A)??[];M.push(g),m.set(A,M)}}u.set(g,{relativePath:g,importsFiles:_,dynamicImportsFiles:w})}return{facts:c,fileGraph:u,filesScanned:c.size,filesSkipped:d,truncated:s,starReexportTargets:l,dynamicImportTargets:p,starReexporters:m}}import{readFileSync as DP}from"node:fs";import{posix as kc}from"node:path";var MP=/(\.(test|spec)\.[^/]+$)|(^|\/)(__tests__|tests?)\//i,NP=/\.(mjs|cjs|jsx?|tsx?)$/i;function GP(e){let t=[];for(let n of e.split(/\s+/)){let r=n.includes("=")?[n,n.slice(n.indexOf("=")+1)]:[n];for(let o of r){let i=o.replace(/^["']|["']$/g,"");NP.test(i)&&!i.startsWith("-")&&t.push(i)}}return t}function Ic(e){return e.split("\\").join("/")}function Zf(e){return e.replace(/^\.\//,"")}var HP=["dist","build","out"],BP={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function eh(e){for(let[t,n]of Object.entries(BP))if(e.endsWith(t))return e.slice(0,-t.length)+n}function UP(e,t){let n=[],r=eh(e);r&&n.push(r);for(let o of HP){let i=`${o}/`;if(!e.startsWith(i))continue;let a=`src/${e.slice(i.length)}`;n.push(a);let c=eh(a);c&&n.push(c)}return n.find(o=>t.has(o))}function ho(e,t){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let n of e)ho(n,t);return}if(e&&typeof e=="object")for(let n of Object.values(e))ho(n,t)}function th(e,t,n,r){let o=[],i=new Set,s=!1;if(t&&t.length>0){let a=Ic(e).replace(/\/$/,"");for(let c of t){let u=Zf(Ic(c));u.startsWith(a+"/")&&(u=u.slice(a.length+1)),u=kc.normalize(u),r.has(u)?i.add(u):o.push(`entrypoint not found in scan: ${c} \u2014 pass it relative to the scanned path (e.g. "src/index.ts"), or as an absolute path under it`)}}else{let a;try{let c=kc.join(e,"package.json");a=JSON.parse(DP(c,"utf-8"))}catch{}if(a){let c=[];if(ho(a.main,c),ho(a.exports,c),ho(a.bin,c),a.scripts&&typeof a.scripts=="object")for(let u of Object.values(a.scripts))typeof u=="string"&&c.push(...GP(u));for(let u of c){let l=kc.normalize(Zf(Ic(u))),p=r.has(l)?l:UP(l,r);p&&i.add(p)}}i.size===0&&(o.push("no entrypoints resolved from package.json \u2014 pass `entrypoints` explicitly, or every export in a reachable file will read as unreachable"),s=!0)}if(n)for(let a of r)MP.test(a)&&i.add(a);return{entrypoints:[...i],warnings:o,lowConfidence:s}}function Oc(e,t){let n=new Set,r=[];for(let o of t)n.has(o)||(n.add(o),r.push(o));for(;r.length>0;){let o=r.pop(),i=e.get(o);if(i)for(let s of i.importsFiles)n.has(s)||(n.add(s),r.push(s))}return n}function nh(e){let t=0,n=new Map,r=new Map,o=new Set,i=[],s=[],a=[];for(let c of e.keys())if(!n.has(c))for(a.push({node:c,iterator:(e.get(c)?.importsFiles??new Set).values()}),n.set(c,t),r.set(c,t),t++,i.push(c),o.add(c);a.length>0;){let u=a[a.length-1],l=u.iterator.next();if(!l.done){let p=l.value;if(!n.has(p))n.set(p,t),r.set(p,t),t++,i.push(p),o.add(p),a.push({node:p,iterator:(e.get(p)?.importsFiles??new Set).values()});else if(o.has(p)){let m=r.get(u.node),d=n.get(p);r.set(u.node,Math.min(m,d))}continue}if(a.pop(),a.length>0){let p=a[a.length-1],m=r.get(p.node),d=r.get(u.node);r.set(p.node,Math.min(m,d))}if(r.get(u.node)===n.get(u.node)){let p=[],m;do m=i.pop(),o.delete(m),p.push(m);while(m!==u.node);(p.length>1||(e.get(p[0])?.importsFiles.has(p[0])??!1))&&s.push({files:p})}}return s}function go(e,t){return`${e}::${t}`}function Fc(e,t,n,r,o,i,s){let a=go(e,t);if(s.has(a))return!1;if(n.has(e)||r.has(a))return!0;s.add(a);for(let c of o.get(a)??[])if(Fc(c.file,c.localName,n,r,o,i,s))return!0;for(let c of i.get(e)??[])if(Fc(c,t,n,r,o,i,s))return!0;return!1}function rh(e,t,n,r,o,i){let s=new Set(t.declarations.filter(l=>l.exported).map(l=>l.name)),a=new Set;for(let l of s)Fc(e,l,n,r,o,i,new Set)&&a.add(l);let c=l=>!s.has(l)||a.has(l),u=!0;for(;u;){u=!1;for(let l of s){if(a.has(l))continue;let p=t.calls.filter(f=>f.callee===l);if(p.some(f=>f.caller!==l&&c(f.caller))){a.add(l),u=!0;continue}let m=p.filter(f=>f.caller===l||!c(f.caller)).length;(t.referenceCounts.get(l)??0)-m>1&&(a.add(l),u=!0)}}return a}function oh(e,t){let n=t.excludeDir&&t.excludeDir.length>0?t.excludeDir:qf,r=t.maxFiles??2e4,{facts:o,fileGraph:i,filesScanned:s,filesSkipped:a,truncated:c,dynamicImportTargets:u,starReexporters:l}=Jf(e,n,r),p=new Set(o.keys()),{entrypoints:m,warnings:d,lowConfidence:f}=th(e,t.entrypoints,t.includeTests??!0,p);c&&d.push(`scan stopped at maxFiles (${r}) \u2014 results are partial, not a full-repo verdict`);let g=m.filter(v=>{let X=o.get(v);return(i.get(v)?.importsFiles.size??0)===0&&(X?.declarations.length??0)===0&&(X?.namedReexports.length??0)===0}),R=g.length>0;R&&d.push(`${g.length} entrypoint file(s) parsed to no imports/exports (likely an extractor parse failure on that file) \u2014 reachability from them is unreliable, so "unreachable-file" results here are low-confidence and may be false positives: ${g.join(", ")}`);let h=Oc(i,m),y=new Set(m),S=new Map([...i].map(([v,X])=>[v,{relativePath:X.relativePath,importsFiles:new Set([...X.importsFiles].filter(le=>!X.dynamicImportsFiles.has(le))),dynamicImportsFiles:new Set}])),C=Oc(S,m),P=[...h].filter(v=>!C.has(v)).sort();P.length>0&&d.push(`${P.length} file(s) reachable only through a dynamic import() \u2014 lower confidence than static analysis, verify with lspGetSemantics before treating as proof: ${P.join(", ")}`);let T=new Map;for(let[v,X]of o){let le=new Map;for(let ae of X.imports){let pe=an(ae.specifier,v,p);pe&&le.set(ae.localName,pe)}T.set(v,le)}let L=new Set,_=new Map;for(let v of h){let X=o.get(v);if(!X)continue;let le=T.get(v);for(let ae of X.imports){let pe=le?.get(ae.localName);pe&&L.add(go(pe,ae.importedName))}for(let ae of X.namedReexports){let pe=an(ae.specifier,v,p);if(!pe)continue;let Me=go(pe,ae.importedName),jt=_.get(Me)??[];jt.push({file:v,localName:ae.localName}),_.set(Me,jt)}}let w=new Map;for(let[v,X]of l){let le=X.filter(ae=>h.has(ae));le.length>0&&w.set(v,le)}let b=new Set(w.keys()),A=[],M=nh(i),B=new Map,k=[],U=0;for(let v of M){if(!v.files.every(ae=>!h.has(ae)))continue;let le=U++;for(let ae of v.files)B.set(ae,le);k.push({id:le,files:v.files,reason:"mutually-referencing cluster with no path from any entrypoint \u2014 each file looks locally referenced by the others, but the cluster as a whole is unreachable"})}let ee=new Map;for(let[v,X]of o){let le=y.has(v),ae=h.has(v);for(let pe of X.declarations){if(!pe.exported)continue;if(!ae){let jt=B.get(v);A.push({file:v,name:pe.name,kind:pe.kind,line:pe.line,reason:jt!==void 0?"dead-cluster":"unreachable-file",...jt!==void 0?{clusterId:jt}:{}});continue}if(le||b.has(v)||u.has(v))continue;let Me=ee.get(v);Me||(Me=rh(v,X,y,L,_,w),ee.set(v,Me)),Me.has(pe.name)||A.push({file:v,name:pe.name,kind:pe.kind,line:pe.line,reason:"unreferenced-export",viaHeuristic:_.has(go(v,pe.name))?"reexport-chain":"lexical-count"})}}return{filesScanned:s,filesSkipped:a,entrypointsResolved:m,deadExports:A,deadClusters:k,warnings:d,...f||R?{confidence:"low"}:{}}}var QP=100;function $P(e,t,n){let r=Math.max(1,Math.ceil(e.length/n)),o=Math.min(Math.max(1,t),r),i=(o-1)*n;return{pageItems:e.slice(i,i+n),currentPage:o,totalPages:r,hasMore:o<r,outOfRange:t>r}}async function ih(e){try{let t=ve(e,x.LOCAL_FIND_DEAD_CODE);if(!t.isValid)return t.errorResult;let n=oh(t.sanitizedPath,e),r=e.itemsPerPage??QP,o=e.page??1,{pageItems:i,currentPage:s,totalPages:a,hasMore:c,outOfRange:u}=$P(n.deadExports,o,r),l=[...n.warnings,...u?[`page:${o} is out of range (only ${a} page(s), ${n.deadExports.length} total candidates) \u2014 returned page ${s} instead.`]:[]],p={path:e.path,filesScanned:n.filesScanned,filesSkipped:n.filesSkipped,entrypointsResolved:n.entrypointsResolved,deadExports:i,deadClusters:n.deadClusters,pagination:{currentPage:s,totalPages:a,entriesPerPage:r,totalEntries:n.deadExports.length,hasMore:c,...u?{outOfRange:!0}:{}},...l.length>0?{warnings:l}:{},...n.confidence?{confidence:n.confidence}:{}};c&&(p.next={nextPage:Fn(x.LOCAL_FIND_DEAD_CODE,{...e,page:s+1},"Continue to the next page of dead-export candidates.")});let m=i[0];if(m){let d=t.sanitizedPath.replace(/\/+$/,"");p.next={...p.next,verifyReferences:{tool:ge,query:{type:"references",uri:`${d}/${m.file}`,symbolName:m.name,lineHint:m.line,includeDeclaration:!1,groupByFile:!0},why:`Verify candidate "${m.name}" before any delete claim \u2014 zero references = confirmed dead. Repeat per candidate using each entry's file/name/line; start with viaHeuristic:"reexport-chain" candidates (most fragile).`,confidence:"high"}}}return p}catch(t){let n=Le.toolExecutionFailed(x.LOCAL_FIND_DEAD_CODE,t instanceof Error?t:new Error(String(t)));return F(n,e,{toolName:x.LOCAL_FIND_DEAD_CODE})}}async function sh(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_FIND_DEAD_CODE,query:n,contextMessage:"localFindDeadCode execution failed",execute:async()=>{let r=_e(sn,n);return r.ok===!1?r.error:await ih(r.data)}}),{toolName:x.LOCAL_FIND_DEAD_CODE},e)}import{z as Ht}from"zod";import{RipgrepQuerySchema as ah}from"@octocodeai/octocode-core/schemas";var jP=["paginated","discovery","detailed","structural"],zP=["semanticRanking"],ch={mode:Ht.enum(jP).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghSearchPullRequests\'s `content.patches.mode` \u2014 different concepts sharing this name.)'),searchText:Ht.string().optional().describe('The search pattern. regex:"fixed" for a literal match, "perl" for advanced features (lookaheads, backreferences), else "smart". (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)'),output:Ht.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content").describe('"content" (default) matches with line text; "files"/"filesWithout" return matching/non-matching paths; "countLines"/"countMatches" return per-file counts; "matchOnly" returns just the matched substring (required for unique/matchWindow). ("files" is unlike localViewStructure\'s `filesOnly`, which filters a directory listing to file entries.)'),pattern:Ht.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Modifiers are part of the node \u2014 `function $NAME` does not match `async function` or `export function`; include the modifiers or use a YAML `kind` rule for modifier-agnostic matches. Use this to find syntax shape, then use lspGetSemantics for semantic proof."),maxDepth:I(0,20).optional().describe("Keep files at most this many directory levels below the search root (0 = files directly in the root). Structural mode pushes this into the native walker; text/regex mode applies it after the native search and emits a warning when it filters deeper matches."),rule:Ht.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),captureText:Ht.boolean().optional().describe("Structural only: return full verbatim capture text for `$$$` list metavars (bodies, arg lists). Default false \u2014 list-capture text is omitted from `metavars`, and `metavarRanges` entries are comment-pruned and truncated to keep results lean; ranges always remain as line anchors."),contextLines:In,matchContentLength:I(1,1e5).optional().default(500),maxMatchesPerFile:I(1,1e5).optional(),maxFiles:I(1,1e5).optional(),matchPage:q.optional(),itemsPerPage:I(1,1e3).optional(),page:q.default(1),unique:Ht.enum(["off","list","count"]).optional().default("off").describe('Needs output:"matchOnly". "list" returns each matched value once per file; "count" adds its frequency.')},WP={...ch,semanticRanking:Ht.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},VP=Z(ah,WP),KP=Y(ah,ch,{strict:!0,omit:zP}),ht=KP.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let n=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(n){let r=n[0].slice(2);t.addIssue({code:"custom",message:`\`${n[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),yo=K(VP,{maxQueries:5});import{validateRipgrepQuery as ww}from"@octocodeai/octocode-core/schemas/runtime";var vc=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],re={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,testPathPenalty:-3.5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Dc=2e3,Mc=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,uh={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+['"]/]},Ro={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...uh},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...uh},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/]}},Nc=/^\s*#{1,6}\s/,So=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,YP=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,XP=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,qP=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,JP=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,ZP=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,ew=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,tw=new Set(["typescript","javascript","rust","python","go","java","scala"]),ts=/\.([a-z0-9]+)$/i;function bo(e){return ts.exec(e)?.[1]?.toLowerCase()??""}function nw(e){let t=bo(e);if(!t)return!1;for(let n of tw)if(Ro[n].extensions.includes(t))return!0;return!1}function Gc(e,t,n){if(n&&n!=="auto")return Ro[n];let r=bo(e),o=(t??"").toLowerCase();for(let i of vc){let s=Ro[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of vc){let s=Ro[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Ro.generic}function ns(e){return YP.test(e)?"generated":qP.test(e)?"fixture":XP.test(e)?"test":ZP.test(e)?"config":JP.test(e)?"docs":!So.test(e)&&(ew.test(e)||nw(e))?"source":"unknown"}function Hc(e){if(!e)return!1;if(So.test(e))return!0;let t=ns(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}function Bc(e,t,n,r={}){if(t==="matchCount"){let m=[...e].sort(lh);return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="path"){let m=[...e].sort((d,f)=>d.path.localeCompare(f.path));return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Dc,i=e,s=[],a=0;if(e.length>o){let m=[...e].sort(lh);i=m.slice(0,o),s=m.slice(o),a=s.length}let c=jc(i,n),u=i.map(m=>{try{return{file:m,s:zc(m,n,c)}}catch{return{file:m,s:rw()}}});u.sort((m,d)=>{if(d.s.score!==m.s.score)return d.s.score-m.s.score;let f=(d.file.matchCount??0)-(m.file.matchCount??0);return f!==0?f:m.file.path.localeCompare(d.file.path)});let l=[...u.map(m=>m.file),...s],p={files:r.sortReverse?l.reverse():l,cappedCandidates:a};return r.debug&&(p.debug=new Map(u.map(m=>[m.file.path,m.s]))),p}function rw(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function lh(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function Co(e,t){for(let n of e)if(n.test(t))return!0;return!1}function rs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Uc(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function Qc(e,t,n){if(e.indexOf(`
63
+ `}import{z as Ac}from"zod";import{FindFilesQuerySchema as IP}from"@octocodeai/octocode-core/schemas";var Vf={maxDepth:_(0,100).optional(),minDepth:_(0,100).optional(),limit:_(1,1e4).optional().describe("Discovery cap applied after sort, before pagination \u2014 total results are capped here; itemsPerPage/page page within that cap."),page:K.default(1),itemsPerPage:_(1,50).optional(),excludeDir:Ac.array(Ac.string()).optional().describe("Directory names to prune from the walk. Common generated/vendor dirs are pruned by default (node_modules, .git, dist, build, out, coverage, target, .next, .cache); pass [] to prune nothing, or pass an explicit list to choose pruned dirs.")},Kf=Ac.object(Object.fromEntries(Object.entries(IP.shape).filter(([e])=>e!=="regexType")));function OP(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 FP=Z(Kf,Vf),on=X(Kf,Vf).superRefine(OP),lo=Y(FP,{maxQueries:5});function zn(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 po(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}function kc(e){let t=e.indexOf("{");if(t===-1)return[e];let n=e.indexOf("}",t);if(n===-1)return[e];let r=e.slice(0,t),o=e.slice(t+1,n).split(","),i=e.slice(n+1);return o.flatMap(s=>kc(`${r}${s}${i}`))}function Yf(e){let t=new Map,n=0,r=!1,o=0,i=0,s=new Set;for(let a of e){for(let c of a.entries)t.has(c.path)||t.set(c.path,c);n+=a.totalDiscovered,r=r||a.wasCapped,o+=a.skipped,i+=a.permissionDenied;for(let c of a.warnings)s.add(c)}return{entries:[...t.values()],totalDiscovered:n,wasCapped:r,skipped:o,permissionDenied:i,warnings:[...s]}}function _c(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+po(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${zn(r)})`}function Ic(e,t){let n=e.length,r=t.itemsPerPage||20,o=Math.max(1,Math.ceil(n/r)),i=t.page||1,s=Math.min(i,o),a=i>o,c=(s-1)*r,u=Math.min(c+r,n),l=s<o;return{paginatedEntries:e.slice(c,u),endIdx:u,pagination:{currentPage:s,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:l,...l?{nextPage:s+1}:{},...a?{outOfRange:!0}:{}}}}function vP(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 mo(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}function Xf(e){let t=e.find(r=>r.type==="file");if(t)return{fetch:{tool:"localGetFileContent",query:{path:t.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"}};let n=e.find(r=>r.type==="directory");if(n)return{viewStructure:{tool:"localViewStructure",query:{path:n.path},why:"Orient inside the first matched directory before reading files.",confidence:"exact"}}}var DP=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function MP(e,t){let n=t??DP,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function qf(e){let t=e.detail==="full",n=e.detail==="modified"||t,r=n||(e.sortBy||"modified")==="modified";try{let o=ve(e,x.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:MP(i.path,i.excludeDir)},{warnings:a,query:c}=UP(s),u=e.limit??1e4,l={path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,extensions:c.extensions,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.time?.modifiedWithin,modifiedBefore:c.time?.modifiedBefore,accessedWithin:c.time?.accessedWithin,sizeGreater:c.size?.greater,sizeLess:c.size?.less,permissions:c.permissions,executable:c.access==="executable",readable:c.access==="readable",writable:c.access==="writable",excludeDir:c.excludeDir,limit:1e4},p=c.pathPattern?kc(c.pathPattern):void 0,m=p&&p.length>1?Yf(p.map(q=>O.queryFileSystem({...l,pathPattern:q}))):O.queryFileSystem({...l,pathPattern:c.pathPattern}),d=m.totalDiscovered,f=m.wasCapped,g=m.entries.map(q=>NP(q,r)),R=e.sortBy||"modified";GP(g,R,r);let h=g.slice(0,u),y=HP(h,t,n),S=y.length,C=e.itemsPerPage||20,P=e.page||1,T=Math.max(1,Math.ceil(S/C)),L=(P-1)*C,k=Math.min(L+C,S),w=y.slice(L,k),b=S>0&&L>=S,A=w,M=[...m.warnings,...mo(m),...f?[`results capped at ${1e4} during the walk before sorting \u2014 sortBy:"${R}" only orders that partial set, not the true top-N across the whole tree`]:[],...b?[`page:${P} is out of range (only ${T} page(s), ${S} total file(s)) \u2014 returned 0 files. Use page:1..${T}.`]:[]],B=[...a,...M],I=P<T,ee={...Xf(A)??{},...I?{nextPage:Fn(x.LOCAL_FIND_FILES,{...i,page:P+1},"Continue to the next page of matched files.")}:{}},v={...S===0?{status:"empty"}:{},path:i.path,files:A,pagination:{currentPage:P,totalPages:T,filesPerPage:C,totalFiles:S,hasMore:I,...I?{nextPage:P+1}:{},...f||d>S?{totalFilesFound:d}:{},...b?{outOfRange:!0}:{}},...Object.keys(ee).length>0?{next:ee}:{},...B.length>0&&{warnings:B}};return $(v,m.entries.reduce((q,le)=>q+le.path.length,0))}catch(o){return F(o,e,{toolName:x.LOCAL_FIND_FILES})}}function NP(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 GP(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 HP(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(t?o.size=r.size:o.sizeFormatted=zn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var BP=/^\d+[hdwm]$/;function UP(e){let t=[],n=e.time;if(!n)return{warnings:t,query:e};let r={...n},o=[{key:"modifiedBefore",value:n.modifiedBefore},{key:"modifiedWithin",value:n.modifiedWithin},{key:"accessedWithin",value:n.accessedWithin}];for(let{key:i,value:s}of o)s&&!BP.test(s)&&(t.push(`time.${i}="${s}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete r[i]);return{warnings:t,query:{...e,time:r}}}async function Jf(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=ke(on,n);return r.ok===!1?r.error:await qf(r.data)}}),{toolName:x.LOCAL_FIND_FILES},e)}import{FindDeadCodeQuerySchema as Zf}from"@octocodeai/octocode-core/schemas";var eh={maxFiles:_(1,5e4).optional(),limit:_(1,5e3).optional(),page:K.default(1),itemsPerPage:_(1,50).optional()},QP=Z(Zf,eh),sn=X(Zf,eh),fo=Y(QP,{maxQueries:5});import{completeMetadata as $P}from"@octocodeai/octocode-core";var D=$P.toolNames,ge=D.LSP_GET_SEMANTIC_CONTENT;function ho(e=process.env){let t=e.ENABLE_RELEASES;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function Wn(e=process.env){let t=e.ENABLE_DISCUSSIONS;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var jP=new Set([D.LOCAL_RIPGREP,D.LOCAL_FETCH_CONTENT,D.LOCAL_FIND_FILES,D.LOCAL_VIEW_STRUCTURE,ge]);function bQ(e){return jP.has(e)}import{readFileSync as VP}from"node:fs";import{posix as nh}from"node:path";var zP=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","async","await"]);function ts(e){return e?!zP.has(e):!1}import{posix as ns}from"node:path";var Oc=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],WP={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function th(e){return e.split("\\").join("/")}function an(e,t,n){let r=th(e);if(!r.startsWith(".")&&!r.startsWith("/"))return null;let o=ns.dirname(th(t)),i=r.startsWith("/")?r.slice(1):ns.normalize(ns.join(o,r)),s=[];if(Oc.some(c=>i.endsWith(c))){s.push(i);for(let[c,u]of Object.entries(WP))if(i.endsWith(c)){s.push(i.slice(0,-c.length)+u);break}}else{s.push(i);for(let c of Oc)s.push(`${i}${c}`);for(let c of Oc)s.push(ns.join(i,`index${c}`))}for(let c of s)if(n.has(c))return c;return null}var KP=1e6,rh=["node_modules","dist","build","out","coverage",".git","target",".next",".cache"];function YP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XP(e,t){let n=e.match(new RegExp(`\\b${YP(t)}\\b`,"g"));return n?n.length:0}function oh(e,t,n){let r=O.getSupportedGraphFactExtensions(),i=O.queryFileSystem({path:e,recursive:!0,showHidden:!1,entryType:"f",extensions:r,excludeDir:t,stopAtLimit:!0,limit:n}).entries,s=i.length>=n,a=new Set(i.map(f=>nh.normalize(f.relativePath.split("\\").join("/")))),c=new Map,u=new Map,l=new Set,p=new Set,m=new Map,d=0;for(let f of i){let g=nh.normalize(f.relativePath.split("\\").join("/"));if((f.size??0)>KP){d++;continue}let R;try{R=VP(f.path,"utf-8")}catch{d++;continue}let h=O.extractGraphFacts(R,g);if(!h){d++;continue}let y;try{y=JSON.parse(h)}catch{d++;continue}let S=(y.declarations??[]).filter(b=>ts(b.name)).map(b=>({id:b.id,name:b.name,kind:b.kind,line:b.line,exported:b.exported??!1})),C=new Map;for(let b of S)!b.exported||C.has(b.name)||C.set(b.name,XP(R,b.name));let P=(y.exports??[]).filter(b=>b.source&&b.name!=="*").map(b=>({specifier:b.source,localName:b.localName??b.name,importedName:b.name,line:b.line})),T=(y.calls??[]).filter(b=>b.kind==="dynamic-import").map(b=>b.callee),L={relativePath:g,declarations:S,imports:(y.imports??[]).map(b=>({specifier:b.specifier,localName:b.localName,importedName:b.importedName,line:b.line})),namedReexports:P,calls:(y.calls??[]).filter(b=>b.kind!=="dynamic-import").map(b=>({caller:b.caller,callee:b.callee})),referenceCounts:C};c.set(g,L);let k=new Set,w=new Set;for(let b of[...L.imports,...L.namedReexports]){let A=an(b.specifier,g,a);A&&A!==g&&k.add(A)}for(let b of T){let A=an(b,g,a);A&&A!==g&&(k.add(A),w.add(A),p.add(A))}for(let b of y.exports??[]){if(!b.source||b.name!=="*")continue;let A=an(b.source,g,a);if(A&&A!==g){k.add(A),l.add(A);let M=m.get(A)??[];M.push(g),m.set(A,M)}}u.set(g,{relativePath:g,importsFiles:k,dynamicImportsFiles:w})}return{facts:c,fileGraph:u,filesScanned:c.size,filesSkipped:d,truncated:s,starReexportTargets:l,dynamicImportTargets:p,starReexporters:m}}import{readFileSync as qP}from"node:fs";import{posix as Fc}from"node:path";var JP=/(\.(test|spec)\.[^/]+$)|(^|\/)(__tests__|tests?)\//i,ZP=/\.(mjs|cjs|jsx?|tsx?)$/i;function ew(e){let t=[];for(let n of e.split(/\s+/)){let r=n.includes("=")?[n,n.slice(n.indexOf("=")+1)]:[n];for(let o of r){let i=o.replace(/^["']|["']$/g,"");ZP.test(i)&&!i.startsWith("-")&&t.push(i)}}return t}function vc(e){return e.split("\\").join("/")}function ih(e){return e.replace(/^\.\//,"")}var tw=["dist","build","out"],nw={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function sh(e){for(let[t,n]of Object.entries(nw))if(e.endsWith(t))return e.slice(0,-t.length)+n}function rw(e,t){let n=[],r=sh(e);r&&n.push(r);for(let o of tw){let i=`${o}/`;if(!e.startsWith(i))continue;let a=`src/${e.slice(i.length)}`;n.push(a);let c=sh(a);c&&n.push(c)}return n.find(o=>t.has(o))}function go(e,t){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let n of e)go(n,t);return}if(e&&typeof e=="object")for(let n of Object.values(e))go(n,t)}function ah(e,t,n,r){let o=[],i=new Set,s=!1;if(t&&t.length>0){let a=vc(e).replace(/\/$/,"");for(let c of t){let u=ih(vc(c));u.startsWith(a+"/")&&(u=u.slice(a.length+1)),u=Fc.normalize(u),r.has(u)?i.add(u):o.push(`entrypoint not found in scan: ${c} \u2014 pass it relative to the scanned path (e.g. "src/index.ts"), or as an absolute path under it`)}}else{let a;try{let c=Fc.join(e,"package.json");a=JSON.parse(qP(c,"utf-8"))}catch{}if(a){let c=[];if(go(a.main,c),go(a.exports,c),go(a.bin,c),a.scripts&&typeof a.scripts=="object")for(let u of Object.values(a.scripts))typeof u=="string"&&c.push(...ew(u));for(let u of c){let l=Fc.normalize(ih(vc(u))),p=r.has(l)?l:rw(l,r);p&&i.add(p)}}i.size===0&&(o.push("no entrypoints resolved from package.json \u2014 pass `entrypoints` explicitly, or every export in a reachable file will read as unreachable"),s=!0)}if(n)for(let a of r)JP.test(a)&&i.add(a);return{entrypoints:[...i],warnings:o,lowConfidence:s}}function Dc(e,t){let n=new Set,r=[];for(let o of t)n.has(o)||(n.add(o),r.push(o));for(;r.length>0;){let o=r.pop(),i=e.get(o);if(i)for(let s of i.importsFiles)n.has(s)||(n.add(s),r.push(s))}return n}function ch(e){let t=0,n=new Map,r=new Map,o=new Set,i=[],s=[],a=[];for(let c of e.keys())if(!n.has(c))for(a.push({node:c,iterator:(e.get(c)?.importsFiles??new Set).values()}),n.set(c,t),r.set(c,t),t++,i.push(c),o.add(c);a.length>0;){let u=a[a.length-1],l=u.iterator.next();if(!l.done){let p=l.value;if(!n.has(p))n.set(p,t),r.set(p,t),t++,i.push(p),o.add(p),a.push({node:p,iterator:(e.get(p)?.importsFiles??new Set).values()});else if(o.has(p)){let m=r.get(u.node),d=n.get(p);r.set(u.node,Math.min(m,d))}continue}if(a.pop(),a.length>0){let p=a[a.length-1],m=r.get(p.node),d=r.get(u.node);r.set(p.node,Math.min(m,d))}if(r.get(u.node)===n.get(u.node)){let p=[],m;do m=i.pop(),o.delete(m),p.push(m);while(m!==u.node);(p.length>1||(e.get(p[0])?.importsFiles.has(p[0])??!1))&&s.push({files:p})}}return s}function yo(e,t){return`${e}::${t}`}function Mc(e,t,n,r,o,i,s){let a=yo(e,t);if(s.has(a))return!1;if(n.has(e)||r.has(a))return!0;s.add(a);for(let c of o.get(a)??[])if(Mc(c.file,c.localName,n,r,o,i,s))return!0;for(let c of i.get(e)??[])if(Mc(c,t,n,r,o,i,s))return!0;return!1}function uh(e,t,n,r,o,i){let s=new Set(t.declarations.filter(l=>l.exported).map(l=>l.name)),a=new Set;for(let l of s)Mc(e,l,n,r,o,i,new Set)&&a.add(l);let c=l=>!s.has(l)||a.has(l),u=!0;for(;u;){u=!1;for(let l of s){if(a.has(l))continue;let p=t.calls.filter(f=>f.callee===l);if(p.some(f=>f.caller!==l&&c(f.caller))){a.add(l),u=!0;continue}let m=p.filter(f=>f.caller===l||!c(f.caller)).length;(t.referenceCounts.get(l)??0)-m>1&&(a.add(l),u=!0)}}return a}function lh(e,t){let n=t.excludeDir&&t.excludeDir.length>0?t.excludeDir:rh,r=t.maxFiles??2e4,{facts:o,fileGraph:i,filesScanned:s,filesSkipped:a,truncated:c,dynamicImportTargets:u,starReexporters:l}=oh(e,n,r),p=new Set(o.keys()),{entrypoints:m,warnings:d,lowConfidence:f}=ah(e,t.entrypoints,t.includeTests??!0,p);c&&d.push(`scan stopped at maxFiles (${r}) \u2014 results are partial, not a full-repo verdict`);let g=m.filter(v=>{let q=o.get(v);return(i.get(v)?.importsFiles.size??0)===0&&(q?.declarations.length??0)===0&&(q?.namedReexports.length??0)===0}),R=g.length>0;R&&d.push(`${g.length} entrypoint file(s) parsed to no imports/exports (likely an extractor parse failure on that file) \u2014 reachability from them is unreliable, so "unreachable-file" results here are low-confidence and may be false positives: ${g.join(", ")}`);let h=Dc(i,m),y=new Set(m),S=new Map([...i].map(([v,q])=>[v,{relativePath:q.relativePath,importsFiles:new Set([...q.importsFiles].filter(le=>!q.dynamicImportsFiles.has(le))),dynamicImportsFiles:new Set}])),C=Dc(S,m),P=[...h].filter(v=>!C.has(v)).sort();P.length>0&&d.push(`${P.length} file(s) reachable only through a dynamic import() \u2014 lower confidence than static analysis, verify with lspGetSemantics before treating as proof: ${P.join(", ")}`);let T=new Map;for(let[v,q]of o){let le=new Map;for(let ae of q.imports){let pe=an(ae.specifier,v,p);pe&&le.set(ae.localName,pe)}T.set(v,le)}let L=new Set,k=new Map;for(let v of h){let q=o.get(v);if(!q)continue;let le=T.get(v);for(let ae of q.imports){let pe=le?.get(ae.localName);pe&&L.add(yo(pe,ae.importedName))}for(let ae of q.namedReexports){let pe=an(ae.specifier,v,p);if(!pe)continue;let Me=yo(pe,ae.importedName),jt=k.get(Me)??[];jt.push({file:v,localName:ae.localName}),k.set(Me,jt)}}let w=new Map;for(let[v,q]of l){let le=q.filter(ae=>h.has(ae));le.length>0&&w.set(v,le)}let b=new Set(w.keys()),A=[],M=ch(i),B=new Map,I=[],U=0;for(let v of M){if(!v.files.every(ae=>!h.has(ae)))continue;let le=U++;for(let ae of v.files)B.set(ae,le);I.push({id:le,files:v.files,reason:"mutually-referencing cluster with no path from any entrypoint \u2014 each file looks locally referenced by the others, but the cluster as a whole is unreachable"})}let ee=new Map;for(let[v,q]of o){let le=y.has(v),ae=h.has(v);for(let pe of q.declarations){if(!pe.exported)continue;if(!ae){let jt=B.get(v);A.push({file:v,name:pe.name,kind:pe.kind,line:pe.line,reason:jt!==void 0?"dead-cluster":"unreachable-file",...jt!==void 0?{clusterId:jt}:{}});continue}if(le||b.has(v)||u.has(v))continue;let Me=ee.get(v);Me||(Me=uh(v,q,y,L,k,w),ee.set(v,Me)),Me.has(pe.name)||A.push({file:v,name:pe.name,kind:pe.kind,line:pe.line,reason:"unreferenced-export",viaHeuristic:k.has(yo(v,pe.name))?"reexport-chain":"lexical-count"})}}return{filesScanned:s,filesSkipped:a,entrypointsResolved:m,deadExports:A,deadClusters:I,warnings:d,...f||R?{confidence:"low"}:{}}}var ow=100;function iw(e,t,n){let r=Math.max(1,Math.ceil(e.length/n)),o=Math.min(Math.max(1,t),r),i=(o-1)*n;return{pageItems:e.slice(i,i+n),currentPage:o,totalPages:r,hasMore:o<r,outOfRange:t>r}}async function ph(e){try{let t=ve(e,x.LOCAL_FIND_DEAD_CODE);if(!t.isValid)return t.errorResult;let n=lh(t.sanitizedPath,e),r=e.itemsPerPage??ow,o=e.page??1,{pageItems:i,currentPage:s,totalPages:a,hasMore:c,outOfRange:u}=iw(n.deadExports,o,r),l=[...n.warnings,...u?[`page:${o} is out of range (only ${a} page(s), ${n.deadExports.length} total candidates) \u2014 returned page ${s} instead.`]:[]],p={path:e.path,filesScanned:n.filesScanned,filesSkipped:n.filesSkipped,entrypointsResolved:n.entrypointsResolved,deadExports:i,deadClusters:n.deadClusters,pagination:{currentPage:s,totalPages:a,entriesPerPage:r,totalEntries:n.deadExports.length,hasMore:c,...u?{outOfRange:!0}:{}},...l.length>0?{warnings:l}:{},...n.confidence?{confidence:n.confidence}:{}};c&&(p.next={nextPage:Fn(x.LOCAL_FIND_DEAD_CODE,{...e,page:s+1},"Continue to the next page of dead-export candidates.")});let m=i[0];if(m){let d=t.sanitizedPath.replace(/\/+$/,"");p.next={...p.next,verifyReferences:{tool:ge,query:{type:"references",uri:`${d}/${m.file}`,symbolName:m.name,lineHint:m.line,includeDeclaration:!1,groupByFile:!0},why:`Verify candidate "${m.name}" before any delete claim \u2014 zero references = confirmed dead. Repeat per candidate using each entry's file/name/line; start with viaHeuristic:"reexport-chain" candidates (most fragile).`,confidence:"high"}}}return p}catch(t){let n=Le.toolExecutionFailed(x.LOCAL_FIND_DEAD_CODE,t instanceof Error?t:new Error(String(t)));return F(n,e,{toolName:x.LOCAL_FIND_DEAD_CODE})}}async function dh(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_FIND_DEAD_CODE,query:n,contextMessage:"localFindDeadCode execution failed",execute:async()=>{let r=ke(sn,n);return r.ok===!1?r.error:await ph(r.data)}}),{toolName:x.LOCAL_FIND_DEAD_CODE},e)}import{z as Ht}from"zod";import{RipgrepQuerySchema as mh}from"@octocodeai/octocode-core/schemas";var sw=["paginated","discovery","detailed","structural"],aw=["semanticRanking"],fh={mode:Ht.enum(sw).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghSearchPullRequests\'s `content.patches.mode` \u2014 different concepts sharing this name.)'),searchText:Ht.string().optional().describe('The search pattern. regex:"fixed" for a literal match, "perl" for advanced features (lookaheads, backreferences), else "smart". (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)'),output:Ht.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content").describe('"content" (default) matches with line text; "files"/"filesWithout" return matching/non-matching paths; "countLines"/"countMatches" return per-file counts; "matchOnly" returns just the matched substring (required for unique/matchWindow). ("files" is unlike localViewStructure\'s `filesOnly`, which filters a directory listing to file entries.)'),pattern:Ht.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Modifiers are part of the node \u2014 `function $NAME` does not match `async function` or `export function`; include the modifiers or use a YAML `kind` rule for modifier-agnostic matches. Use this to find syntax shape, then use lspGetSemantics for semantic proof."),maxDepth:_(0,20).optional().describe("Keep files at most this many directory levels below the search root (0 = files directly in the root). Structural mode pushes this into the native walker; text/regex mode applies it after the native search and emits a warning when it filters deeper matches."),rule:Ht.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),captureText:Ht.boolean().optional().describe("Structural only: return full verbatim capture text for `$$$` list metavars (bodies, arg lists). Default false \u2014 list-capture text is omitted from `metavars`, and `metavarRanges` entries are comment-pruned and truncated to keep results lean; ranges always remain as line anchors."),contextLines:In,matchContentLength:_(1,1e5).optional().default(500),maxMatchesPerFile:_(1,1e5).optional(),maxFiles:_(1,1e5).optional(),matchPage:K.optional(),itemsPerPage:_(1,1e3).optional(),page:K.default(1),unique:Ht.enum(["off","list","count"]).optional().default("off").describe('Needs output:"matchOnly". "list" returns each matched value once per file; "count" adds its frequency.')},cw={...fh,semanticRanking:Ht.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},uw=Z(mh,cw),lw=X(mh,fh,{strict:!0,omit:aw}),ht=lw.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let n=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(n){let r=n[0].slice(2);t.addIssue({code:"custom",message:`\`${n[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),Ro=Y(uw,{maxQueries:5});import{validateRipgrepQuery as Bw}from"@octocodeai/octocode-core/schemas/runtime";var Nc=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],re={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,testPathPenalty:-3.5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Gc=2e3,Hc=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,hh={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+['"]/]},So={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...hh},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...hh},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/]}},Bc=/^\s*#{1,6}\s/,bo=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,pw=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,dw=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,mw=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,fw=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,hw=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,gw=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,yw=new Set(["typescript","javascript","rust","python","go","java","scala"]),rs=/\.([a-z0-9]+)$/i;function Co(e){return rs.exec(e)?.[1]?.toLowerCase()??""}function Rw(e){let t=Co(e);if(!t)return!1;for(let n of yw)if(So[n].extensions.includes(t))return!0;return!1}function Uc(e,t,n){if(n&&n!=="auto")return So[n];let r=Co(e),o=(t??"").toLowerCase();for(let i of Nc){let s=So[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Nc){let s=So[i];if(i!=="generic"&&s.extensions.includes(r))return s}return So.generic}function os(e){return pw.test(e)?"generated":mw.test(e)?"fixture":dw.test(e)?"test":hw.test(e)?"config":fw.test(e)?"docs":!bo.test(e)&&(gw.test(e)||Rw(e))?"source":"unknown"}function Qc(e){if(!e)return!1;if(bo.test(e))return!0;let t=os(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}function $c(e,t,n,r={}){if(t==="matchCount"){let m=[...e].sort(gh);return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="path"){let m=[...e].sort((d,f)=>d.path.localeCompare(f.path));return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Gc,i=e,s=[],a=0;if(e.length>o){let m=[...e].sort(gh);i=m.slice(0,o),s=m.slice(o),a=s.length}let c=Vc(i,n),u=i.map(m=>{try{return{file:m,s:Kc(m,n,c)}}catch{return{file:m,s:Sw()}}});u.sort((m,d)=>{if(d.s.score!==m.s.score)return d.s.score-m.s.score;let f=(d.file.matchCount??0)-(m.file.matchCount??0);return f!==0?f:m.file.path.localeCompare(d.file.path)});let l=[...u.map(m=>m.file),...s],p={files:r.sortReverse?l.reverse():l,cappedCandidates:a};return r.debug&&(p.debug=new Map(u.map(m=>[m.file.path,m.s]))),p}function Sw(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function gh(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function xo(e,t){for(let n of e)if(n.test(t))return!0;return!1}function is(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jc(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function zc(e,t,n){if(e.indexOf(`
66
64
  `)<0)return e;let o=e.split(`
67
- `);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 $c(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=ow(e,t,r);if(o<0)return"code";let i=iw(e);return i>=0&&o>i?"comment":ph(e,o)?"string":"code"}function ow(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function iw(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 ph(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 sw(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function aw(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 cw(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Uc(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=Qc(u,r,n.caseSensitive),p=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${rs(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(p+=re.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(p+=re.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(p+=re.substring,m.push("substring match")));let d=c.kind;if(d)p+=uw(d,m);else{let f=$c(l,r,t.id,n.caseSensitive);f!=="code"?(p+=re.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(Co(t.declaration,l)&&(p+=re.declarationLine,m.push("declaration line")),Co(t.export,l)&&(p+=re.exportLine,m.push("export/public line")),Co(t.import,l)&&(p+=re.importLine,m.push("import line")),t.id==="markdown"&&Nc.test(l)&&(p+=re.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&lw(l,r)&&(p+=re.configKeyLine,m.push("config key match")))}p>s&&(s=p,a=m.join(", "))}return a&&o.push(a),s}function uw(e,t){switch(e){case"declaration":return t.push("AST: declaration"),re.declarationLine;case"export":return t.push("AST: export/public"),re.exportLine;case"configKey":return t.push("AST: config key"),re.configKeyLine;case"heading":return t.push("AST: heading"),re.headingLine;case"import":return t.push("AST: import"),re.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),re.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function lw(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 pw(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(ts,"").includes(u))&&(s+=re.pathSegmentToken,i.push("query token in path"))}let a=bo(e);return r.extensions.includes(a)&&t.langType&&(s+=re.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=re.sourceDir,i.push("source file")),s}function dw(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),re.lowSignalPathPenalty):e==="test"?(n.push("test file (penalized)"),re.testPathPenalty):0}function mw(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*re.matchCountScale,r=Math.min(n,re.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function jc(e,t){let n=aw(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=>fw(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 fw(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${rs(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function hw(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*re.rareQueryTokenScale,re.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 zc(e,t,n){let r=Gc(e.path,t.langType,t.profileOverride),o=ns(e.path),i=sw(t.keyword),s=[],a=0;return a+=cw(e.matches,r,t,i,s),a+=pw(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=re.pathUnderQuery,s.push("under requested subtree")),a+=dw(o,t,s),So.test(e.path)&&!t.explicitLowSignal&&(a+=re.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=mw(e.matchCount??0,s),a+=hw(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var gw=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"]),yw=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function dh(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=Rw(i);s.fetch={tool:"localGetFileContent",query:Wc({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"low":"exact"};let a=Sw(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"low"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"low"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Wc({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Wc({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function Rw(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-8),endLine:n+8}}function Sw(e,t,n){if(t.output==="countLines"||t.output==="countMatches"||t.unique==="list"||t.unique==="count")return;if(n==="structural")return bw(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.output==="matchOnly"){let o=Vc(e?.value);return o?{symbol:o}:void 0}let r=Vc(t.searchText);return r?{symbol:r}:void 0}function bw(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=Vc(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function Vc(e){if(typeof e!="string")return;let t=e.trim();if(yw.test(t)&&!gw.has(t))return t}function Wc(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function os(e,t,n,r,o){let i=t.sort??"relevance",s=n==="structural"&&i==="relevance"?"path":i,a;try{a=Bc(e,s,Cw(t),{debug:!1,sortReverse:t.sortReverse})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,u=a.debug,l=c.length,p=t.output==="files"||t.output==="filesWithout",m=t.output==="countLines"||t.output==="countMatches",d=p||m,f=c.reduce((B,k)=>B+(k.matchCount??0),0),g=d?o?.totalOccurrences??o?.totalStructuralMatches??f:f,R=t,h=Math.min(R.itemsPerPage||Gt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),y=R.page||1,S=Math.max(1,Math.ceil(l/h)),C=(y-1)*h,P=Math.min(C+h,l),T=c.slice(C,P),L=l>0&&C>=l;L&&r.push(`page:${y} is out of range (only ${S} page(s), ${l} total file(s)) \u2014 returned 0 files. Use page:1..${S}.`);let _=R.maxMatchesPerFile||Gt.DEFAULT_MATCHES_PER_PAGE,w=T.map(B=>{let k=B.matches?.length??0,U=Math.max(1,Math.ceil(k/_)),ee=Math.max(1,R.matchPage||1),v=(ee-1)*_,X=k>0&&v>=k,le=Math.min(v+_,k),ae=d?void 0:B.matches?.slice(v,le),pe=ae?.length;X&&r.push(`${B.path}: matchPage:${ee} is out of range under maxMatchesPerFile:${_} (only ${U} page(s), ${k} total match(es) for this file) \u2014 returned 0 rows for this file. Use matchPage:1..${U}, or drop matchPage to re-derive it from the current maxMatchesPerFile.`);let Me=u?.get(B.path);return{path:B.path,...p?{}:t.output==="countLines"?{totalMatchedLines:B.matchCount||1}:t.output==="countMatches"?{totalOccurrences:B.matchCount||1}:{totalMatchRows:k,...pe!==void 0?{returnedMatchRows:pe}:{}},...ae!==void 0&&{matches:ae},...Me?{ranking:{score:Me.score,profile:Me.profile,pathRole:Me.pathRole,reasons:Me.reasons}}:{},pagination:!d&&(k>_||X)?{currentPage:ee,totalPages:U,matchesPerPage:_,totalMatches:k,hasMore:ee<U,...ee<U?{nextMatchPage:ee+1}:{},...X?{outOfRange:!0}:{}}:void 0}}),b=w.filter(B=>B.pagination?.hasMore),A=dh(w,t,n,{isFileListMode:d,currentPage:y,totalFilePages:S,matchPage:R.matchPage||1,matchesPerPage:_,hasFileWithMoreMatches:b.length>0}),M={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:y,totalPages:S,filesPerPage:h,totalFiles:l,...p?{}:{totalMatches:g},hasMore:y<S,...y<S?{nextPage:y+1}:{},...L?{outOfRange:!0}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return mh(M,t,{totalMatches:g,totalFiles:l})}function mh(e,t,n){return e}function Cw(e){let t=e.rankingProfile,n=!!(e.include?.length||Hc(e.path));return{queryPath:e.path,keyword:e.searchText,langType:e.langType,caseSensitive:e.caseMode==="sensitive",wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function fh(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&&xw(r)&&n.push(`pattern '${r}' looks literal \u2014 set regex:"fixed" to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&Pw(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function xw(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function Pw(e){return/\(\?[=!<]/.test(e)}import Vn from"node:path";function Tw(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function Ew(e){return{path:e.path,pattern:e.searchText??"",fixedString:e.regex==="fixed",perlRegex:e.regex==="perl",caseSensitive:e.caseMode==="sensitive",caseInsensitive:e.caseMode==="insensitive",wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline==="on"||e.multiline==="dotall",multilineDotall:e.multiline==="dotall",filesOnly:e.output==="files",filesWithoutMatch:e.output==="filesWithout",countLinesPerFile:e.output==="countLines",countMatchesPerFile:e.output==="countMatches",contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:Tw(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.output==="matchOnly",unique:e.unique==="list"||e.unique==="count",countUnique:e.unique==="count",matchWindow:e.matchWindow,maxCollectedFiles:1e4}}function Lw(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}function Aw(e,t){let n=Vn.isAbsolute(e)?e:Vn.join(t,e),r=Vn.relative(t,n);if(!r||r.startsWith("..")||Vn.isAbsolute(r))return 0;let o=Vn.dirname(r);return o==="."?0:o.split(Vn.sep).filter(Boolean).length}async function hh(e){let t=[],n=ww(e);if(!n.isValid)return F(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:x.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=ht.safeParse(e);if(!r.success){let h=r.error.issues.map(y=>y.message);return F(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:x.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return F(new Error("Path is required for search"),o,{toolName:x.LOCAL_RIPGREP,extra:{warnings:t}});let s=ve(o,x.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=fh({pattern:a.searchText??"",fixedString:a.regex==="fixed",perlRegex:a.regex==="perl"});if(!c.isValid)return F(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:x.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await O.searchRipgrep(Ew(a))}catch(h){return F(h instanceof Error?h:new Error(String(h)),o,{toolName:x.LOCAL_RIPGREP})}let p=l.files.map(h=>({path:h.path,matchCount:h.matchCount,matches:h.matches.map(y=>{let S={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(S.count=y.count),y.kind!==void 0&&(S.kind=y.kind),y.scoreHint!==void 0&&(S.scoreHint=y.scoreHint),S})})),m=a.maxDepth,d=m===void 0?p:p.filter(h=>Aw(h.path,a.path)<=m);m!==void 0&&d.length!==p.length&&u.push(`Applied maxDepth:${m} after native text search; filtered ${p.length-d.length} deeper file(s).`);let f=Lw(d),g={totalOccurrences:l.stats.matchCount,matchedLines:l.stats.matchedLines,filesMatched:d.length,filesSearched:l.stats.filesSearched,bytesSearched:l.stats.bytesSearched??void 0,searchTime:l.stats.searchTime,capped:l.stats.capped??void 0,capReason:l.stats.capReason??void 0};if(l.stats.capped&&u.push(`Search hit native collection cap (${l.stats.capReason??"resource limit"}); narrow path/include/keywords for exhaustive results.`),d.length===0){let h=['No matches \u2014 broaden the search: try caseMode:"insensitive", a shorter/partial term, or regex:"smart" instead of "fixed".',...a.include?.length||a.maxDepth!==void 0?["Filters are active (include/maxDepth) \u2014 drop them to search the wider tree."]:[],...a.wholeWord?["wholeWord:true excludes partial hits \u2014 drop it to match substrings."]:[]];return $({status:"empty",searchEngine:"rg",stats:g,hints:h,warnings:[...t,...u]},f)}a.output!=="files"&&f>Gt.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(f/1024)}KB).`);let R=await os(d,o,"rg",[...t,...u],g);return $(R,f)}import{readFile as Iw,stat as Ow}from"node:fs/promises";var gh={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},yh={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}};function _w(e){return e.trim().replace(/^\./,"").toLowerCase()}function Rh(e){if(!e?.trim())return;let t=_w(e),n=gh[t]??yh[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function Kc(e){let t=Rh(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}var kw=/^\s*(\/\/|\/\*|\*|#)/;function bh(e,t,n){let r=t&&Object.keys(t).length>0;if(n)return{...e?{metavars:e}:{},...r?{metavarRanges:t??void 0}:{}};let o;if(e){o={};for(let[s,a]of Object.entries(e))a.length<=1&&(o[s]=a.map(Sh));Object.keys(o).length===0&&(o=void 0)}let i;if(r&&t){i={};for(let[s,a]of Object.entries(t)){let u=(a.length>1?a.filter(l=>!kw.test(l.text)):a).map(l=>({...l,text:Sh(l.text)}));u.length>0&&(i[s]=u)}Object.keys(i).length===0&&(i=void 0)}return{...o?{metavars:o}:{},...i?{metavarRanges:i}:{}}}function Sh(e){return e.length>120?`${e.slice(0,120)}\u2026`:e}var Ch=[],xh=2e3,Fw=1e6,vw="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`.";function wh(e){if(!e||!/\)\s*\{/.test(e))return;let t=e.replace(/\)\s*\{/,"): $R {");return t===e?void 0:t}function Dw(e){let t=wh(e);return t?` Try: \`${t}\`.`:""}function Ph(e){return e.include?.length?e.include:Kc(e.langType)}async function Mw(e){try{return(await Ow(e)).isFile()}catch{return!1}}async function Nw(e,t,n){let r=await Iw(e,"utf8"),o=await O.structuralSearch(r,e,n??t.pattern,t.rule);return{files:o.length>0?[{path:e,matches:o}]:[],totalMatches:o.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Th(e){let t=ve(e,x.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=await Mw(t.sanitizedPath),r=!!e.captureText,o=S=>({path:t.sanitizedPath,pattern:S??e.pattern,rule:e.rule,...Ph(e)?{include:Ph(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Ch.length?{excludeDir:Ch}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??xh,maxFileBytes:Fw}),i=S=>n?Nw(t.sanitizedPath,e,S):O.structuralSearchFiles(o(S)),s,a=!1,c;try{if(s=await i(),s.totalMatches===0&&e.pattern&&!e.rule&&!/[;}]\s*$/.test(e.pattern))try{let S=await i(`${e.pattern};`);S.totalMatches>0&&(s=S,a=!0)}catch{}if(s.totalMatches===0&&e.pattern&&!e.rule){let S=wh(e.pattern);if(S)try{let C=await i(S);C.totalMatches>0&&(s=C,c=S)}catch{}}}catch(S){let C=S instanceof Error?S.message:String(S),P=e.langType||"source";return F(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${C} \u2014 patterns must be valid ${P} 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:x.LOCAL_RIPGREP})}let u=s.files.map(S=>({path:S.path,matchCount:S.matches.length,matches:S.matches.map(C=>({line:C.startLine,endLine:C.endLine,value:C.text.replace(/\s+/g," ").trim().slice(0,300),column:C.startCol,endColumn:C.endCol,...bh(C.metavars,C.metavarRanges,r)}))})),l=e.maxDepth,p=u,m=0;if(typeof l=="number"&&!n){let S=t.sanitizedPath.replace(/\/+$/,"");p=u.filter(C=>(C.path.startsWith(`${S}/`)?C.path.slice(S.length+1):C.path).split("/").length<=l+1),m=u.length-p.length}let d=p.reduce((S,C)=>S+(C.matchCount??C.matches?.length??0),0),f=e.maxFiles??xh,R=(s.parsedFiles??0)+(s.skippedUnreadable??0)+(s.skippedLarge??0)>=f,h={totalStructuralMatches:typeof l=="number"?d:s.totalMatches,...R?{capReached:!0}:{}},y=[...s.warnings];if(m>0&&y.push(`maxDepth ${l}: dropped ${m} deeper file(s) \u2014 raise maxDepth or omit it to include them.`),a&&y.push(`Matched after appending ';' \u2014 statement patterns must parse as complete statements; the bare pattern parsed as an expression fragment. Results are for "${e.pattern};".`),c&&y.push(`Matched after adding a return-type metavar \u2014 the bare pattern missed functions that declare a return type. Results are for "${c}".`),s.totalMatches===0&&!n)try{let S=O.structuralSearchFilesDetailed(o()),C=S.query;if(C){let P=[`query parsed as ${C.kind}`];C.literalAnchor&&P.push(`literal anchor "${C.literalAnchor}"`),P.push(`pre-filter: ${C.preFilter}`),C.unsafeReason&&P.push(`unsafe: ${C.unsafeReason}`),y.push(`Engine explanation: ${P.join(", ")}.`);for(let T of[...C.diagnostics??[],...S.diagnostics??[]].slice(0,3))y.push(`Engine ${T.severity} [${T.stage}/${T.code}]: ${T.message}${T.recovery?` \u2014 ${T.recovery}`:""}`)}}catch{}return(p.length===0||h.totalStructuralMatches===0)&&e.pattern&&!e.rule&&m===0&&y.push(vw+Dw(e.pattern)),await os(p,e,"structural",y,h)}function Gw(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.output==="content"?n.output="files":t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function is(e){let t=Gw(e);if(t.mode==="structural")return await Th(t);t.contextLines===void 0&&(t.contextLines=2);try{return await hh(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}:F(n,t,{toolName:x.LOCAL_RIPGREP})}}async function Eh(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=_e(ht,n);return r.ok===!1?r.error:await is(r.data)}}),{toolName:x.LOCAL_RIPGREP},e)}import{z as Lh}from"zod";import{ViewStructureQuerySchema as Ah}from"@octocodeai/octocode-core/schemas";var _h={excludeDir:Lh.array(Lh.string()).optional().describe("Directory names to prune from recursive walks (default: common generated/vendor dirs such as node_modules, dist, build, out, coverage, target). Pass [] to inspect everything."),maxDepth:I(0,20).optional(),limit:I(1,1e4).optional(),page:q.default(1),itemsPerPage:I(1,50).optional()},Hw=Z(Ah,_h),cn=Y(Ah,_h),xo=K(Hw,{maxQueries:5});var Bw=new Set(["+","*","?"]),Uw=1e3;function Qw(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function kh(e,t){let n=e[t];return n===void 0?!1:Bw.has(n)||n==="{"&&zw(e,t)}function $w(e,t,n){let r=n.pop()??!1,o=kh(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?Ih(e,t+1):t+1})}function jw(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Ih(e,t)})}function Yc(e){if(e.length>Uw)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=Qw(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=$w(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(kh(e,r)){let i=jw(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function zw(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 Ih(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function i1(e,t){let n=Yc(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}function Oh(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(!Yc(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 n}function Fh(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 vh(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 Dh(e){let t={},n=e.find(o=>o.type==="file"&&o.path);n?.path&&(t.fetch={tool:"localGetFileContent",query:{path:n.path,minify:"standard"},why:'Read the first listed file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"});let r=e.find(o=>o.type==="directory"&&o.path);return r?.path&&(t.viewDeeper={tool:"localViewStructure",query:{path:r.path},why:"Descend into the first listed subdirectory.",confidence:"exact"}),t.fetch||t.viewDeeper?t:void 0}var Ww=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function Vw(e,t){let n=t??Ww,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Mh(e){try{let t=ve(e,x.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.detail==="modified"||e.detail==="full"||e.sortBy==="time";return Kw(e,t.sanitizedPath,n)}catch(t){let n=Le.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function Kw(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=Xw(e),s=Yw(e,i),a=r&&s?1e4:1e4,c=Vw(t,e.excludeDir),u;try{u=O.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:qw(e),excludeDir:c,limit:a})}catch(L){return eT(L,e,t)}let l=u.entries.map(L=>Jw(L,n,e.detail==="full")),p=Oh(l,e),m=e.sortBy??"name";p=p.sort((L,_)=>{let w=0;switch(m){case"size":{let b=L.sizeBytes??(L.size?lo(L.size):0),A=_.sizeBytes??(_.size?lo(_.size):0);w=b-A;break}case"time":n&&L.modified&&_.modified?w=L.modified.localeCompare(_.modified):w=L.name.localeCompare(_.name);break;case"extension":w=(L.extension||"").localeCompare(_.extension||"");break;default:w=L.name.localeCompare(_.name);break}return e.reverse?-w:w}),e.limit&&(p=p.slice(0,e.limit));let d=p.length,{paginatedEntries:f,pagination:g}=Ac(p,e),h=e.detail==="full"||e.detail==="modified"?{path:t,entries:f.map(L=>({...vh(L),path:L.path??`${t.replace(/\/$/,"")}/${L.name}`}))}:{path:t,...Fh(f)},y=[...u.warnings,...po({skipped:u.skipped,permissionDenied:u.permissionDenied}),...u.wasCapped?[`Results capped at ${a} entries during the walk before sorting \u2014 sortBy:"${m}" only orders that partial set, not the true top-N across the whole tree. Add pattern/extensions/entryType/excludeDir or reduce depth to narrow the scope.`]:[],...g.outOfRange?[`page:${e.page} is out of range (only ${g.totalPages} page(s), ${g.totalEntries} total entries) \u2014 returned page ${g.currentPage} instead.`]:[]],S=d===0,C=Lc(p),T={...Dh(f)??{},...g.hasMore?{nextPage:Fn(x.LOCAL_VIEW_STRUCTURE,{...e,page:g.currentPage+1},"Continue to the next page of directory entries.")}:{}};return $({...S?{status:"empty"}:{},...h,summary:C,...g.hasMore||g.totalPages>1||g.outOfRange?{pagination:g}:{},...Object.keys(T).length>0?{next:T}:{},...y.length>0&&{warnings:y}},u.entries.reduce((L,_)=>L+_.path.length,0))}function Yw(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function Xw(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function qw(e){return e.entryType}function Jw(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:zn(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=Zw(e.permissions)),o}function Zw(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 eT(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=Le.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return F(a,t,{toolName:x.LOCAL_VIEW_STRUCTURE})}async function Nh(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=_e(cn,n);return r.ok===!1?r.error:await Mh(r.data)}}),{toolName:x.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import{acquirePooledClientDetailed as QT,isLanguageServerAvailable as $T}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as jT}from"@octocodeai/octocode-engine/lsp/workspaceRoot";var Gh=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];function gt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0},...e.lineDeviation!==void 0&&{lineDeviation:e.lineDeviation}}}function Xc(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 tT=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"]);function nT(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function Hh(e,t){if(t===void 0||t==="progressIdle")return e;let n=nT(e);if(!n||!tT.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}import{readFile as rT,stat as oT}from"node:fs/promises";import{SymbolResolver as iT,SymbolResolutionError as sT}from"@octocodeai/octocode-engine/lsp/resolver";import{toUri as aT}from"@octocodeai/octocode-engine/lsp/uri";import{LSP_ERROR_CODES as ss}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function qc(e,t){let n=e.uri,r=ve({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await oT(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:ss.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:ss.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:aT(o),absolutePath:o,content:await rT(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:ss.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Bh(e,t){let n=await qc(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 iT({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=e.lineHint!==void 0?Math.abs(o.foundAtLine-e.lineHint):void 0,u=a>1&&c!==void 0&&c>0?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.uri,range:cT(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u},...c!==void 0&&c>0?{lineDeviation:c}:{}}}}}catch(o){if(o instanceof sT)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:ss.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 cT(e){return{start:e,end:{line:e.line,character:e.character}}}import To from"node:path";import{readFile as TT}from"node:fs/promises";import{resolveImportAliasDefinitions as ET}from"@octocodeai/octocode-engine/lsp/resolver";var Bt=40,as=40,Jc=10;function Zc(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function eu(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Zc(e.type,t),reason:t}}}function Qe(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Zc(e,n),reason:n}}}function $e(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 Po(e,t,n,r,o){let i=o.length>0,s=o.map(Xc),{pageItems:a,pagination:c}=$e(s,e.page??1,e.itemsPerPage??as);return{type:e.type,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function tu(e,t,n,r){let o=n.map(p=>{let m=p.uri===t.uri&&p.range.start.line===t.resolvedSymbol.position.line&&p.range.start.character===t.resolvedSymbol.position.character;return{...p,...m?{isDefinition:!0}:{}}}),i=e.groupByFile?Uh(o):void 0,s=i??o.map(Xc),{pageItems:a,pagination:c}=$e(s,e.page??1,e.itemsPerPage??as),u=o.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0,l=r?.possiblyTruncated===!0?[`Reference warmup opened ${r.warmedFiles}/${r.candidates} candidate file(s) and may be incomplete because the candidate set hit the warmup cap; narrow workspaceRoot/path or confirm with localSearchCode before unused/safe-delete claims.`]:[];return{type:"references",uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...i?{byFile:a}:{locations:a},totalReferences:o.length,totalFiles:new Set(o.map(p=>p.uri)).size,...o.length>0&&o.every(p=>p.isDefinition)?{definitionOnly:!0}:{},...r?{warmup:r}:{},...u?{empty:u}:{}},pagination:c,...l.length>0?{warnings:l}:{}}}async function nu(e,t,n){let r=Qh(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function Uh(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 Qh(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=>$h(r)).join(`
68
- `).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 $h(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}import{safeReadLineWindow as uT}from"@octocodeai/octocode-engine/lsp/validation";var lT={maxNodes:100,maxRequests:50},jh={truncatedByDepth:!1,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,cycleCount:0,failedRequestCount:0};function zh(e){return{...lT,...e,visitedNodeCount:0,requestCount:0,truncatedByBudget:!1}}function Wh(e){return e.requestCount>=e.maxRequests?(e.truncatedByBudget=!0,!1):(e.requestCount+=1,!0)}function Vh(e){return e.visitedNodeCount>=e.maxNodes?(e.truncatedByBudget=!0,!1):(e.visitedNodeCount+=1,!0)}function it(e,t){return{...e,truncatedByBudget:t.truncatedByBudget,visitedNodeCount:t.visitedNodeCount,requestCount:t.requestCount}}function wo(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Kh(e,t,n){if(t<=0)return e;let r=n?.[0]?.start.line??e.range.start.line,o=await uT(e.uri,r,t);if(!o)return e;let i=_r(o).length,s=Math.max(0,r-t),a=s+Math.max(0,i-1);return{...e,content:o,displayRange:{startLine:s+1,endLine:a+1}}}async function pT(e,t){return Promise.all(e.map(async n=>({...n,from:await Kh(n.from,t,n.fromRanges)})))}async function dT(e,t){return Promise.all(e.map(async n=>({...n,to:await Kh(n.to,t)})))}async function ru(e,t,n,r,o,i=zh(void 0)){if(n<=0||!e)return{calls:[],...jh};if(!Wh(i))return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getIncomingCalls(t),a=o>0?await pT(s,o):s;if(n===1)return it({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=wo(u.from);if(r.has(l)){c.push(it({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!Vh(i)||(r.add(l),c.push(await ru(e,u.from,n-1,r,o,i)),i.truncatedByBudget))break}return it({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}async function ou(e,t,n,r,o,i=zh(void 0)){if(n<=0||!e)return{calls:[],...jh};if(!Wh(i))return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getOutgoingCalls(t),a=o>0?await dT(s,o):s;if(n===1)return it({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=wo(u.to);if(r.has(l)){c.push(it({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!Vh(i)||(r.add(l),c.push(await ou(e,u.to,n-1,r,o,i)),i.truncatedByBudget))break}return it({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}var mT=new Set(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),fT=new Set(["symbolNotFound","anchorFailed"]);function hT(e){if(e.kind==="empty"&&typeof e.category=="string")return{category:e.category,...typeof e.reason=="string"?{reason:e.reason}:{}};let t=e.empty;if(yt(t)&&typeof t.category=="string")return{category:t.category,...typeof t.reason=="string"?{reason:t.reason}:{}}}function gT(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"rs":return"^\\s*pub\\s";case"py":case"pyi":return"^\\s*(def|class)\\s";case"go":return"^(func|type|var|const)\\s";case"java":case"kt":case"scala":case"cs":return"^\\s*(public|protected|internal)\\s";case"rb":return"^\\s*(def|class|module)\\s";default:return"^\\s*export\\s"}}function yT(e,t){let n=e.symbolName;if(typeof n=="string"&&n.trim())return n.trim();let r=t.resolvedSymbol?.name;if(typeof r=="string"&&r.trim())return r.trim()}function iu(e,t){if(!su(t))return t;let n=t.payload,r=n.locations?.[0],o=r?.displayRange?.startLine;if(r?.uri&&typeof o=="number"){let c=r.uri.startsWith("file://")?decodeURIComponent(r.uri.slice(7)):r.uri;return{...t,next:{readSite:{tool:"localGetFileContent",query:{path:c,startLine:Math.max(1,o-3),endLine:(r.displayRange?.endLine??o)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}let i=hT(n);if(i?.category==="unsupportedOperation"&&t.type==="documentSymbols"&&t.uri){let c=t.uri.startsWith("file://")?decodeURIComponent(t.uri.slice(7)):t.uri;return{...t,next:{textSearch:{tool:"localSearchCode",query:{path:c,searchText:gT(c),regex:"perl"},why:"documentSymbols is unsupported for this file's language server \u2014 fall back to a regex search over top-level declarations for an outline.",confidence:"low"}}}}let s=yT(e,t);if(!i||!s||!mT.has(i.category))return t;let a={textSearch:{tool:"localSearchCode",query:{keywords:s},why:`Semantic ${t.type} returned no result (${i.category}) \u2014 fall back to a text search for "${s}"`,confidence:"low"}};return fT.has(i.category)&&t.uri&&(a.reAnchor={tool:"lspGetSemantics",query:{type:"documentSymbols",uri:t.uri},why:"Re-anchor: list this file's symbols to find the correct lineHint, then retry the semantic query",confidence:"medium"}),{...t,next:a}}var RT=8;function Xh(e){return $(e,N(e))}function qh(e,t){return e.format!=="compact"||!su(t)?t:ST(t)}function su(e){return yt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&yt(e.payload)}function ST(e){return{...e,format:"compact",payload:bT(e.payload)}}function bT(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Yh)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(xT)}:{locations:(e.locations??[]).map(Yh)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Jh(e.root)}:{},direction:e.direction,calls:e.calls.map(PT),...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(CT)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function CT(e){if(!yt(e))return String(e);let t=De(e,"line"),n=De(e,"character"),r=De(e,"endLine"),o=Rt(e,"kind"),i=Rt(e,"name"),s=De(e,"childCount"),a=Rt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Yh(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${eg(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function xT(e){if(!yt(e))return String(e);let t=Rt(e,"uri"),n=De(e,"firstLine"),r=De(e,"firstCharacter"),o=De(e,"count"),i=Zh(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 PT(e){if(!yt(e))return String(e);let t=Rt(e,"direction"),n=Jh(e.item),r=Zh(e,"ranges").map(wT).join(","),o=De(e,"rangeCount"),i=De(e,"rangeSampleCount"),s=Rt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${eg(s,180)}`:""].filter(Boolean).join(" ")}function Jh(e){if(!yt(e))return String(e);let t=Rt(e,"name"),n=Rt(e,"kind"),r=Rt(e,"uri"),o=De(e,"line"),i=De(e,"endLine"),s=De(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function wT(e){return yt(e)?`${De(e,"line")}:${De(e,"character")}`:String(e)}function yt(e){return typeof e=="object"&&e!==null}function Rt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function De(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Zh(e,t){let n=e[t];return Array.isArray(n)?n:[]}function eg(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}function tg(e,t){let n=rg(e.fromRanges);return{direction:"incoming",item:cs(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...og(e.from,t)}}function ng(e,t){let n=rg(e.fromRanges);return{direction:"outgoing",item:cs(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...og(e.to,t)}}function cs(e){return{name:e.name,kind:Kn(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 rg(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>=RT))break}return n}function og(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Kn(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}async function au(e,t,n){let o=(await n.prepareCallHierarchy(t.absolutePath,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,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await ru(n,o,i,new Set([wo(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await ou(n,o,i,new Set([wo(o)]),e.contextLines??0):s,u=y=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(y.to.uri),l=c.calls.filter(u).length,p=c.calls.filter(y=>!u(y)),m=[...a.calls.map(y=>({direction:"incoming",...y})),...p.map(y=>({direction:"outgoing",...y}))],d=m.map(y=>y.direction==="incoming"?tg(y,e.contextLines??0):ng(y,e.contextLines??0)),{pageItems:f,pagination:g}=$e(d,e.page??1,e.itemsPerPage??Jc),R=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",h=!a.truncatedByDepth&&!c.truncatedByDepth&&!a.truncatedByBudget&&!c.truncatedByBudget&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:cs(o),direction:R,calls:f,incomingCalls:a.calls.length,outgoingCalls:p.length,completeness:{complete:h,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,truncatedByBudget:a.truncatedByBudget||c.truncatedByBudget,visitedNodeCount:a.visitedNodeCount+c.visitedNodeCount,requestCount:a.requestCount+c.requestCount,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function cu(e,t,n){let o=(await n.prepareTypeHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Qe(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=$e(s,e.page??1,e.itemsPerPage??Bt);return{type:e.type,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}var ag=new Set(["references","callers","callees","callHierarchy","implementation"]),ig=100,LT=512*1024,sg=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];async function cg(e,t,n){let r={candidates:0,warmedFiles:0,skippedLarge:0,possiblyTruncated:!1};if(typeof e.openDocument!="function")return r;try{let o=To.extname(t.absolutePath).slice(1),i=sg.includes(o)?sg:[o],s=await is({path:n,searchText:t.resolvedSymbol.name,regex:"fixed",wholeWord:!0,output:"files",maxFiles:ig,include:i.filter(Boolean).map(c=>`*.${c}`)}),a={candidates:s.files?.length??0,warmedFiles:0,skippedLarge:0,possiblyTruncated:(s.files?.length??0)>=ig||!!s.stats?.capped};for(let c of s.files??[]){let u=typeof c.path=="string"?c.path:void 0;if(!u)continue;let l=To.isAbsolute(u)?u:To.join(n,u);if(To.resolve(l)!==To.resolve(t.absolutePath))try{let p=await TT(l,"utf-8");if(p.length>LT){a.skippedLarge+=1;continue}await e.openDocument(l,p),a.warmedFiles+=1}catch{}}return a}catch{return r}}async function ug(e,t,n,r){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?Po(e,t,"definition","definitionProvider",await ET({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)})):Qe(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?Po(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):Qe(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?Po(e,t,"implementation","implementationProvider",await n.implementation(t.absolutePath,t.resolvedSymbol.position,t.content)):Qe(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?tu(e,t,await n.findReferences(t.absolutePath,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content),r):Qe(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?nu(e,t,await n.hover(t.absolutePath,t.resolvedSymbol.position,t.content)):Qe(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?au(e,t,n):Qe(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?cu(e,t,n):Qe(e.type,t,"typeHierarchyProvider unsupported",!0)}}import lu from"node:path";import{fileURLToPath as AT}from"node:url";import{unavailableHintFor as _T}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as kT}from"@octocodeai/octocode-engine/lsp/config";var uu;function pu(e){return uu||(uu=new Set(O.getSupportedJsTsExtensions().map(t=>`.${t}`))),uu.has(lu.extname(e).toLowerCase())}function Xe(e,t,n){let r=kT(e),o=_T(r,void 0),i=n?.message?` LSP startup detail (${n.kind??"startupFailed"}): ${n.message}.`:"";throw new xe(H.LSP_SERVER_UNAVAILABLE,`No ${r} language server is available for ${e}, so "${t}" cannot be answered semantically.${i} ${o} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}var IT=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];function lg(e,t){let n=e.startsWith("file://")?AT(e):e;return lu.isAbsolute(n)?n:lu.resolve(t,n)}function du(){return[...O.getSupportedJsTsExtensions(),...IT]}function pg(){return du().map(e=>`**/*.${e}`)}var OT=[".git","node_modules","dist","out","coverage","target"];async function dg(e,t){let n=e.symbolName?.trim();if(n)try{return(await O.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:pg(),excludeDir:[...OT],maxSnippetChars:1})).files[0]?.path}catch{return}}async function mu(e,t){if(e.uri)return lg(e.uri,t);let n=await dg(e,t);if(n)return n;try{let o=O.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:du(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function fu(e){return e instanceof Error?e.message:String(e)}function hu(e,t){if(!pu(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}}function FT(e){if(!e||typeof e!="object")return!1;let t=e,n=r=>!!r&&typeof r=="object"&&typeof r.line=="number"&&typeof r.character=="number";return n(t.start)&&n(t.end)}function mg(e,t){if(!pu(e))return null;try{let n=O.extractGraphFacts(t,e);if(!n)return null;let r=JSON.parse(n),i=(Array.isArray(r.declarations)?r.declarations:[]).filter(s=>typeof s.name=="string"&&Zi(s.name)&&typeof s.kind=="string"&&FT(s.range)).map(s=>({name:s.name,kind:s.kind,range:s.range}));return i.length>0?i:null}catch{return null}}import{acquirePooledClient as vT,isLanguageServerAvailable as DT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as MT}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Ru(e){let t=await qc(e,ge);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await MT(t.value.absolutePath),r=await DT(t.value.absolutePath,n),o=r?await vT(n,t.value.absolutePath):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=hu(t.value.uri,t.value.content),u=c?.length?null:mg(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(u?.length)s=u,a="native-graph-facts";else if(i&&o){let h=await o.documentSymbols(t.value.absolutePath,t.value.content);s=Array.isArray(h)?h:[],a="lsp"}else{let h=Bp(t.value.content,t.value.uri);h&&(s=h,a="markdown")}let l=a!==void 0;!l&&!r&&Xe(t.value.uri,"documentSymbols");let p=fg(s),m=gg(s),{pageItems:d,pagination:f}=$e(p,e.page??1,e.itemsPerPage??Bt),g=yg(p,h=>h.kind),R=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:p.length,returnedSymbols:d.length,topLevelSymbols:m,kinds:g},payload:{kind:"documentSymbols",symbols:d,...R?{empty:R}:{}},pagination:f}}function fg(e){let t=[];for(let n of e)Su(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Su(e,t,n){if(!e||typeof e!="object")return;let r=e,o=hg(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Kn(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)&&NT.has(Kn(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Su(s,t,i)}}var NT=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"]);function hg(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 gg(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function yg(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}import Rg from"node:path";import{readFile as GT}from"node:fs/promises";import{acquirePooledClientDetailed as Sg,isLanguageServerAvailable as bg}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as HT}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Cg}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function bu(e){let t=e.symbolName??"",n=Rg.resolve(e.workspaceRoot??(e.uri?await Cg(e.uri):process.cwd())),r=await mu(e,n);await bg(r,n)||Xe(r,"workspaceSymbol");let i=await Sg(n,r);i.ok===!1&&Xe(r,"workspaceSymbol",i);let s=i.client;if(!s.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let a;try{Rg.extname(r)&&await s.openDocument(r),a=await s.workspaceSymbol(t)}catch(p){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${fu(p)}`}}}let c=await UT(s,xg(a)),{pageItems:u,pagination:l}=$e(c,e.page??1,e.itemsPerPage??Bt);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:c.length},payload:c.length>0?{kind:"workspaceSymbol",query:t,symbols:u,totalSymbols:c.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}var BT=10;async function UT(e,t){return t.length===0||t.length>BT?t:Promise.all(t.map(async n=>{try{if(!n.uri)return n;let r=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri,o=await GT(r,"utf8");await e.openDocument(r);let i=await HT({anchorUri:r,symbolName:n.name,locations:await e.gotoDefinition(r,{line:n.line-1,character:n.character},o)});if(!Array.isArray(i)||i.length!==1)return n;let s=i[0],a=(s.range?.start?.line??-1)+1;return!s.uri||a<1||s.uri===n.uri&&a===n.line?n:{...n,uri:s.uri,line:a,endLine:(s.range?.end?.line??s.range?.start?.line??a-1)+1,character:s.range?.start?.character??n.character}}catch{return n}}))}function xg(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,u=(s?.end?.line??s?.start?.line??0)+1,l=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:Kn(o),line:c,character:s?.start?.character??0,endLine:u,childCount:0,...l?{containerName:l}:{},uri:a}]})}async function Cu(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Cg(t):process.cwd());await bg(t,n)||Xe(t,"diagnostic");let o=await Sg(n,t);o.ok===!1&&Xe(t,"diagnostic",o);let i=o.client;if(!i.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let s=await i.getDiagnostics(t),a=Pg(s),c=a.filter(m=>m.severity===1).length,u=a.filter(m=>m.severity===2).length,{pageItems:l,pagination:p}=$e(a,e.page??1,e.itemsPerPage??Bt);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:a.length,errorCount:c,warningCount:u},payload:a.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:a.length,errorCount:c,warningCount:u}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:p}}function Pg(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>wg(r))}return[]}function wg(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}async function xu(e){return te(e.queries||[],async t=>Fe({toolName:ge,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await zT(t);return Xh(iu(t,qh(t,n)))}}),{toolName:ge,minQueryTimeoutMs:3e4},e)}async function zT(e){if(e.type==="documentSymbols")return Ru(e);if(e.type==="workspaceSymbol")return bu(e);if(e.type==="diagnostic")return Cu(e);let t=await Bh(e,ge);if(t.ok===!1){let u=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return eu(e,u)}let n=e.workspaceRoot??await jT(t.value.absolutePath);await $T(t.value.absolutePath,n)||Xe(t.value.uri,e.type);let o=await QT(n,t.value.absolutePath);o.ok===!1&&Xe(t.value.uri,e.type,o);let i=o.client,s=ag.has(e.type)?await cg(i,t.value,n):void 0,a=i.getReadiness?.(),c=await ug(e,t.value,i,s);return Hh(c,a)}import{z as us}from"zod";import{LspGetSemanticsQuerySchema as Tg}from"@octocodeai/octocode-core/schemas";var WT=I(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),VT=I(0,1e5).optional(),KT=["structured","compact"],Eg={type:us.enum(Gh).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:us.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:WT.optional(),orderHint:VT,depth:I(0,20).optional().describe("Traversal depth for call-hierarchy / type-hierarchy queries (0 = direct only)."),includeDeclaration:us.boolean().optional().default(!0),page:q.describe("Result page for paginated reference/symbol lists (advance while pagination.hasMore)."),itemsPerPage:I(1,100).optional().describe("References/symbols returned per page (with page)."),contextLines:I(0,100).optional().describe("Lines of surrounding source shown around each result location."),format:us.enum(KT).optional().default("structured")},YT=Z(Tg,Eg),Yn=Y(Tg,Eg),XT=Yn,Xn=K(YT,{maxQueries:5});import{existsSync as Lg}from"fs";import{delimiter as qT,dirname as JT,join as Ag}from"path";function _g(){return process.platform==="win32"?"npm.cmd":"npm"}function ZT(){let e=JT(process.execPath);return Ag(e,_g())}function eE(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function tE(){let e=(process.env.PATH??"").split(qT).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...eE()])]}function kg(){let e=ZT();if(Lg(e))return{command:process.execPath,argsPrefix:[e]};let t=_g();for(let n of tE()){let r=Ag(n,t);if(Lg(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var nE=["view","search","ping","config","whoami"],rE=[...vn,...wd];async function fz(e=1e4){let t=kg();return Td(t.command,[...t.argsPrefix,"--version"],e)}async function Ut(e,t,n={}){if(!nE.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Oi(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=kg(),c=await Zt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:rE});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var qn="https://registry.npmjs.org",Eo=null;async function Lo(){if(Eo)return Eo;try{let e=await Ut("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 Eo=t,t}}catch{}return Eo=qn,qn}function oE(){Eo=null}async function iE(){try{let e=await Lo(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}var Rz=5;var Jn=new Map,wu=5,Ao=3e4;function _o(e){try{return new URL(e).host||e}catch{return e}}var Pu=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 Ig(e,t=Date.now()){let n=Jn.get(_o(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Ao)throw new Pu(_o(e),Ao-r);n.state="half-open"}}function Tu(e){let t=Jn.get(_o(e));t&&(t.failures=0,t.state="closed")}function Og(e,t=Date.now()){let n=_o(e),r=Jn.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=wu&&(r.state="open",r.openedAt=t)),Jn.set(n,r)}function Sz(){Jn.clear(),wu=5,Ao=3e4}function bz(e){typeof e.failureThreshold=="number"&&(wu=e.failureThreshold),typeof e.cooldownMs=="number"&&(Ao=e.cooldownMs)}function Fg(e,t=Date.now()){let n=Jn.get(_o(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Ao:!1}import{z as E}from"zod";var ls=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()}),sE=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()}),vg=E.looseObject({objects:E.array(sE),total:E.union([E.number(),E.string()]).optional()}),Dg=E.union([E.string(),E.boolean(),E.number(),E.null(),E.record(E.string(),E.unknown())]);var aE=6e4;function Mg(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function cE(e,t,n,r){e&&kt({limit_type:"primary",retry_after_seconds:Mg(r),api_method:t,api_url:n,provider:e})}function uE(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(nr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Jl(r),e.status===429&&cE(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function lE(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=Mg(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=aE,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:u,packageRegistry:l}=t,p=e;if(a){let R=e.includes("?")?"&":"?";p=`${e}${R}version=${encodeURIComponent(Yt)}`}let m={"User-Agent":`Octocode-MCP/${Yt}`,...i},d=globalThis.fetch;if(!d)throw new Error(nr.FETCH_NOT_AVAILABLE.message);Ig(p);let f,g=n+1;for(let R=1;R<=g;R++){if(c?.aborted)throw new Error("Request aborted");try{let h=await d(p,{method:s,headers:m,signal:c});if(!h.ok)throw uE(h,s,p,l,u);if(h.status===204)return Tu(p),null;let y=await h.json();return Tu(p),y}catch(h){let y=h;if(c?.aborted||h instanceof Error&&h.name==="AbortError")throw new Error("Request aborted");if(y&&y.retryable===!1)throw h;if(f=h instanceof Error?h:new Error(String(h)),R===g)break;let S=lE(R,r,o,y);await new Promise(C=>setTimeout(C,S))}}throw Og(p),new Error(nr.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}function Qt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var pE="https://api.npmjs.org/downloads/point/last-week";function ke(e){return e===void 0?0:N(e)}async function ps(e){try{let t=`${pE}/${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:ke(n)}}catch{return{rawResponseChars:0}}}function Ng(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 Gg(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 dE(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function ds(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Qt(e.repository):(e.repository.url&&(r=Qt(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:dE(e),...o?{repositoryDirectory:o}:{},...Ng(e.exports)?{exports:Ng(e.exports)}:{},...Gg(e.bin,e.name)?{bin:Gg(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 mE(e){return typeof e.links?.repository=="string"?Qt(e.links.repository):typeof e.repository=="string"?Qt(e.repository):typeof e.repository?.url=="string"?Qt(e.repository.url):null}function Hg(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:mE(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 Eu(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function Bg(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}var fE=3e3;function Lu(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}async function Au(e){try{let t=await Lo(),n=Eu(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=ke(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:ke(i)}}catch{return{rawResponseChars:0}}}async function fs(e,t,n){let[r,o]=await Promise.all([ps(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Au(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 ms(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function hE(e,t){try{let n=await Ut("view",[e,"--json"],{timeout:fE});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,...ms(c)?{}:{errorDetail:c},rawResponseChars:ke(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=ke(o),s=ls.safeParse(o);return s.success?{pkg:ds(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,...ms(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function gE(e,t){try{let n=await Lo(),r=Eu(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(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=ke(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=ls.safeParse(i);return a.success?{pkg:ds(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,...ms(r)?{}:{errorDetail:r},rawResponseChars:0}}}function yE(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function _u(e,t){let n=0,r;for(let o of yE(e)){let i;try{i=await st(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);ms(u)||(r=u);continue}if(n+=ke(i),!i||typeof i!="object")continue;let s=ls.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:ds(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function hs(e,t=!1){let[n,r]=await Promise.allSettled([hE(e,t),gE(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?fs(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function Ug(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await hs(e,t);if(!r){if(o){let s=Lu(o);if(s&&n){let a=await _u(e,t);if(a.pkg){let c=await fs(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 RE(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ut("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:ke(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=ke(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let l=[...a].sort((f,g)=>{let R=f?.score?.final??0;return(g?.score?.final??0)-R}).slice(r,r+t),p=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 R=await hs(g.name,!0);if(R.pkg)return R}return{pkg:Hg(g),rawResponseChars:0}})),m=p.map(f=>f?.pkg).filter(f=>!!f),d=p.reduce((f,g)=>f+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+d}}async function SE(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${qn}/-/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:`Could not reach the npm search API (${f instanceof Error?f.message:String(f)}). The package may not exist, or the registry search endpoint is unavailable.`,hints:['Verify the exact package name / scope (e.g. "@scope/name")',"For an exact known name, query it directly instead of a keyword search","Ensure the npm registry is accessible from this environment"]}}let a=ke(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=vg.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 R=f.score?.final??0;return(g.score?.final??0)-R}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),p=await Promise.all(l.map(async f=>{if(n){let g=await hs(f.name,!0);if(g.pkg)return g}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?Qt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=p.map(f=>f.pkg).filter(f=>!!f),d=p.reduce((f,g)=>f+g.rawResponseChars,0);return{packages:m,totalFound:Bg(c.data.total,m.length),rawResponseChars:a+d}}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 ku(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:ke(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:ke(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?Qt(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:ke(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Iu(e,t,n,r=0){try{let o=await RE(e,t,n,r);if(!("error"in o))return o}catch{}return SE(e,t,n,r)}async function Ou(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}):ps(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Au(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}function un(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Qg(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function Fu(e,t,n,r=0){let o=ce("npm-search",{name:e,limit:t,metadata:n,from:r});return he(o,async()=>{if(Fg(qn)){if(r===0&&t===1&&un(e)){let l=await _u(e,n);if(l.pkg){let p=await fs(e,l.pkg,l.rawResponseChars);return{packages:p.pkg?[p.pkg]:[],totalFound:p.pkg?1:0,rawResponseChars:p.rawResponseChars}}}let u=await ku(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&&un(e)){let u=await Ug(e,n,t===1);if("error"in u){if(!Lu(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await Iu(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Ou(s);let a=Qg(e);if(a!==e){let u=await Iu(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return Ou(u)}let c=await ku(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 $g(e){try{let t=await Ut("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=Dg.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 jg(e){let t=un(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Fu(e.name,n,!0,r)}function vu(e){if(e===void 0)return;let n=(Array.isArray(e)?e.join(" "):e).trim();return n.length>0?n:void 0}var bE=/\b(?:404|e404)\b|not\s+found|no\s+such\s+package|does\s+not\s+exist/i;function Du(e){return bE.test(e)}function CE(e){return"error"in e}function gs(e){return"npmUrl"in e}function xE(e){return gs(e)&&e.path?e.path:e.name}function PE(e){return gs(e)?e.repoUrl:e.repository}function wE(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}var TE={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function EE(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=s=>s.replace(/\.git$/,""),r=t.match(/^(github|gitlab|bitbucket):(.+)$/i);if(r&&r[1]&&r[2]){let s=TE[r[1].toLowerCase()];return n(`https://${s}/${r[2]}`)}let o=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(o&&o[1]&&o[2])return n(`https://${o[1]}/${o[2]}`);let i=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(i&&i[1]){let s=i[1].replace(/^[^@/]+@/,"");return n(`https://${s}`)}return n(t)}function Mu(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 zg(e,t){let n=Mu(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghListReleases",query:{owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags (requires ENABLE_RELEASES)"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function LE(e){let t=xE(e),n=EE(PE(e)),r={name:t};gs(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=wE(gs(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=zg(n,o);return i&&(r.next=i),r.version&&Mu(n)&&(r.warnings=[`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`]),r}function AE(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=Mu(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:zg(i.repository,i.repositoryDirectory)});let{repository:u,repositoryDirectory:l,next:p,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function _E(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,u=s&&o>=a?o+1:a;return{currentPage:o,totalPages:u,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function Wg(e){return te(e.queries,async t=>{try{let n=t.packageName??vu(t.keywords);if(!n)return F("Provide a packageName or keywords for package search",t);let r=await jg({name:n,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(CE(r)){if(Du(r.error)){let p=un(n);return se(t,{packages:[],hints:[p?`No package published under the exact name "${n}". Check the spelling, and try the scoped (@scope/name) vs unscoped form.`:`No packages matched "${n}". Try different or fewer keywords, or search by an exact package name.`]},!1,x.PACKAGE_SEARCH,{rawResponse:r})}return F(r.error,t,{rawResponse:r})}let o=r.packages,i=o.map(LE),s=i.length>0,a=o.length>1||r.totalFound>1,c=_E(t,r.totalFound,i.length,a),l={...AE(i),pagination:c};return se(t,l,s,x.PACKAGE_SEARCH,{rawResponse:r.rawResponseChars??r})}catch(n){return F(n,t,{toolName:x.PACKAGE_SEARCH})}},{toolName:x.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{z as ys}from"zod";import{NpmPackageQuerySchema as Vg}from"@octocodeai/octocode-core/schemas";var Kg={page:q,keywords:ys.union([ys.string(),ys.array(ys.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},ko=Y(Vg,Kg),Io=K(Z(Vg,Kg,{strict:!0}),{maxQueries:5});var Rs={hasTool(e){return Sa(e)},getDescription(e){return Ra[e]??""},getToolName(e){return x[e]??String(e)}};var Nu=(e,t=Rs)=>t.getDescription(e);function kE(e,t){return t.getToolName(e)}function Pe(e,t,n){let r=kE(t,e);return{...n,name:r,description:Nu(r,e)}}var at={security:"remote",requiresServerRuntime:!0,requiresProviders:!0};function IE(e=Rs){let t=Pe(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Wr,inputSchema:Vr,executionFn:ym,...at}}),n=Pe(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:en,inputSchema:jr,executionFn:lm,...at}}),r=Pe(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:so,inputSchema:ao,executionFn:yf,...at}}),o=Pe(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:oo,inputSchema:io,executionFn:mf,...at}}),i=Pe(e,"GITHUB_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Jr,inputSchema:Zr,executionFn:Ym,...at}}),s=Pe(e,"GITHUB_ISSUES",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:eo,inputSchema:to,executionFn:Xm,...at}}),a=Pe(e,"GITHUB_COMMITS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:no,inputSchema:ro,executionFn:qm,...at}}),c=Pe(e,"GITHUB_RELEASES",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:Un,inputSchema:Qn,executionFn:Jm,...at}}),u=Pe(e,"GITHUB_DISCUSSIONS",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:$n,inputSchema:jn,executionFn:nf,...at}}),l=Pe(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ko,inputSchema:Io,executionFn:Wg,security:"remote",requiresServerRuntime:!0}}),p=Pe(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Nn,inputSchema:$r,executionFn:zd,...at}}),m=Pe(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:ht,inputSchema:yo,executionFn:Eh,security:"basic"}}),d=Pe(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:cn,inputSchema:xo,executionFn:Nh,security:"basic"}}),f=Pe(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:on,inputSchema:uo,executionFn:Wf,security:"basic"}}),g=Pe(e,"LOCAL_FIND_DEAD_CODE",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:sn,inputSchema:mo,executionFn:sh,security:"basic"}}),R=Pe(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:rn,inputSchema:co,executionFn:Bf,security:"basic"}}),h={name:ge,description:Nu(ge,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Yn,inputSchema:Xn,executionFn:xu,security:"basic",requiresServerRuntime:!0}},y=[t,n,r,o,i,s,a,...fo()?[c]:[],...Wn()?[u]:[],l,p,m,d,f,g,R,h];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_PULL_REQUESTS:i,GITHUB_ISSUES:s,GITHUB_COMMITS:a,GITHUB_RELEASES:c,GITHUB_DISCUSSIONS:u,PACKAGE_SEARCH:l,GITHUB_CLONE_REPO:p,LOCAL_RIPGREP:m,LOCAL_VIEW_STRUCTURE:d,LOCAL_FIND_FILES:f,LOCAL_FIND_DEAD_CODE:g,LOCAL_FETCH_CONTENT:R,LSP_GET_SEMANTIC_CONTENT:h,ALL_TOOLS:y}}var Ce=IE(),iV=Ce.GITHUB_SEARCH_CODE,sV=Ce.GITHUB_FETCH_CONTENT,aV=Ce.GITHUB_VIEW_REPO_STRUCTURE,cV=Ce.GITHUB_SEARCH_REPOSITORIES,uV=Ce.GITHUB_PULL_REQUESTS,lV=Ce.GITHUB_ISSUES,pV=Ce.GITHUB_COMMITS,dV=Ce.GITHUB_RELEASES,mV=Ce.GITHUB_DISCUSSIONS,fV=Ce.PACKAGE_SEARCH,hV=Ce.GITHUB_CLONE_REPO,gV=Ce.LOCAL_RIPGREP,yV=Ce.LOCAL_VIEW_STRUCTURE,RV=Ce.LOCAL_FIND_FILES,SV=Ce.LOCAL_FIND_DEAD_CODE,bV=Ce.LOCAL_FETCH_CONTENT,CV=Ce.LSP_GET_SEMANTIC_CONTENT,Yg=Ce.ALL_TOOLS;import{completeMetadata as OE}from"@octocodeai/octocode-core";var Oo=null;function Xg(){return Oo||(Oo=OE),Oo}async function wV(){return Xg()}async function TV(){Xg()}function EV(){return Oo}function LV(){Oo=null}var qg=["GitHub","Local Code","Package","Other"],Jg=new Map([D.GITHUB_SEARCH_CODE,D.GITHUB_SEARCH_REPOSITORIES,D.GITHUB_PULL_REQUESTS,D.GITHUB_ISSUES,D.GITHUB_COMMITS,D.GITHUB_FETCH_CONTENT,D.GITHUB_VIEW_REPO_STRUCTURE,D.GITHUB_CLONE_REPO,D.LOCAL_RIPGREP,D.LOCAL_FIND_FILES,D.LOCAL_FIND_DEAD_CODE,D.LOCAL_FETCH_CONTENT,D.LOCAL_VIEW_STRUCTURE,ge,D.PACKAGE_SEARCH,...Wn()?[D.GITHUB_DISCUSSIONS]:[]].map((e,t)=>[e,t])),qe=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},FE=["id","mainResearchGoal","researchGoal","reasoning"],Fo=new Set([...FE]),vE=[{name:D.GITHUB_SEARCH_CODE,schema:Wr,inputSchema:Vr},{name:D.GITHUB_FETCH_CONTENT,schema:en,inputSchema:jr},{name:D.GITHUB_VIEW_REPO_STRUCTURE,schema:so,inputSchema:ao},{name:D.GITHUB_SEARCH_REPOSITORIES,schema:oo,inputSchema:io},{name:D.GITHUB_PULL_REQUESTS,schema:Jr,inputSchema:Zr},{name:D.GITHUB_ISSUES,schema:eo,inputSchema:to},{name:D.GITHUB_COMMITS,schema:no,inputSchema:ro},...fo()?[{name:D.GITHUB_RELEASES,schema:Un,inputSchema:Qn}]:[],...Wn()?[{name:D.GITHUB_DISCUSSIONS,schema:$n,inputSchema:jn}]:[],{name:D.PACKAGE_SEARCH,schema:ko,inputSchema:Io},{name:D.GITHUB_CLONE_REPO,schema:Nn,inputSchema:$r},{name:D.LOCAL_RIPGREP,schema:ht,inputSchema:yo},{name:D.LOCAL_VIEW_STRUCTURE,schema:cn,inputSchema:xo},{name:D.LOCAL_FIND_FILES,schema:on,inputSchema:uo},{name:D.LOCAL_FIND_DEAD_CODE,schema:sn,inputSchema:mo},{name:D.LOCAL_FETCH_CONTENT,schema:rn,inputSchema:co},{name:ge,schema:Yn,inputSchema:Xn}],DE=[...fo()?[]:[{name:D.GITHUB_RELEASES,schema:Un,inputSchema:Qn,disabled:{envVar:"ENABLE_RELEASES"}}],...Wn()?[]:[{name:D.GITHUB_DISCUSSIONS,schema:$n,inputSchema:jn,disabled:{envVar:"ENABLE_DISCUSSIONS"}}]];function $t(e){return vE.find(t=>t.name===e)??DE.find(t=>t.name===e)}function Zn(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===D.PACKAGE_SEARCH?"Package":"Other"}function OV(e){return[...e].sort((t,n)=>{let r=qg.indexOf(Zn(t)),o=qg.indexOf(Zn(n));if(r!==o)return r-o;let i=Jg.get(t)??Number.MAX_SAFE_INTEGER,s=Jg.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}import{z as Zg}from"zod";var ME=["id","researchGoal","reasoning"],ey=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function MV(e){let t=$t(e);if(!t)return"{}";try{return JSON.stringify(Zg.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Zg.toJSONSchema(t.schema,{io:"input"}),null,2)}}function NV(e){return JSON.stringify(e??{},null,2)}function GV(e){let t=Zn(e),n=[...ME];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function HV(){return ey.map(e=>({...e}))}function BV(){return JSON.stringify(Object.fromEntries(ey.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function UV(e,t){return t?.tools?.[e]?.description??e}import{z as NE}from"zod";function Ss(e){let t=$t(e);if(!t)return[];let n=NE.toJSONSchema(t.schema,{io:"input"});if(!er(n))return[];let r=St(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Fo.has(i)&&!Bu(r[i])):[]);return Hu(r,o)}function GE(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 Gu(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=er(e.items)?e.items:void 0;return`array<${n?Gu(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(er).map(Gu).filter(r=>r!=="value");if(n.length>0)return[...new Set(n)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Hu(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Fo.has(o))continue;let s=er(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Gu(s),constraints:GE(s),description:typeof s.description=="string"?s.description:void 0}),St(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!Bu(s.properties?.[l]):!1):[]);r.push(...Hu(s.properties,u,a))}let c=s.type==="array"&&er(s.items)?s.items:void 0;if(c&&St(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!Bu(c.properties?.[l]):!1):[]);r.push(...Hu(c.properties,u,a))}}return r}function ny(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[ty(e,n)]}return ty(e,t)}function ty(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return e}}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e){return St(e)}function Bu(e){return er(e)&&"default"in e}function ry(e){return e===D.GITHUB_PULL_REQUESTS?[{label:"PR search (list)",query:{owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"PR detail (diffs + reviews)",query:{owner:"sindresorhus",repo:"slugify",prNumber:1,content:{comments:{discussion:!0},reviews:!0,patches:{mode:"all"}}}}]:e===D.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===D.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===D.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===D.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===D.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===D.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===D.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===D.LOCAL_FIND_DEAD_CODE?[{label:"default entrypoints (package.json + tests)",query:{path:"packages/octocode-tools-core",itemsPerPage:20}},{label:"explicit entrypoints",query:{path:"packages/octocode-tools-core",entrypoints:["src/index.ts","src/direct.ts"],includeTests:!1}}]:e===D.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,entryType:"f",itemsPerPage:100}}]:e===D.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===D.GITHUB_COMMITS?[{label:"file history (bounded window)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",since:"6m",itemsPerPage:10}},{label:"compare two refs (base...head)",query:{owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===D.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{packageName:"schema validation",page:1}}]:e===ge?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function oy(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function HE(e){let t=ry(e);if(t.length>0)return t.map(r=>({...r,command:oy(e,r.query)}));let n=BE(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:oy(e,n)}]}function JV(e){return HE(e)[0]?.query??{}}function BE(e){if(!$t(e))return{};let t=Ss(e),n=t.filter(i=>!i.name.includes(".")),r=UE(n),o={};for(let i of r)o[i.name]=ny(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}var iy=4,Uu=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),sy=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function UE(e){let t=e.filter(i=>i.required),n=new Map;for(let i of t)n.set(i.name,i);let r=e.filter(i=>!i.required&&QE(i)).sort($E),o=Math.max(iy,t.length);for(let i of r){if(n.size>=o)break;n.set(i.name,i)}return n.size>0?[...n.values()]:e.filter(i=>!sy.has(i.name)).filter(i=>i.type!=="boolean").slice(0,iy)}function QE(e){return sy.has(e.name)||e.type==="boolean"?!1:jE(e)?Uu.has(e.name):!0}function $E(e,t){let n=Uu.get(e.name)??Number.MAX_SAFE_INTEGER,r=Uu.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function jE(e){return e.constraints?.includes("default ")===!0}function n2(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 zE(e,r,n)}function zE(e,t,n={}){let r=VE(e,t,n),o=$t(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.",WE(i.error));return i.data}function WE(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function VE(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(St(t)&&Array.isArray(t.queries))r=t.queries;else if(St(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=St(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>KE(e,a,tL(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function KE(e,t,n,r){let o={...n},i=Zn(e),s=r.sourceLabel??"direct tool execution",a=YE(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 YE(e,t){return`Execute ${e} via ${t}`}function XE(e,t){let n=e.length+1,r=t.length+1,o=Array.from({length:n*r},()=>0);for(let i=0;i<n;i++)o[i*r]=i;for(let i=0;i<r;i++)o[i]=i;for(let i=1;i<n;i++)for(let s=1;s<r;s++){let a=e[i-1]===t[s-1]?0:1;o[i*r+s]=Math.min(o[(i-1)*r+s]+1,o[i*r+s-1]+1,o[(i-1)*r+s-1]+a)}return o[n*r-1]}function qE(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),u=XE(n,c);if(c.includes(n)||n.includes(c)){u<o&&(r=a,o=u);continue}if(n.length<3)continue;let l=Math.max(2,Math.floor(a.length/3));u<=l&&u<s&&(i=a,s=u)}return r??i}var JE=new Set(["none","standard","symbols"]),ZE={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"searchText",keywords:"searchText",language:"langType"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:{field:"minify",map:e=>{if(e===!0)return"standard";if(e===!1)return"none";if(typeof e=="string"&&JE.has(e))return e}}},ghSearchPullRequests:{merged:{field:"state",map:e=>e===!0?"merged":void 0}},ghSearchCommits:{filePath:"path"},localFindFiles:{maxResults:"limit"}};function eL(e,t){let n=ZE[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n)){if(!(o in t))continue;let s=typeof i=="string"?i:i.field;if(s in t){r??={...t},delete r[o];continue}let a=typeof i=="string"?t[o]:i.map(t[o]);a!==void 0&&(r??={...t},r[s]=a,delete r[o])}return r??t}function tL(e,t,n,r={}){if(!St(t))throw new qe("Tool input must be a JSON object or an array of objects.");let o=eL(e,t),i=new Set([...Ss(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Fo]),s={},a=[];for(let[c,u]of Object.entries(o)){if(i.has(c)){s[c]=u;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(u=>{let l=qE(u,i);return l?`'${u}' \u2192 did you mean '${l}'?`:""}).filter(Boolean);throw new qe(`Unknown field(s): ${a.join(", ")}`,[...c,`Remove unknown field(s) from query ${n+1}: ${a.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return s}import{getConfigSync as mL}from"@octocodeai/config";import{ContentSanitizer as nL}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as rL}from"@octocodeai/config";var cy="OCTOCODE_MCP_FULL_TEXT",oL="[content withheld: sanitization failed \u2014 retry the call; if this persists, report it]";function Qu(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:Ve(t.structuredContent)}}catch{t={...t,structuredContent:{status:"error",code:"SANITIZATION_FAILED",error:"structuredContent withheld: sanitization failed \u2014 retry the call; if this persists, report it"},isError:!0}}return iL(t)?sL(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=nL.sanitizeContent(n.text);return{...n,text:r}}catch{return{...n,text:oL}}return n})}),t)}function iL(e){return rL()==="mcp"&&process.env[cy]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function sL(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:aL(e.structuredContent)},...t]}}var ay=3;function aL(e){let t=["structuredContent available"];if(vo(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=uL(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;if(vo(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`),Array.isArray(e.results)&&e.results.length>0){let r=e.results.slice(0,ay).map(cL).filter(Boolean);if(r.length>0){let o=e.results.length-ay;t.push(`[${r.join(" \xB7 ")}${o>0?` \xB7 +${o} more`:""}]`)}}}return`${t.join(" \xB7 ")}. Read structuredContent for full data; if your client cannot read structuredContent, set ${cy}=true.`}function cL(e){if(!vo(e))return"";let t=[];typeof e.id=="string"&&t.push(e.id),t.push(typeof e.status=="string"?e.status:"ok");let n=e.data;return vo(n)&&typeof n.path=="string"&&n.path&&t.push(n.path.split("/").slice(-2).join("/").slice(0,80)),t.join(" ")}function uL(e){let t=0,n=0;for(let r of e)vo(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function vo(e){return typeof e=="object"&&e!==null}var lL="TOOL_CALLBACK_EXCEPTION";function $u(e,t){let n=pL(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
69
- message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:lL,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Qu(r)}catch{return r}}function pL(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:dL(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 dL(e){try{return JSON.stringify(e)}catch{return}}var bs=null,Cs=null,fL=Xl;function hL(e){let t=e;return n=>t(n)}function gL(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:hL(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var yL=Yg.map(gL);function RL(e){return yL.find(t=>t.name===e)}async function SL(e,t){let n=RL(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=bL(n,t);return await CL(n),xL(n),await PL(n,r)}catch(r){return $u(n.name,r)}}function bL(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function CL(e){e.requiresServerRuntime&&(bs||(bs=fL().catch(t=>{throw bs=null,t})),await bs),e.requiresProviders&&(Cs||(Cs=xd().then(()=>{}).catch(t=>{throw Cs=null,t})),await Cs)}function xL(e){if(!e.isLocal&&!e.isClone)return;let t=mL();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function PL(e,t){try{let n=e.security==="remote"?await wL(e,t):await TL(e,t);return Qu(n)}catch(n){return $u(e.name,n)}}async function wL(e,t){return ju(e.name,async(r,o)=>e.execute({...r,authInfo:o.authInfo,sessionId:o.sessionId,signal:o.signal}))(t,{})}async function TL(e,t){return zu(e.execute,e.name)(t)}var T2={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};import{getConfigSync as uy}from"@octocodeai/config";function A2(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function _2(){try{return uy().local.enabled}catch{return!1}}function k2(){try{if(!uy().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}import{validateCommand as EL}from"@octocodeai/octocode-engine/commandValidator";async function v2(e,t=[],n={}){let r=EL(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Oi(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 Zt(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}}import{z as G}from"zod";var xs=G.object({text:G.string()}),LL=G.object({match:G.object({text:G.string()}).optional(),start:G.number(),end:G.number()}),AL=G.object({type:G.literal("match"),data:G.object({path:xs,lines:G.object({text:G.string()}),line_number:G.number(),absolute_offset:G.number(),submatches:G.array(LL)})}),_L=G.object({type:G.literal("context"),data:G.object({path:xs,lines:G.object({text:G.string()}),line_number:G.number(),absolute_offset:G.number()})}),kL=G.object({type:G.literal("begin"),data:G.object({path:xs})}),IL=G.object({type:G.literal("end"),data:G.object({path:xs,stats:G.object({elapsed:G.object({human:G.string()}),searches:G.number(),searches_with_match:G.number()}).optional()})}),OL=G.object({type:G.literal("summary"),data:G.object({elapsed_total:G.object({human:G.string()}),stats:G.object({elapsed:G.object({human:G.string()}),searches:G.number(),searches_with_match:G.number(),bytes_searched:G.number(),bytes_printed:G.number(),matched_lines:G.number(),matches:G.number()})})}),N2=G.discriminatedUnion("type",[AL,_L,kL,IL,OL]);import{securityRegistry as FY,ContentSanitizer as vY}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as MY}from"@octocodeai/octocode-engine/mask";import{configureSecurity as GY}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as WY}from"@octocodeai/octocode-core";import{z as KY}from"zod";export{GL as ALL_ERROR_CODES,Yg as ALL_TOOLS,TS as BASE_SCHEMA,$r as BulkCloneRepoLocalSchema,Xn as BulkLspGetSemanticsQuerySchema,Ps as CONFIG_ERRORS,Hr as CORE_ALLOWED_ENV_VARS,lt as CREDENTIALS_FILE,Pu as CircuitOpenError,Nn as CloneRepoQueryLocalSchema,vY as ContentSanitizer,xB as DEFAULTS,Rz as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,Yu as DEFAULT_MATCH_SNIPPET_CHARS,Rs as DEFAULT_TOOL_METADATA_GATEWAY,Ra as DESCRIPTIONS,KS as DIFF_PREVIEW_MAX_LINES,Fo as DIRECT_TOOL_AUTO_FILLED_FIELDS,qg as DIRECT_TOOL_CATEGORIES,vE as DIRECT_TOOL_DEFINITIONS,qe as DirectToolInputError,z as ERROR_CODES,ye as ERROR_MESSAGES,nr as FETCH_ERRORS,Ct as FILE_OPERATION_ERRORS,jr as FileContentBulkQueryLocalSchema,ZC as FileContentQueryBaseLocalSchema,en as FileContentQueryLocalSchema,hV as GITHUB_CLONE_REPO,pV as GITHUB_COMMITS,mV as GITHUB_DISCUSSIONS,sV as GITHUB_FETCH_CONTENT,Ku as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,lV as GITHUB_ISSUES,uV as GITHUB_PULL_REQUESTS,dV as GITHUB_RELEASES,iV as GITHUB_SEARCH_CODE,me as GITHUB_SEARCH_DEFAULT_LIMIT,oe as GITHUB_SEARCH_MAX_LIMIT,DL as GITHUB_SEARCH_MAX_PAGES,cV as GITHUB_SEARCH_REPOSITORIES,Mt as GITHUB_STRUCTURE_DEFAULTS,ML as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Wu as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,aV as GITHUB_VIEW_REPO_STRUCTURE,$0 as GenericToolResultRowSchema,Vr as GitHubCodeSearchBulkQueryLocalSchema,Wr as GitHubCodeSearchQueryLocalSchema,Ei as GitHubProvider,jx as GitHubPullRequestSearchBulkQueryLocalSchema,gc as GitHubPullRequestSearchQueryLocalSchema,io as GitHubReposSearchBulkQueryLocalSchema,oo as GitHubReposSearchSingleQueryLocalSchema,ao as GitHubViewRepoStructureBulkQueryLocalSchema,so as GitHubViewRepoStructureQueryLocalSchema,mn as HOME,Mk as IGNORED_FILE_EXTENSIONS,Nk as IGNORED_FILE_NAMES,Gk as IGNORED_FOLDER_NAMES,et as KEY_FILE,Do as LOCAL_DEFAULT_FILES_PER_PAGE,bV as LOCAL_FETCH_CONTENT,SV as LOCAL_FIND_DEAD_CODE,RV as LOCAL_FIND_FILES,bt as LOCAL_MAX_DEPTH,ln as LOCAL_MAX_FILES_PER_PAGE,Je as LOCAL_MAX_LIMIT,gV as LOCAL_RIPGREP,H as LOCAL_TOOL_ERROR_CODES,Xu as LOCAL_TOOL_ERROR_REGISTRY,yV as LOCAL_VIEW_STRUCTURE,ge as LSP_GET_SEMANTICS_TOOL_NAME,CV as LSP_GET_SEMANTIC_CONTENT,Qn as ListReleasesBulkLocalSchema,Un as ListReleasesLocalSchema,co as LocalFetchContentBulkQuerySchema,rn as LocalFetchContentQuerySchema,mo as LocalFindDeadCodeBulkQuerySchema,sn as LocalFindDeadCodeQuerySchema,uo as LocalFindFilesBulkQuerySchema,on as LocalFindFilesQuerySchema,yo as LocalRipgrepBulkQuerySchema,ht as LocalRipgrepQuerySchema,hy as LocalToolErrorCategory,xo as LocalViewStructureBulkQuerySchema,cn as LocalViewStructureQuerySchema,Yn as LspGetSemanticsQueryDisplaySchema,XT as LspGetSemanticsQuerySchema,yR as MAX_BRANCH_CACHE_SIZE,pn as MAX_CHAR_LENGTH,Vu as MAX_CONTEXT_LINES,$p as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,xr as MAX_DIRECTORY_FILES,No as MAX_MATCH_CONTENT_LENGTH,Mo as MAX_PAGE_NUMBER,ai as MAX_TOTAL_SIZE,Ks as NETWORK_ERROR_PATTERNS,Dg as NpmDeprecationOutputSchema,vg as NpmRegistrySearchSchema,Io as NpmSearchBulkQueryLocalSchema,ko as NpmSearchQueryLocalSchema,ls as NpmViewResultSchema,Es as OCTOCODE_DIR,Ie as OCTOCODE_HOME,Kl as OctocodeConfigSchema,pR as OctokitWithThrottling,fV as PACKAGE_SEARCH,rr as PROMISE_ERRORS,hd as PROVIDER_CAPABILITIES,wd as PROXY_ENV_VARS,Ne as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,ct as PR_CONTENT_MAX_ITEMS_PER_PAGE,sc as ProviderInitializationError,oi as RATE_LIMIT_CONFIG,Ys as RATE_LIMIT_PATTERNS,xt as REPOSITORY_ERRORS,Gt as RESOURCE_LIMITS,N2 as RipgrepJsonMessageSchema,Ee as SEARCH_ERRORS,Gh as SEMANTIC_CONTENT_TYPES,tD as SENSITIVE_ENV_VARS,Vt as SESSION_FILE,my as STARTUP_ERRORS,D as STATIC_TOOL_NAMES,Kt as STATS_FILE,ap as STATUS_TO_ERROR_CODE,ro as SearchCommitsBulkLocalSchema,no as SearchCommitsLocalSchema,jn as SearchDiscussionsBulkLocalSchema,$n as SearchDiscussionsLocalSchema,to as SearchIssuesBulkLocalSchema,eo as SearchIssuesLocalSchema,Zr as SearchPullRequestsBulkLocalSchema,Jr as SearchPullRequestsLocalSchema,T2 as StatusEmojis,vn as TOOLING_ALLOWED_ENV_VARS,fy as TOOL_ERRORS,dy as TOOL_METADATA_ERRORS,x as TOOL_NAMES,xe as ToolError,Le as ToolErrors,tr as VALIDATION_ERRORS,Qg as _packageNameToSearchKeywords,LV as _resetMetadataState,oE as _resetNpmRegistryUrlCache,Vl as _resetSessionState,k_ as _resetTokenResolvers,__ as _setTokenResolvers,eP as applyConfiguredAllowedRoots,La as applyContentPagination,Oh as applyEntryFilters,cc as applyExactMatchRanking,hi as applyPagination,vr as applyPartialContentFilter,ad as applyStructurePagination,Ig as assertCircuitAvailable,$ as attachRawResponseChars,CO as buildBlockBoundaryHint,Ii as buildChildProcessEnv,ea as buildCodeSearchQuery,QO as buildDiffPreview,HE as buildDirectToolCommandPatterns,JV as buildDirectToolExampleQuery,RP as buildEntryPaginationHints,ny as buildExampleValue,uc as buildGhSearchCodeFinalizer,Fb as buildGitHubPullRequestsSearchParams,um as buildGithubFetchContentFinalizer,sa as buildIssueSearchQuery,bc as buildMergedPagination,_E as buildPackagePagination,Sc as buildPartialFailureWarnings,ob as buildPullRequestSearchCacheKey,ra as buildPullRequestSearchQuery,ta as buildRepoSearchQuery,Rc as buildResultPagination,ty as buildScalarExampleValue,dh as buildSearchNextMap,os as buildSearchResult,$u as buildToolErrorResult,po as buildWalkWarnings,j0 as bulkOutputEnvelopeFields,US as byteSlice,fi as byteToCharIndex,jp as charToByteIndex,bB as checkLargeOutputSafety,fz as checkNpmAvailability,$g as checkNpmDeprecation,iE as checkNpmRegistryReachable,Yc as checkRegexSafety,I as clampedInt,Jt as cleanJsonObject,I_ as cleanup,Pk as clearAllCache,Tk as clearLSPToolCache,wk as clearLocalToolCache,j_ as clearOctokitInstances,T0 as clearProviderCache,Ek as clearRemoteAPICache,_d as cloneRepo,Hu as collectDisplayFields,Bi as collectFlatErrors,vC as commonDirPrefix,Xc as compactLocation,AE as compactPackageRepositories,gt as compactResolvedSymbol,cf as compareIsoDateDescending,WY as completeMetadata,Nd as computeQueryTimeout,bz as configureCircuitBreaker,GY as configureSecurity,In as contextLinesField,fO as convertByteMatchToChar,rt as countLines,N as countSerializedChars,ka as createBasePRTransformation,Ln as createCacheMeta,wo as createCallItemKey,F as createErrorResult,mt as createGitHubProviderError,Ti as createGitHubProviderErrorFromResult,Be as createLazyProviderContext,Ea as createPaginationInfo,VC as createProviderExecutionContext,K as createRelaxedBulkQuerySchema,Nt as createResponseFormat,k0 as createResult,i1 as createSafeRegExp,se as createSuccessResult,jo as decrypt,dl as deleteCredentials,Wl as deleteSession,GE as describeSchemaConstraints,Gu as describeSchemaType,A2 as detectEnvironment,$o as encrypt,tl as ensureClone,vt as ensureCloneParentDir,Uo as ensureHome,Pt as ensureOctocodeDir,Sy as ensureRepos,Ts as ensureTmp,by as ensureTree,br as etagSoftCache,li as evictExpiredClones,wn as evictExpiredTrees,te as executeBulkOperation,zd as executeCloneRepo,SL as executeDirectTool,Bf as executeFetchContent,sh as executeFindDeadCode,Wf as executeFindFiles,xu as executeLspGetSemantics,Ut as executeNpmCommand,ft as executeProviderOperation,jd as executeProviderOperations,Eh as executeRipgrepSearch,hh as executeRipgrepSearchInternal,Nh as executeViewStructure,vd as executeWithErrorIsolation,Fe as executeWithToolBoundary,yf as exploreMultipleRepositoryStructures,xn as extractEtag,di as extractMatchingLines,Pf as fallbackOnBestEffortFailure,Nf as fetchContent,ga as fetchDirectoryContents,Nr as fetchDirectoryContentsRecursivelyAPI,wa as fetchFileContentToDisk,Aa as fetchFileTimestamp,Kp as fetchGitHubFileContentAPI,wF as fetchGitHubPullRequestByNumberAPI,Ba as fetchGitHubPullRequestByNumberAPIInternal,rd as fetchHistory,lm as fetchMultipleGitHubFileContents,Ar as fetchRawGitHubFileContent,st as fetchWithRetries,Yp as filterPatch,Zx as filterStructure,mh as finalizeRipgrepResult,ih as findDeadCode,$t as findDirectToolDefinition,zf as findFiles,Ir as findNextBlockBoundary,Nl as flushSession,Gl as flushSessionSync,vu as foldKeywords,rR as formatBytes,I0 as formatCallToolResultForOutput,oy as formatDirectToolCommandPattern,NV as formatDirectToolMetadataSchemaText,BV as formatDirectToolOutputSchemaText,MV as formatDirectToolSchemaText,WE as formatDirectToolValidationIssues,zn as formatFileSize,Ui as formatFinalizedResponse,An as formatPRForResponse,LE as formatPackageData,ru as gatherIncomingCallsRecursive,ou as gatherOutgoingCallsRecursive,ce as generateCacheKey,lv as generatePaginationHints,Pi as generateStructurePaginationHints,js as getActiveProvider,zs as getActiveProviderConfig,xl as getAppDataPath,Tl as getArchitecture,pO as getBulkDefaultCharLength,zp as getByteLength,Lk as getCacheStats,mS as getCacheTTL,Pr as getCloneBaseDir,ma as getCloneDir,Wt as getCredentials,yl as getCredentialsFilePath,Vo as getCredentialsSync,el as getDefaultOctocodeHome,Nu as getDescription,GV as getDirectToolAutoFilledFields,Zn as getDirectToolCategory,UV as getDirectToolDescription,Ss as getDirectToolDisplayFields,HV as getDirectToolOutputFields,hr as getDirectorySizeBytes,pp as getExtension,Rd as getFileContent,zo as getGhCliToken,$s as getGitHubToken,Pl as getLocalAppDataPath,k2 as getLspEnvironmentHint,fS as getMaxCacheSizeBytes,hS as getMaxCloneCount,EV as getMetadataOrNull,Lo as getNpmRegistryUrl,zt as getOctocodeDir,Q as getOctokit,Hl as getOrCreateSession,Dt as getOutputCharLimit,up as getOwnerQualifier,wl as getPlatformName,Xa as getProvider,ne as getRawResponseChars,Mr as getRecursiveFetchFailureCount,bd as getRepoStructure,eS as getReposBaseDir,gr as getServerConfig,Bl as getSessionId,Rl as getToken,F_ as getTokenSource,Sl as getTokenSync,Fs as getTokenWithRefresh,ui as getTreeBaseDir,wr as getTreeDir,be as handleCatchError,V as handleGitHubAPIError,ki as handleProviderError,hl as hasCredentials,gl as hasCredentialsSync,AN as hasExpensiveContentRequest,Bu as hasSchemaDefault,Cx as hasValidCodeSearchParams,rp as hashGitHubToken,Mn as hoistSharedFields,wB as ignoreBestEffortFailure,Ql as incrementErrors,ti as incrementGitHubCacheHits,ni as incrementGitHubCacheRateLimits,jl as incrementPackageRegistryFailures,$l as incrementRateLimitByProvider,Zo as incrementRateLimits,Ul as incrementToolCalls,ei as incrementToolCharSavings,Sw as inferLspSymbolName,Xl as initialize,xd as initializeProviders,TV as initializeToolMetadata,ar as invalidateCredentialsCache,q0 as invokeCallbackSafely,En as isCacheHit,_p as isCacheValid,Fg as isCircuitOpen,ql as isCloneEnabled,Wn as isDiscussionsEnabled,un as isExactPackageName,Oe as isGitHubAPIError,Cb as isGitHubAPISuccess,er as isJsonSchemaObject,Ds as isLinux,O_ as isLocalEnabled,eQ as isLocalTool,vs as isMac,kr as isMidBlockCut,nt as isNoResultsSearchError,Du as isPackageNotFoundError,zC as isProviderError,Fi as isProviderSuccess,St as isRecord,ir as isRefreshTokenExpired,fo as isReleasesEnabled,xb as isRepository,ut as isTokenExpired,ws as isToolError,Sa as isToolInMetadata,cr as isWindows,On as lineNumberField,Jm as listMultipleGitHubReleases,ml as listStoredHosts,fl as listStoredHostsSync,wV as loadToolContent,oC as makeToolResultRowSchema,Jd as mapCodeSearchProviderResult,qd as mapCodeSearchToolQuery,om as mapFileContentProviderResult,rm as mapFileContentToolQuery,nm as mapPullRequestProviderResultData,tm as mapPullRequestToolQuery,em as mapRepoSearchProviderRepositories,Zd as mapRepoSearchToolQuery,im as mapRepoStructureProviderResult,ac as mapRepoStructureToolQuery,MY as maskSensitiveData,Fr as normalizeOwnerRepo,bm as normalizePullRequestContentRequest,EE as normalizeRepoUrl,Cn as normalizeResponseHeaders,Ac as paginateEntries,lo as parseFileSize,Re as parseGitHubProjectId,kn as parseHasMore,we as paths,fh as preflightValidateRipgrepPattern,zE as prepareDirectToolInput,n2 as prepareDirectToolInputFromJsonText,Vp as processFileContentAPI,vi as providerSupports,fp as rateLimitWarning,fa as readCacheMeta,pt as readCredentialsStore,hp as recomputeMatchPositions,Og as recordCircuitFailure,Tu as recordCircuitSuccess,Jl as recordPackageRegistryFailure,kt as recordRateLimit,or as redactPath,bl as refreshAuthToken,Dn as relativizeResultPaths,q as relaxedPageNumberField,pi as removeCloneDir,Sz as resetCircuitBreaker,zl as resetSessionStats,_s as resetTokenResolution,fe as resolveCacheAuthFingerprint,Ae as resolveDefaultBranch,qc as resolveFileAnchor,Ur as resolveQueryId,Bh as resolveSymbolAnchor,ks as resolveToken,Tt as resolveTokenFull,Is as resolveTokenWithRefresh,Qr as resolveUniqueQueryIds,Pd as responseEnvelopeFields,v2 as safeExec,_e as safeParseOrError,Qu as sanitizeCallToolResult,Ve as sanitizeStructuredContent,gd as searchCode,is as searchContentRipgrep,yp as searchGitHubCodeAPI,nd as searchGitHubPullRequestsAPI,sd as searchGitHubReposAPI,ym as searchMultipleGitHubCode,qm as searchMultipleGitHubCommits,nf as searchMultipleGitHubDiscussions,Xm as searchMultipleGitHubIssues,qr as searchMultipleGitHubPullRequests,Ym as searchMultipleGitHubPullRequestsSplit,mf as searchMultipleGitHubRepos,Fu as searchNpmPackage,jg as searchPackage,Wg as searchPackages,Sd as searchPullRequests,yd as searchRepos,FY as securityRegistry,yO as serializeForPagination,Em as shapePullRequestForContent,Ia as shouldEnrichPullRequestFromSearch,Cr as shouldIgnoreDir,bn as shouldIgnoreFile,_2 as shouldUseMCPLsp,aa as shouldUseSearchForIssues,oa as shouldUseSearchForPRs,RO as sliceByCharRespectLines,Ta as sliceContent,gi as snapToSemanticBoundary,OV as sortDirectToolNames,Td as spawnCheckSuccess,aD as spawnCollectStdout,Zt as spawnWithTimeout,_r as splitLines,pI as startCacheGC,dI as stopCacheGC,Os as storeCredentials,Lc as summarizeEntries,vh as toEntryObject,Fh as toGroupedLists,qu as toToolError,Eb as transformCodeSearchResult,_b as transformFileContentResult,Dr as transformPullRequestItemFromREST,Ha as transformPullRequestItemFromSearch,Ob as transformPullRequestResult,Lb as transformRepoSearchResult,Hb as transformRepoStructureResult,Xp as trimDiffContext,ex as truncateSnippetChars,Ge as updateSessionStats,Ko as updateToken,Oi as validateArgs,ve as validateToolPath,Ka as viewGitHubRepositoryStructureAPI,Mh as viewStructure,zu as withBasicSecurityValidation,he as withDataCache,si as withDataCacheConditional,Q0 as withResponseEnvelope,ju as withSecurityValidation,Tn as writeCacheMeta,KY as z};
65
+ `);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 Wc(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Hc.test(e))return"comment";let o=bw(e,t,r);if(o<0)return"code";let i=Cw(e);return i>=0&&o>i?"comment":yh(e,o)?"string":"code"}function bw(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function Cw(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 yh(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 xw(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function Pw(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 ww(e,t,n,r,o){if(!e||e.length===0)return 0;let i=jc(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=zc(u,r,n.caseSensitive),p=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${is(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(p+=re.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(p+=re.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(p+=re.substring,m.push("substring match")));let d=c.kind;if(d)p+=Tw(d,m);else{let f=Wc(l,r,t.id,n.caseSensitive);f!=="code"?(p+=re.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(xo(t.declaration,l)&&(p+=re.declarationLine,m.push("declaration line")),xo(t.export,l)&&(p+=re.exportLine,m.push("export/public line")),xo(t.import,l)&&(p+=re.importLine,m.push("import line")),t.id==="markdown"&&Bc.test(l)&&(p+=re.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&Ew(l,r)&&(p+=re.configKeyLine,m.push("config key match")))}p>s&&(s=p,a=m.join(", "))}return a&&o.push(a),s}function Tw(e,t){switch(e){case"declaration":return t.push("AST: declaration"),re.declarationLine;case"export":return t.push("AST: export/public"),re.exportLine;case"configKey":return t.push("AST: config key"),re.configKeyLine;case"heading":return t.push("AST: heading"),re.headingLine;case"import":return t.push("AST: import"),re.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),re.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function Ew(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 Lw(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(rs,"").includes(u))&&(s+=re.pathSegmentToken,i.push("query token in path"))}let a=Co(e);return r.extensions.includes(a)&&t.langType&&(s+=re.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=re.sourceDir,i.push("source file")),s}function Aw(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),re.lowSignalPathPenalty):e==="test"?(n.push("test file (penalized)"),re.testPathPenalty):0}function kw(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*re.matchCountScale,r=Math.min(n,re.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function Vc(e,t){let n=Pw(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=>_w(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 _w(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${is(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function Iw(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*re.rareQueryTokenScale,re.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 Kc(e,t,n){let r=Uc(e.path,t.langType,t.profileOverride),o=os(e.path),i=xw(t.keyword),s=[],a=0;return a+=ww(e.matches,r,t,i,s),a+=Lw(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=re.pathUnderQuery,s.push("under requested subtree")),a+=Aw(o,t,s),bo.test(e.path)&&!t.explicitLowSignal&&(a+=re.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=kw(e.matchCount??0,s),a+=Iw(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var Ow=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"]),Fw=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Rh(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=vw(i);s.fetch={tool:"localGetFileContent",query:Yc({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"low":"exact"};let a=Dw(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"low"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"low"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Yc({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Yc({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function vw(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-8),endLine:n+8}}function Dw(e,t,n){if(t.output==="countLines"||t.output==="countMatches"||t.unique==="list"||t.unique==="count")return;if(n==="structural")return Mw(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.output==="matchOnly"){let o=Xc(e?.value);return o?{symbol:o}:void 0}let r=Xc(t.searchText);return r?{symbol:r}:void 0}function Mw(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=Xc(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function Xc(e){if(typeof e!="string")return;let t=e.trim();if(Fw.test(t)&&!Ow.has(t))return t}function Yc(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function ss(e,t,n,r,o){let i=t.sort??"relevance",s=n==="structural"&&i==="relevance"?"path":i,a;try{a=$c(e,s,Nw(t),{debug:!1,sortReverse:t.sortReverse})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,u=a.debug,l=c.length,p=t.output==="files"||t.output==="filesWithout",m=t.output==="countLines"||t.output==="countMatches",d=p||m,f=c.reduce((B,I)=>B+(I.matchCount??0),0),g=d?o?.totalOccurrences??o?.totalStructuralMatches??f:f,R=t,h=Math.min(R.itemsPerPage||Gt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),y=R.page||1,S=Math.max(1,Math.ceil(l/h)),C=(y-1)*h,P=Math.min(C+h,l),T=c.slice(C,P),L=l>0&&C>=l;L&&r.push(`page:${y} is out of range (only ${S} page(s), ${l} total file(s)) \u2014 returned 0 files. Use page:1..${S}.`);let k=R.maxMatchesPerFile||Gt.DEFAULT_MATCHES_PER_PAGE,w=T.map(B=>{let I=B.matches?.length??0,U=Math.max(1,Math.ceil(I/k)),ee=Math.max(1,R.matchPage||1),v=(ee-1)*k,q=I>0&&v>=I,le=Math.min(v+k,I),ae=d?void 0:B.matches?.slice(v,le),pe=ae?.length;q&&r.push(`${B.path}: matchPage:${ee} is out of range under maxMatchesPerFile:${k} (only ${U} page(s), ${I} total match(es) for this file) \u2014 returned 0 rows for this file. Use matchPage:1..${U}, or drop matchPage to re-derive it from the current maxMatchesPerFile.`);let Me=u?.get(B.path);return{path:B.path,...p?{}:t.output==="countLines"?{totalMatchedLines:B.matchCount||1}:t.output==="countMatches"?{totalOccurrences:B.matchCount||1}:{totalMatchRows:I,...pe!==void 0?{returnedMatchRows:pe}:{}},...ae!==void 0&&{matches:ae},...Me?{ranking:{score:Me.score,profile:Me.profile,pathRole:Me.pathRole,reasons:Me.reasons}}:{},pagination:!d&&(I>k||q)?{currentPage:ee,totalPages:U,matchesPerPage:k,totalMatches:I,hasMore:ee<U,...ee<U?{nextMatchPage:ee+1}:{},...q?{outOfRange:!0}:{}}:void 0}}),b=w.filter(B=>B.pagination?.hasMore),A=Rh(w,t,n,{isFileListMode:d,currentPage:y,totalFilePages:S,matchPage:R.matchPage||1,matchesPerPage:k,hasFileWithMoreMatches:b.length>0}),M={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:y,totalPages:S,filesPerPage:h,totalFiles:l,...p?{}:{totalMatches:g},hasMore:y<S,...y<S?{nextPage:y+1}:{},...L?{outOfRange:!0}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return Sh(M,t,{totalMatches:g,totalFiles:l})}function Sh(e,t,n){return e}function Nw(e){let t=e.rankingProfile,n=!!(e.include?.length||Qc(e.path));return{queryPath:e.path,keyword:e.searchText,langType:e.langType,caseSensitive:e.caseMode==="sensitive",wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function bh(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&&Gw(r)&&n.push(`pattern '${r}' looks literal \u2014 set regex:"fixed" to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&Hw(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function Gw(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function Hw(e){return/\(\?[=!<]/.test(e)}import Vn from"node:path";function Uw(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function Qw(e){return{path:e.path,pattern:e.searchText??"",fixedString:e.regex==="fixed",perlRegex:e.regex==="perl",caseSensitive:e.caseMode==="sensitive",caseInsensitive:e.caseMode==="insensitive",wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline==="on"||e.multiline==="dotall",multilineDotall:e.multiline==="dotall",filesOnly:e.output==="files",filesWithoutMatch:e.output==="filesWithout",countLinesPerFile:e.output==="countLines",countMatchesPerFile:e.output==="countMatches",contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:Uw(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.output==="matchOnly",unique:e.unique==="list"||e.unique==="count",countUnique:e.unique==="count",matchWindow:e.matchWindow,maxCollectedFiles:1e4}}function $w(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}function jw(e,t){let n=Vn.isAbsolute(e)?e:Vn.join(t,e),r=Vn.relative(t,n);if(!r||r.startsWith("..")||Vn.isAbsolute(r))return 0;let o=Vn.dirname(r);return o==="."?0:o.split(Vn.sep).filter(Boolean).length}async function Ch(e){let t=[],n=Bw(e);if(!n.isValid)return F(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:x.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=ht.safeParse(e);if(!r.success){let h=r.error.issues.map(y=>y.message);return F(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:x.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return F(new Error("Path is required for search"),o,{toolName:x.LOCAL_RIPGREP,extra:{warnings:t}});let s=ve(o,x.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=bh({pattern:a.searchText??"",fixedString:a.regex==="fixed",perlRegex:a.regex==="perl"});if(!c.isValid)return F(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:x.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await O.searchRipgrep(Qw(a))}catch(h){return F(h instanceof Error?h:new Error(String(h)),o,{toolName:x.LOCAL_RIPGREP})}let p=l.files.map(h=>({path:h.path,matchCount:h.matchCount,matches:h.matches.map(y=>{let S={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(S.count=y.count),y.kind!==void 0&&(S.kind=y.kind),y.scoreHint!==void 0&&(S.scoreHint=y.scoreHint),S})})),m=a.maxDepth,d=m===void 0?p:p.filter(h=>jw(h.path,a.path)<=m);m!==void 0&&d.length!==p.length&&u.push(`Applied maxDepth:${m} after native text search; filtered ${p.length-d.length} deeper file(s).`);let f=$w(d),g={totalOccurrences:l.stats.matchCount,matchedLines:l.stats.matchedLines,filesMatched:d.length,filesSearched:l.stats.filesSearched,bytesSearched:l.stats.bytesSearched??void 0,searchTime:l.stats.searchTime,capped:l.stats.capped??void 0,capReason:l.stats.capReason??void 0};if(l.stats.capped&&u.push(`Search hit native collection cap (${l.stats.capReason??"resource limit"}); narrow path/include/keywords for exhaustive results.`),d.length===0){let h=['No matches \u2014 broaden the search: try caseMode:"insensitive", a shorter/partial term, or regex:"smart" instead of "fixed".',...a.include?.length||a.maxDepth!==void 0?["Filters are active (include/maxDepth) \u2014 drop them to search the wider tree."]:[],...a.wholeWord?["wholeWord:true excludes partial hits \u2014 drop it to match substrings."]:[]];return $({status:"empty",searchEngine:"rg",stats:g,hints:h,warnings:[...t,...u]},f)}a.output!=="files"&&f>Gt.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(f/1024)}KB).`);let R=await ss(d,o,"rg",[...t,...u],g);return $(R,f)}import{readFile as Vw,stat as Kw}from"node:fs/promises";var xh={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},Ph={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}};function zw(e){return e.trim().replace(/^\./,"").toLowerCase()}function wh(e){if(!e?.trim())return;let t=zw(e),n=xh[t]??Ph[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function qc(e){let t=wh(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}var Ww=/^\s*(\/\/|\/\*|\*|#)/;function Eh(e,t,n){let r=t&&Object.keys(t).length>0;if(n)return{...e?{metavars:e}:{},...r?{metavarRanges:t??void 0}:{}};let o;if(e){o={};for(let[s,a]of Object.entries(e))a.length<=1&&(o[s]=a.map(Th));Object.keys(o).length===0&&(o=void 0)}let i;if(r&&t){i={};for(let[s,a]of Object.entries(t)){let u=(a.length>1?a.filter(l=>!Ww.test(l.text)):a).map(l=>({...l,text:Th(l.text)}));u.length>0&&(i[s]=u)}Object.keys(i).length===0&&(i=void 0)}return{...o?{metavars:o}:{},...i?{metavarRanges:i}:{}}}function Th(e){return e.length>120?`${e.slice(0,120)}\u2026`:e}var Lh=[],Ah=2e3,Yw=1e6,Xw="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`.";function _h(e){if(!e||!/\)\s*\{/.test(e))return;let t=e.replace(/\)\s*\{/,"): $R {");return t===e?void 0:t}function qw(e){let t=_h(e);return t?` Try: \`${t}\`.`:""}function kh(e){return e.include?.length?e.include:qc(e.langType)}async function Jw(e){try{return(await Kw(e)).isFile()}catch{return!1}}async function Zw(e,t,n){let r=await Vw(e,"utf8"),o=await O.structuralSearch(r,e,n??t.pattern,t.rule);return{files:o.length>0?[{path:e,matches:o}]:[],totalMatches:o.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Ih(e){let t=ve(e,x.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=await Jw(t.sanitizedPath),r=!!e.captureText,o=S=>({path:t.sanitizedPath,pattern:S??e.pattern,rule:e.rule,...kh(e)?{include:kh(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Lh.length?{excludeDir:Lh}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??Ah,maxFileBytes:Yw}),i=S=>n?Zw(t.sanitizedPath,e,S):O.structuralSearchFiles(o(S)),s,a=!1,c;try{if(s=await i(),s.totalMatches===0&&e.pattern&&!e.rule&&!/[;}]\s*$/.test(e.pattern))try{let S=await i(`${e.pattern};`);S.totalMatches>0&&(s=S,a=!0)}catch{}if(s.totalMatches===0&&e.pattern&&!e.rule){let S=_h(e.pattern);if(S)try{let C=await i(S);C.totalMatches>0&&(s=C,c=S)}catch{}}}catch(S){let C=S instanceof Error?S.message:String(S),P=e.langType||"source";return F(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${C} \u2014 patterns must be valid ${P} 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:x.LOCAL_RIPGREP})}let u=s.files.map(S=>({path:S.path,matchCount:S.matches.length,matches:S.matches.map(C=>({line:C.startLine,endLine:C.endLine,value:C.text.replace(/\s+/g," ").trim().slice(0,300),column:C.startCol,endColumn:C.endCol,...Eh(C.metavars,C.metavarRanges,r)}))})),l=e.maxDepth,p=u,m=0;if(typeof l=="number"&&!n){let S=t.sanitizedPath.replace(/\/+$/,"");p=u.filter(C=>(C.path.startsWith(`${S}/`)?C.path.slice(S.length+1):C.path).split("/").length<=l+1),m=u.length-p.length}let d=p.reduce((S,C)=>S+(C.matchCount??C.matches?.length??0),0),f=e.maxFiles??Ah,R=(s.parsedFiles??0)+(s.skippedUnreadable??0)+(s.skippedLarge??0)>=f,h={totalStructuralMatches:typeof l=="number"?d:s.totalMatches,...R?{capReached:!0}:{}},y=[...s.warnings];if(m>0&&y.push(`maxDepth ${l}: dropped ${m} deeper file(s) \u2014 raise maxDepth or omit it to include them.`),a&&y.push(`Matched after appending ';' \u2014 statement patterns must parse as complete statements; the bare pattern parsed as an expression fragment. Results are for "${e.pattern};".`),c&&y.push(`Matched after adding a return-type metavar \u2014 the bare pattern missed functions that declare a return type. Results are for "${c}".`),s.totalMatches===0&&!n)try{let S=O.structuralSearchFilesDetailed(o()),C=S.query;if(C){let P=[`query parsed as ${C.kind}`];C.literalAnchor&&P.push(`literal anchor "${C.literalAnchor}"`),P.push(`pre-filter: ${C.preFilter}`),C.unsafeReason&&P.push(`unsafe: ${C.unsafeReason}`),y.push(`Engine explanation: ${P.join(", ")}.`);for(let T of[...C.diagnostics??[],...S.diagnostics??[]].slice(0,3))y.push(`Engine ${T.severity} [${T.stage}/${T.code}]: ${T.message}${T.recovery?` \u2014 ${T.recovery}`:""}`)}}catch{}return(p.length===0||h.totalStructuralMatches===0)&&e.pattern&&!e.rule&&m===0&&y.push(Xw+qw(e.pattern)),await ss(p,e,"structural",y,h)}function eT(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.output==="content"?n.output="files":t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function as(e){let t=eT(e);if(t.mode==="structural")return await Ih(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Ch(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}:F(n,t,{toolName:x.LOCAL_RIPGREP})}}async function Oh(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=ke(ht,n);return r.ok===!1?r.error:await as(r.data)}}),{toolName:x.LOCAL_RIPGREP},e)}import{z as Fh}from"zod";import{ViewStructureQuerySchema as vh}from"@octocodeai/octocode-core/schemas";var Dh={excludeDir:Fh.array(Fh.string()).optional().describe("Directory names to prune from recursive walks (default: common generated/vendor dirs such as node_modules, dist, build, out, coverage, target). Pass [] to inspect everything."),maxDepth:_(0,20).optional(),limit:_(1,1e4).optional(),page:K.default(1),itemsPerPage:_(1,50).optional()},tT=Z(vh,Dh),cn=X(vh,Dh),Po=Y(tT,{maxQueries:5});var nT=new Set(["+","*","?"]),rT=1e3;function oT(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Mh(e,t){let n=e[t];return n===void 0?!1:nT.has(n)||n==="{"&&aT(e,t)}function iT(e,t,n){let r=n.pop()??!1,o=Mh(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?Nh(e,t+1):t+1})}function sT(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Nh(e,t)})}function Jc(e){if(e.length>rT)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=oT(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=iT(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Mh(e,r)){let i=sT(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function aT(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 Nh(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function Tj(e,t){let n=Jc(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}function Gh(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(!Jc(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 n}function Hh(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 Bh(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 Uh(e){let t={},n=e.find(o=>o.type==="file"&&o.path);n?.path&&(t.fetch={tool:"localGetFileContent",query:{path:n.path,minify:"standard"},why:'Read the first listed file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"});let r=e.find(o=>o.type==="directory"&&o.path);return r?.path&&(t.viewDeeper={tool:"localViewStructure",query:{path:r.path},why:"Descend into the first listed subdirectory.",confidence:"exact"}),t.fetch||t.viewDeeper?t:void 0}var cT=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function uT(e,t){let n=t??cT,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Qh(e){try{let t=ve(e,x.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.detail==="modified"||e.detail==="full"||e.sortBy==="time";return lT(e,t.sanitizedPath,n)}catch(t){let n=Le.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function lT(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=dT(e),s=pT(e,i),a=r&&s?1e4:1e4,c=uT(t,e.excludeDir),u;try{u=O.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:mT(e),excludeDir:c,limit:a})}catch(L){return gT(L,e,t)}let l=u.entries.map(L=>fT(L,n,e.detail==="full")),p=Gh(l,e),m=e.sortBy??"name";p=p.sort((L,k)=>{let w=0;switch(m){case"size":{let b=L.sizeBytes??(L.size?po(L.size):0),A=k.sizeBytes??(k.size?po(k.size):0);w=b-A;break}case"time":n&&L.modified&&k.modified?w=L.modified.localeCompare(k.modified):w=L.name.localeCompare(k.name);break;case"extension":w=(L.extension||"").localeCompare(k.extension||"");break;default:w=L.name.localeCompare(k.name);break}return e.reverse?-w:w}),e.limit&&(p=p.slice(0,e.limit));let d=p.length,{paginatedEntries:f,pagination:g}=Ic(p,e),h=e.detail==="full"||e.detail==="modified"?{path:t,entries:f.map(L=>({...Bh(L),path:L.path??`${t.replace(/\/$/,"")}/${L.name}`}))}:{path:t,...Hh(f)},y=[...u.warnings,...mo({skipped:u.skipped,permissionDenied:u.permissionDenied}),...u.wasCapped?[`Results capped at ${a} entries during the walk before sorting \u2014 sortBy:"${m}" only orders that partial set, not the true top-N across the whole tree. Add pattern/extensions/entryType/excludeDir or reduce depth to narrow the scope.`]:[],...g.outOfRange?[`page:${e.page} is out of range (only ${g.totalPages} page(s), ${g.totalEntries} total entries) \u2014 returned page ${g.currentPage} instead.`]:[]],S=d===0,C=_c(p),T={...Uh(f)??{},...g.hasMore?{nextPage:Fn(x.LOCAL_VIEW_STRUCTURE,{...e,page:g.currentPage+1},"Continue to the next page of directory entries.")}:{}};return $({...S?{status:"empty"}:{},...h,summary:C,...g.hasMore||g.totalPages>1||g.outOfRange?{pagination:g}:{},...Object.keys(T).length>0?{next:T}:{},...y.length>0&&{warnings:y}},u.entries.reduce((L,k)=>L+k.path.length,0))}function pT(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function dT(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function mT(e){return e.entryType}function fT(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:zn(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=hT(e.permissions)),o}function hT(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 gT(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=Le.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return F(a,t,{toolName:x.LOCAL_VIEW_STRUCTURE})}async function $h(e){let{queries:t}=e;return te(t||[],async n=>Fe({toolName:x.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=ke(cn,n);return r.ok===!1?r.error:await Qh(r.data)}}),{toolName:x.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import{acquirePooledClientDetailed as oE,isLanguageServerAvailable as iE}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as sE}from"@octocodeai/octocode-engine/lsp/workspaceRoot";var jh=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];function gt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0},...e.lineDeviation!==void 0&&{lineDeviation:e.lineDeviation}}}function Zc(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 yT=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"]);function RT(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function zh(e,t){if(t===void 0||t==="progressIdle")return e;let n=RT(e);if(!n||!yT.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}import{readFile as ST,stat as bT}from"node:fs/promises";import{SymbolResolver as CT,SymbolResolutionError as xT}from"@octocodeai/octocode-engine/lsp/resolver";import{toUri as PT}from"@octocodeai/octocode-engine/lsp/uri";import{LSP_ERROR_CODES as cs}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function eu(e,t){let n=e.uri,r=ve({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await bT(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:cs.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:cs.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:PT(o),absolutePath:o,content:await ST(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:cs.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Wh(e,t){let n=await eu(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 CT({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=e.lineHint!==void 0?Math.abs(o.foundAtLine-e.lineHint):void 0,u=a>1&&c!==void 0&&c>0?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.uri,range:wT(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u},...c!==void 0&&c>0?{lineDeviation:c}:{}}}}}catch(o){if(o instanceof xT)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:cs.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 wT(e){return{start:e,end:{line:e.line,character:e.character}}}import Eo from"node:path";import{readFile as UT}from"node:fs/promises";import{resolveImportAliasDefinitions as QT}from"@octocodeai/octocode-engine/lsp/resolver";var Bt=40,us=40,tu=10;function nu(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function ru(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:nu(e.type,t),reason:t}}}function Qe(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:nu(e,n),reason:n}}}function $e(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 wo(e,t,n,r,o){let i=o.length>0,s=o.map(Zc),{pageItems:a,pagination:c}=$e(s,e.page??1,e.itemsPerPage??us);return{type:e.type,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function ou(e,t,n,r){let o=n.map(p=>{let m=p.uri===t.uri&&p.range.start.line===t.resolvedSymbol.position.line&&p.range.start.character===t.resolvedSymbol.position.character;return{...p,...m?{isDefinition:!0}:{}}}),i=e.groupByFile?Vh(o):void 0,s=i??o.map(Zc),{pageItems:a,pagination:c}=$e(s,e.page??1,e.itemsPerPage??us),u=o.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0,l=r?.possiblyTruncated===!0?[`Reference warmup opened ${r.warmedFiles}/${r.candidates} candidate file(s) and may be incomplete because the candidate set hit the warmup cap; narrow workspaceRoot/path or confirm with localSearchCode before unused/safe-delete claims.`]:[];return{type:"references",uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...i?{byFile:a}:{locations:a},totalReferences:o.length,totalFiles:new Set(o.map(p=>p.uri)).size,...o.length>0&&o.every(p=>p.isDefinition)?{definitionOnly:!0}:{},...r?{warmup:r}:{},...u?{empty:u}:{}},pagination:c,...l.length>0?{warnings:l}:{}}}async function iu(e,t,n){let r=Kh(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function Vh(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 Kh(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=>Yh(r)).join(`
66
+ `).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 Yh(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}import{safeReadLineWindow as TT}from"@octocodeai/octocode-engine/lsp/validation";var ET={maxNodes:100,maxRequests:50},Xh={truncatedByDepth:!1,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,cycleCount:0,failedRequestCount:0};function qh(e){return{...ET,...e,visitedNodeCount:0,requestCount:0,truncatedByBudget:!1}}function Jh(e){return e.requestCount>=e.maxRequests?(e.truncatedByBudget=!0,!1):(e.requestCount+=1,!0)}function Zh(e){return e.visitedNodeCount>=e.maxNodes?(e.truncatedByBudget=!0,!1):(e.visitedNodeCount+=1,!0)}function it(e,t){return{...e,truncatedByBudget:t.truncatedByBudget,visitedNodeCount:t.visitedNodeCount,requestCount:t.requestCount}}function To(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function eg(e,t,n){if(t<=0)return e;let r=n?.[0]?.start.line??e.range.start.line,o=await TT(e.uri,r,t);if(!o)return e;let i=kr(o).length,s=Math.max(0,r-t),a=s+Math.max(0,i-1);return{...e,content:o,displayRange:{startLine:s+1,endLine:a+1}}}async function LT(e,t){return Promise.all(e.map(async n=>({...n,from:await eg(n.from,t,n.fromRanges)})))}async function AT(e,t){return Promise.all(e.map(async n=>({...n,to:await eg(n.to,t)})))}async function su(e,t,n,r,o,i=qh(void 0)){if(n<=0||!e)return{calls:[],...Xh};if(!Jh(i))return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getIncomingCalls(t),a=o>0?await LT(s,o):s;if(n===1)return it({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=To(u.from);if(r.has(l)){c.push(it({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!Zh(i)||(r.add(l),c.push(await su(e,u.from,n-1,r,o,i)),i.truncatedByBudget))break}return it({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}async function au(e,t,n,r,o,i=qh(void 0)){if(n<=0||!e)return{calls:[],...Xh};if(!Jh(i))return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getOutgoingCalls(t),a=o>0?await AT(s,o):s;if(n===1)return it({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=To(u.to);if(r.has(l)){c.push(it({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!Zh(i)||(r.add(l),c.push(await au(e,u.to,n-1,r,o,i)),i.truncatedByBudget))break}return it({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return it({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}var kT=new Set(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),_T=new Set(["symbolNotFound","anchorFailed"]);function IT(e){if(e.kind==="empty"&&typeof e.category=="string")return{category:e.category,...typeof e.reason=="string"?{reason:e.reason}:{}};let t=e.empty;if(yt(t)&&typeof t.category=="string")return{category:t.category,...typeof t.reason=="string"?{reason:t.reason}:{}}}function OT(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"rs":return"^\\s*pub\\s";case"py":case"pyi":return"^\\s*(def|class)\\s";case"go":return"^(func|type|var|const)\\s";case"java":case"kt":case"scala":case"cs":return"^\\s*(public|protected|internal)\\s";case"rb":return"^\\s*(def|class|module)\\s";default:return"^\\s*export\\s"}}function FT(e,t){let n=e.symbolName;if(typeof n=="string"&&n.trim())return n.trim();let r=t.resolvedSymbol?.name;if(typeof r=="string"&&r.trim())return r.trim()}function cu(e,t){if(!uu(t))return t;let n=t.payload,r=n.locations?.[0],o=r?.displayRange?.startLine;if(r?.uri&&typeof o=="number"){let c=r.uri.startsWith("file://")?decodeURIComponent(r.uri.slice(7)):r.uri;return{...t,next:{readSite:{tool:"localGetFileContent",query:{path:c,startLine:Math.max(1,o-3),endLine:(r.displayRange?.endLine??o)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}let i=IT(n);if(i?.category==="unsupportedOperation"&&t.type==="documentSymbols"&&t.uri){let c=t.uri.startsWith("file://")?decodeURIComponent(t.uri.slice(7)):t.uri;return{...t,next:{textSearch:{tool:"localSearchCode",query:{path:c,searchText:OT(c),regex:"perl"},why:"documentSymbols is unsupported for this file's language server \u2014 fall back to a regex search over top-level declarations for an outline.",confidence:"low"}}}}let s=FT(e,t);if(!i||!s||!kT.has(i.category))return t;let a={textSearch:{tool:"localSearchCode",query:{keywords:s},why:`Semantic ${t.type} returned no result (${i.category}) \u2014 fall back to a text search for "${s}"`,confidence:"low"}};return _T.has(i.category)&&t.uri&&(a.reAnchor={tool:"lspGetSemantics",query:{type:"documentSymbols",uri:t.uri},why:"Re-anchor: list this file's symbols to find the correct lineHint, then retry the semantic query",confidence:"medium"}),{...t,next:a}}var vT=8;function ng(e){return $(e,N(e))}function rg(e,t){return e.format!=="compact"||!uu(t)?t:DT(t)}function uu(e){return yt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&yt(e.payload)}function DT(e){return{...e,format:"compact",payload:MT(e.payload)}}function MT(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(tg)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(GT)}:{locations:(e.locations??[]).map(tg)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:og(e.root)}:{},direction:e.direction,calls:e.calls.map(HT),...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(NT)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function NT(e){if(!yt(e))return String(e);let t=De(e,"line"),n=De(e,"character"),r=De(e,"endLine"),o=Rt(e,"kind"),i=Rt(e,"name"),s=De(e,"childCount"),a=Rt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function tg(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${sg(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function GT(e){if(!yt(e))return String(e);let t=Rt(e,"uri"),n=De(e,"firstLine"),r=De(e,"firstCharacter"),o=De(e,"count"),i=ig(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 HT(e){if(!yt(e))return String(e);let t=Rt(e,"direction"),n=og(e.item),r=ig(e,"ranges").map(BT).join(","),o=De(e,"rangeCount"),i=De(e,"rangeSampleCount"),s=Rt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${sg(s,180)}`:""].filter(Boolean).join(" ")}function og(e){if(!yt(e))return String(e);let t=Rt(e,"name"),n=Rt(e,"kind"),r=Rt(e,"uri"),o=De(e,"line"),i=De(e,"endLine"),s=De(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function BT(e){return yt(e)?`${De(e,"line")}:${De(e,"character")}`:String(e)}function yt(e){return typeof e=="object"&&e!==null}function Rt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function De(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function ig(e,t){let n=e[t];return Array.isArray(n)?n:[]}function sg(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}function ag(e,t){let n=ug(e.fromRanges);return{direction:"incoming",item:ls(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...lg(e.from,t)}}function cg(e,t){let n=ug(e.fromRanges);return{direction:"outgoing",item:ls(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...lg(e.to,t)}}function ls(e){return{name:e.name,kind:Kn(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 ug(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>=vT))break}return n}function lg(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Kn(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}async function lu(e,t,n){let o=(await n.prepareCallHierarchy(t.absolutePath,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,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await su(n,o,i,new Set([To(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await au(n,o,i,new Set([To(o)]),e.contextLines??0):s,u=y=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(y.to.uri),l=c.calls.filter(u).length,p=c.calls.filter(y=>!u(y)),m=[...a.calls.map(y=>({direction:"incoming",...y})),...p.map(y=>({direction:"outgoing",...y}))],d=m.map(y=>y.direction==="incoming"?ag(y,e.contextLines??0):cg(y,e.contextLines??0)),{pageItems:f,pagination:g}=$e(d,e.page??1,e.itemsPerPage??tu),R=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",h=!a.truncatedByDepth&&!c.truncatedByDepth&&!a.truncatedByBudget&&!c.truncatedByBudget&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:ls(o),direction:R,calls:f,incomingCalls:a.calls.length,outgoingCalls:p.length,completeness:{complete:h,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,truncatedByBudget:a.truncatedByBudget||c.truncatedByBudget,visitedNodeCount:a.visitedNodeCount+c.visitedNodeCount,requestCount:a.requestCount+c.requestCount,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function pu(e,t,n){let o=(await n.prepareTypeHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Qe(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=$e(s,e.page??1,e.itemsPerPage??Bt);return{type:e.type,uri:t.uri,resolvedSymbol:gt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}var mg=new Set(["references","callers","callees","callHierarchy","implementation"]),pg=100,$T=512*1024,dg=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];async function fg(e,t,n){let r={candidates:0,warmedFiles:0,skippedLarge:0,possiblyTruncated:!1};if(typeof e.openDocument!="function")return r;try{let o=Eo.extname(t.absolutePath).slice(1),i=dg.includes(o)?dg:[o],s=await as({path:n,searchText:t.resolvedSymbol.name,regex:"fixed",wholeWord:!0,output:"files",maxFiles:pg,include:i.filter(Boolean).map(c=>`*.${c}`)}),a={candidates:s.files?.length??0,warmedFiles:0,skippedLarge:0,possiblyTruncated:(s.files?.length??0)>=pg||!!s.stats?.capped};for(let c of s.files??[]){let u=typeof c.path=="string"?c.path:void 0;if(!u)continue;let l=Eo.isAbsolute(u)?u:Eo.join(n,u);if(Eo.resolve(l)!==Eo.resolve(t.absolutePath))try{let p=await UT(l,"utf-8");if(p.length>$T){a.skippedLarge+=1;continue}await e.openDocument(l,p),a.warmedFiles+=1}catch{}}return a}catch{return r}}async function hg(e,t,n,r){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?wo(e,t,"definition","definitionProvider",await QT({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)})):Qe(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?wo(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):Qe(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?wo(e,t,"implementation","implementationProvider",await n.implementation(t.absolutePath,t.resolvedSymbol.position,t.content)):Qe(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?ou(e,t,await n.findReferences(t.absolutePath,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content),r):Qe(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?iu(e,t,await n.hover(t.absolutePath,t.resolvedSymbol.position,t.content)):Qe(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?lu(e,t,n):Qe(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?pu(e,t,n):Qe(e.type,t,"typeHierarchyProvider unsupported",!0)}}import mu from"node:path";import{fileURLToPath as jT}from"node:url";import{unavailableHintFor as zT}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as WT}from"@octocodeai/octocode-engine/lsp/config";var du;function fu(e){return du||(du=new Set(O.getSupportedJsTsExtensions().map(t=>`.${t}`))),du.has(mu.extname(e).toLowerCase())}function Xe(e,t,n){let r=WT(e),o=zT(r,void 0),i=n?.message?` LSP startup detail (${n.kind??"startupFailed"}): ${n.message}.`:"";throw new xe(H.LSP_SERVER_UNAVAILABLE,`No ${r} language server is available for ${e}, so "${t}" cannot be answered semantically.${i} ${o} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}var VT=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];function gg(e,t){let n=e.startsWith("file://")?jT(e):e;return mu.isAbsolute(n)?n:mu.resolve(t,n)}function hu(){return[...O.getSupportedJsTsExtensions(),...VT]}function yg(){return hu().map(e=>`**/*.${e}`)}var KT=[".git","node_modules","dist","out","coverage","target"];async function Rg(e,t){let n=e.symbolName?.trim();if(n)try{return(await O.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:yg(),excludeDir:[...KT],maxSnippetChars:1})).files[0]?.path}catch{return}}async function gu(e,t){if(e.uri)return gg(e.uri,t);let n=await Rg(e,t);if(n)return n;try{let o=O.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:hu(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function yu(e){return e instanceof Error?e.message:String(e)}function Ru(e,t){if(!fu(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}}function YT(e){if(!e||typeof e!="object")return!1;let t=e,n=r=>!!r&&typeof r=="object"&&typeof r.line=="number"&&typeof r.character=="number";return n(t.start)&&n(t.end)}function Sg(e,t){if(!fu(e))return null;try{let n=O.extractGraphFacts(t,e);if(!n)return null;let r=JSON.parse(n),i=(Array.isArray(r.declarations)?r.declarations:[]).filter(s=>typeof s.name=="string"&&ts(s.name)&&typeof s.kind=="string"&&YT(s.range)).map(s=>({name:s.name,kind:s.kind,range:s.range}));return i.length>0?i:null}catch{return null}}import{acquirePooledClient as XT,isLanguageServerAvailable as qT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as JT}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Cu(e){let t=await eu(e,ge);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await JT(t.value.absolutePath),r=await qT(t.value.absolutePath,n),o=r?await XT(n,t.value.absolutePath):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Ru(t.value.uri,t.value.content),u=c?.length?null:Sg(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(u?.length)s=u,a="native-graph-facts";else if(i&&o){let h=await o.documentSymbols(t.value.absolutePath,t.value.content);s=Array.isArray(h)?h:[],a="lsp"}else{let h=$p(t.value.content,t.value.uri);h&&(s=h,a="markdown")}let l=a!==void 0;!l&&!r&&Xe(t.value.uri,"documentSymbols");let p=bg(s),m=xg(s),{pageItems:d,pagination:f}=$e(p,e.page??1,e.itemsPerPage??Bt),g=Pg(p,h=>h.kind),R=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:p.length,returnedSymbols:d.length,topLevelSymbols:m,kinds:g},payload:{kind:"documentSymbols",symbols:d,...R?{empty:R}:{}},pagination:f}}function bg(e){let t=[];for(let n of e)xu(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function xu(e,t,n){if(!e||typeof e!="object")return;let r=e,o=Cg(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Kn(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)&&ZT.has(Kn(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)xu(s,t,i)}}var ZT=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"]);function Cg(e){if(Su(e.range))return e.range;let t=e.location;return t&&Su(t.range)?t.range:void 0}function Su(e){if(!e||typeof e!="object")return!1;let t=e;return bu(t.start)&&bu(t.end)}function bu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function xg(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Pg(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}import wg from"node:path";import{readFile as eE}from"node:fs/promises";import{acquirePooledClientDetailed as Tg,isLanguageServerAvailable as Eg}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as tE}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Lg}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Pu(e){let t=e.symbolName??"",n=wg.resolve(e.workspaceRoot??(e.uri?await Lg(e.uri):process.cwd())),r=await gu(e,n);await Eg(r,n)||Xe(r,"workspaceSymbol");let i=await Tg(n,r);i.ok===!1&&Xe(r,"workspaceSymbol",i);let s=i.client;if(!s.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let a;try{wg.extname(r)&&await s.openDocument(r),a=await s.workspaceSymbol(t)}catch(p){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${yu(p)}`}}}let c=await rE(s,Ag(a)),{pageItems:u,pagination:l}=$e(c,e.page??1,e.itemsPerPage??Bt);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:c.length},payload:c.length>0?{kind:"workspaceSymbol",query:t,symbols:u,totalSymbols:c.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}var nE=10;async function rE(e,t){return t.length===0||t.length>nE?t:Promise.all(t.map(async n=>{try{if(!n.uri)return n;let r=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri,o=await eE(r,"utf8");await e.openDocument(r);let i=await tE({anchorUri:r,symbolName:n.name,locations:await e.gotoDefinition(r,{line:n.line-1,character:n.character},o)});if(!Array.isArray(i)||i.length!==1)return n;let s=i[0],a=(s.range?.start?.line??-1)+1;return!s.uri||a<1||s.uri===n.uri&&a===n.line?n:{...n,uri:s.uri,line:a,endLine:(s.range?.end?.line??s.range?.start?.line??a-1)+1,character:s.range?.start?.character??n.character}}catch{return n}}))}function Ag(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,u=(s?.end?.line??s?.start?.line??0)+1,l=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:Kn(o),line:c,character:s?.start?.character??0,endLine:u,childCount:0,...l?{containerName:l}:{},uri:a}]})}async function wu(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Lg(t):process.cwd());await Eg(t,n)||Xe(t,"diagnostic");let o=await Tg(n,t);o.ok===!1&&Xe(t,"diagnostic",o);let i=o.client;if(!i.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let s=await i.getDiagnostics(t),a=kg(s),c=a.filter(m=>m.severity===1).length,u=a.filter(m=>m.severity===2).length,{pageItems:l,pagination:p}=$e(a,e.page??1,e.itemsPerPage??Bt);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:a.length,errorCount:c,warningCount:u},payload:a.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:a.length,errorCount:c,warningCount:u}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:p}}function kg(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>_g(r))}return[]}function _g(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}async function Tu(e){return te(e.queries||[],async t=>Fe({toolName:ge,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await aE(t);return ng(cu(t,rg(t,n)))}}),{toolName:ge,minQueryTimeoutMs:3e4},e)}async function aE(e){if(e.type==="documentSymbols")return Cu(e);if(e.type==="workspaceSymbol")return Pu(e);if(e.type==="diagnostic")return wu(e);let t=await Wh(e,ge);if(t.ok===!1){let u=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return ru(e,u)}let n=e.workspaceRoot??await sE(t.value.absolutePath);await iE(t.value.absolutePath,n)||Xe(t.value.uri,e.type);let o=await oE(n,t.value.absolutePath);o.ok===!1&&Xe(t.value.uri,e.type,o);let i=o.client,s=mg.has(e.type)?await fg(i,t.value,n):void 0,a=i.getReadiness?.(),c=await hg(e,t.value,i,s);return zh(c,a)}import{z as ps}from"zod";import{LspGetSemanticsQuerySchema as Ig}from"@octocodeai/octocode-core/schemas";var cE=_(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),uE=_(0,1e5).optional(),lE=["structured","compact"],Og={type:ps.enum(jh).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:ps.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:cE.optional(),orderHint:uE,depth:_(0,20).optional().describe("Traversal depth for call-hierarchy / type-hierarchy queries (0 = direct only)."),includeDeclaration:ps.boolean().optional().default(!0),page:K.describe("Result page for paginated reference/symbol lists (advance while pagination.hasMore)."),itemsPerPage:_(1,100).optional().describe("References/symbols returned per page (with page)."),contextLines:_(0,100).optional().describe("Lines of surrounding source shown around each result location."),format:ps.enum(lE).optional().default("structured")},pE=Z(Ig,Og),Yn=X(Ig,Og),dE=Yn,Xn=Y(pE,{maxQueries:5});import{existsSync as Fg}from"fs";import{delimiter as mE,dirname as fE,join as vg}from"path";function Dg(){return process.platform==="win32"?"npm.cmd":"npm"}function hE(){let e=fE(process.execPath);return vg(e,Dg())}function gE(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function yE(){let e=(process.env.PATH??"").split(mE).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...gE()])]}function Mg(){let e=hE();if(Fg(e))return{command:process.execPath,argsPrefix:[e]};let t=Dg();for(let n of yE()){let r=vg(n,t);if(Fg(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var RE=["view","search","ping","config","whoami"],SE=[...vn,...Ld];async function vz(e=1e4){let t=Mg();return Ad(t.command,[...t.argsPrefix,"--version"],e)}async function Ut(e,t,n={}){if(!RE.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Fi(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=Mg(),c=await Zt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:SE});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var qn="https://registry.npmjs.org",Lo=null;async function Ao(){if(Lo)return Lo;try{let e=await Ut("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 Lo=t,t}}catch{}return Lo=qn,qn}function bE(){Lo=null}async function CE(){try{let e=await Ao(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}var Gz=5;var Jn=new Map,Lu=5,ko=3e4;function _o(e){try{return new URL(e).host||e}catch{return e}}var Eu=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 Ng(e,t=Date.now()){let n=Jn.get(_o(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<ko)throw new Eu(_o(e),ko-r);n.state="half-open"}}function Au(e){let t=Jn.get(_o(e));t&&(t.failures=0,t.state="closed")}function Gg(e,t=Date.now()){let n=_o(e),r=Jn.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=Lu&&(r.state="open",r.openedAt=t)),Jn.set(n,r)}function Hz(){Jn.clear(),Lu=5,ko=3e4}function Bz(e){typeof e.failureThreshold=="number"&&(Lu=e.failureThreshold),typeof e.cooldownMs=="number"&&(ko=e.cooldownMs)}function Hg(e,t=Date.now()){let n=Jn.get(_o(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<ko:!1}import{z as E}from"zod";var ds=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()}),xE=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()}),Bg=E.looseObject({objects:E.array(xE),total:E.union([E.number(),E.string()]).optional()}),Ug=E.union([E.string(),E.boolean(),E.number(),E.null(),E.record(E.string(),E.unknown())]);var PE=6e4;function Qg(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function wE(e,t,n,r){e&&_t({limit_type:"primary",retry_after_seconds:Qg(r),api_method:t,api_url:n,provider:e})}function TE(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(nr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&tp(r),e.status===429&&wE(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function EE(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=Qg(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=PE,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:u,packageRegistry:l}=t,p=e;if(a){let R=e.includes("?")?"&":"?";p=`${e}${R}version=${encodeURIComponent(Yt)}`}let m={"User-Agent":`Octocode-MCP/${Yt}`,...i},d=globalThis.fetch;if(!d)throw new Error(nr.FETCH_NOT_AVAILABLE.message);Ng(p);let f,g=n+1;for(let R=1;R<=g;R++){if(c?.aborted)throw new Error("Request aborted");try{let h=await d(p,{method:s,headers:m,signal:c});if(!h.ok)throw TE(h,s,p,l,u);if(h.status===204)return Au(p),null;let y=await h.json();return Au(p),y}catch(h){let y=h;if(c?.aborted||h instanceof Error&&h.name==="AbortError")throw new Error("Request aborted");if(y&&y.retryable===!1)throw h;if(f=h instanceof Error?h:new Error(String(h)),R===g)break;let S=EE(R,r,o,y);await new Promise(C=>setTimeout(C,S))}}throw Gg(p),new Error(nr.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}function Qt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var LE="https://api.npmjs.org/downloads/point/last-week";function _e(e){return e===void 0?0:N(e)}async function ms(e){try{let t=`${LE}/${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:_e(n)}}catch{return{rawResponseChars:0}}}function $g(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 jg(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 AE(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function fs(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Qt(e.repository):(e.repository.url&&(r=Qt(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:AE(e),...o?{repositoryDirectory:o}:{},...$g(e.exports)?{exports:$g(e.exports)}:{},...jg(e.bin,e.name)?{bin:jg(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 kE(e){return typeof e.links?.repository=="string"?Qt(e.links.repository):typeof e.repository=="string"?Qt(e.repository):typeof e.repository?.url=="string"?Qt(e.repository.url):null}function zg(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:kE(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 ku(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function Wg(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}var _E=3e3;function _u(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}async function Iu(e){try{let t=await Ao(),n=ku(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=_e(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:_e(i)}}catch{return{rawResponseChars:0}}}async function gs(e,t,n){let[r,o]=await Promise.all([ms(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Iu(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 hs(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function IE(e,t){try{let n=await Ut("view",[e,"--json"],{timeout:_E});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,...hs(c)?{}:{errorDetail:c},rawResponseChars:_e(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=_e(o),s=ds.safeParse(o);return s.success?{pkg:fs(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,...hs(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function OE(e,t){try{let n=await Ao(),r=ku(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(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=_e(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=ds.safeParse(i);return a.success?{pkg:fs(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,...hs(r)?{}:{errorDetail:r},rawResponseChars:0}}}function FE(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Ou(e,t){let n=0,r;for(let o of FE(e)){let i;try{i=await st(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);hs(u)||(r=u);continue}if(n+=_e(i),!i||typeof i!="object")continue;let s=ds.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:fs(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function ys(e,t=!1){let[n,r]=await Promise.allSettled([IE(e,t),OE(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?gs(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function Vg(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await ys(e,t);if(!r){if(o){let s=_u(o);if(s&&n){let a=await Ou(e,t);if(a.pkg){let c=await gs(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 vE(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ut("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:_e(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=_e(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let l=[...a].sort((f,g)=>{let R=f?.score?.final??0;return(g?.score?.final??0)-R}).slice(r,r+t),p=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 R=await ys(g.name,!0);if(R.pkg)return R}return{pkg:zg(g),rawResponseChars:0}})),m=p.map(f=>f?.pkg).filter(f=>!!f),d=p.reduce((f,g)=>f+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+d}}async function DE(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${qn}/-/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:`Could not reach the npm search API (${f instanceof Error?f.message:String(f)}). The package may not exist, or the registry search endpoint is unavailable.`,hints:['Verify the exact package name / scope (e.g. "@scope/name")',"For an exact known name, query it directly instead of a keyword search","Ensure the npm registry is accessible from this environment"]}}let a=_e(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Bg.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 R=f.score?.final??0;return(g.score?.final??0)-R}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),p=await Promise.all(l.map(async f=>{if(n){let g=await ys(f.name,!0);if(g.pkg)return g}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?Qt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=p.map(f=>f.pkg).filter(f=>!!f),d=p.reduce((f,g)=>f+g.rawResponseChars,0);return{packages:m,totalFound:Wg(c.data.total,m.length),rawResponseChars:a+d}}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 Fu(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:_e(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:_e(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?Qt(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:_e(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function vu(e,t,n,r=0){try{let o=await vE(e,t,n,r);if(!("error"in o))return o}catch{}return DE(e,t,n,r)}async function Du(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}):ms(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Iu(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}function un(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Kg(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function Mu(e,t,n,r=0){let o=ce("npm-search",{name:e,limit:t,metadata:n,from:r});return he(o,async()=>{if(Hg(qn)){if(r===0&&t===1&&un(e)){let l=await Ou(e,n);if(l.pkg){let p=await gs(e,l.pkg,l.rawResponseChars);return{packages:p.pkg?[p.pkg]:[],totalFound:p.pkg?1:0,rawResponseChars:p.rawResponseChars}}}let u=await Fu(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&&un(e)){let u=await Vg(e,n,t===1);if("error"in u){if(!_u(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await vu(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Du(s);let a=Kg(e);if(a!==e){let u=await vu(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return Du(u)}let c=await Fu(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 Yg(e){try{let t=await Ut("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=Ug.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 Xg(e){let t=un(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Mu(e.name,n,!0,r)}function Nu(e){if(e===void 0)return;let n=(Array.isArray(e)?e.join(" "):e).trim();return n.length>0?n:void 0}var ME=/\b(?:404|e404)\b|not\s+found|no\s+such\s+package|does\s+not\s+exist/i;function Gu(e){return ME.test(e)}function NE(e){return"error"in e}function Rs(e){return"npmUrl"in e}function GE(e){return Rs(e)&&e.path?e.path:e.name}function HE(e){return Rs(e)?e.repoUrl:e.repository}function BE(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}var UE={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function QE(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=s=>s.replace(/\.git$/,""),r=t.match(/^(github|gitlab|bitbucket):(.+)$/i);if(r&&r[1]&&r[2]){let s=UE[r[1].toLowerCase()];return n(`https://${s}/${r[2]}`)}let o=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(o&&o[1]&&o[2])return n(`https://${o[1]}/${o[2]}`);let i=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(i&&i[1]){let s=i[1].replace(/^[^@/]+@/,"");return n(`https://${s}`)}return n(t)}function Hu(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 qg(e,t){let n=Hu(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghListReleases",query:{owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags (requires ENABLE_RELEASES)"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function $E(e){let t=GE(e),n=QE(HE(e)),r={name:t};Rs(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=BE(Rs(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=qg(n,o);return i&&(r.next=i),r.version&&Hu(n)&&(r.warnings=[`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`]),r}function jE(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=Hu(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:qg(i.repository,i.repositoryDirectory)});let{repository:u,repositoryDirectory:l,next:p,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function zE(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,u=s&&o>=a?o+1:a;return{currentPage:o,totalPages:u,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function Jg(e){return te(e.queries,async t=>{try{let n=t.packageName??Nu(t.keywords);if(!n)return F("Provide a packageName or keywords for package search",t);let r=await Xg({name:n,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(NE(r)){if(Gu(r.error)){let p=un(n);return se(t,{packages:[],hints:[p?`No package published under the exact name "${n}". Check the spelling, and try the scoped (@scope/name) vs unscoped form.`:`No packages matched "${n}". Try different or fewer keywords, or search by an exact package name.`]},!1,x.PACKAGE_SEARCH,{rawResponse:r})}return F(r.error,t,{rawResponse:r})}let o=r.packages,i=o.map($E),s=i.length>0,a=o.length>1||r.totalFound>1,c=zE(t,r.totalFound,i.length,a),l={...jE(i),pagination:c};return se(t,l,s,x.PACKAGE_SEARCH,{rawResponse:r.rawResponseChars??r})}catch(n){return F(n,t,{toolName:x.PACKAGE_SEARCH})}},{toolName:x.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{z as Ss}from"zod";import{NpmPackageQuerySchema as Zg}from"@octocodeai/octocode-core/schemas";var ey={page:K,keywords:Ss.union([Ss.string(),Ss.array(Ss.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},Io=X(Zg,ey),Oo=Y(Z(Zg,ey,{strict:!0}),{maxQueries:5});var bs={hasTool(e){return Ca(e)},getDescription(e){return ba[e]??""},getToolName(e){return x[e]??String(e)}};var Bu=(e,t=bs)=>t.getDescription(e);function WE(e,t){return t.getToolName(e)}function Pe(e,t,n){let r=WE(t,e);return{...n,name:r,description:Bu(r,e)}}var at={security:"remote",requiresServerRuntime:!0,requiresProviders:!0};function VE(e=bs){let t=Pe(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Vr,inputSchema:Kr,executionFn:Pm,...at}}),n=Pe(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:en,inputSchema:zr,executionFn:gm,...at}}),r=Pe(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:ao,inputSchema:co,executionFn:Pf,...at}}),o=Pe(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:io,inputSchema:so,executionFn:Sf,...at}}),i=Pe(e,"GITHUB_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Zr,inputSchema:eo,executionFn:tf,...at}}),s=Pe(e,"GITHUB_ISSUES",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:to,inputSchema:no,executionFn:nf,...at}}),a=Pe(e,"GITHUB_COMMITS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:ro,inputSchema:oo,executionFn:rf,...at}}),c=Pe(e,"GITHUB_RELEASES",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:Un,inputSchema:Qn,executionFn:of,...at}}),u=Pe(e,"GITHUB_DISCUSSIONS",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:$n,inputSchema:jn,executionFn:uf,...at}}),l=Pe(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Io,inputSchema:Oo,executionFn:Jg,security:"remote",requiresServerRuntime:!0}}),p=Pe(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Nn,inputSchema:jr,executionFn:Kd,...at}}),m=Pe(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:ht,inputSchema:Ro,executionFn:Oh,security:"basic"}}),d=Pe(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:cn,inputSchema:Po,executionFn:$h,security:"basic"}}),f=Pe(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:on,inputSchema:lo,executionFn:Jf,security:"basic"}}),g=Pe(e,"LOCAL_FIND_DEAD_CODE",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:sn,inputSchema:fo,executionFn:dh,security:"basic"}}),R=Pe(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:rn,inputSchema:uo,executionFn:Wf,security:"basic"}}),h={name:ge,description:Bu(ge,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Yn,inputSchema:Xn,executionFn:Tu,security:"basic",requiresServerRuntime:!0}},y=[t,n,r,o,i,s,a,...ho()?[c]:[],...Wn()?[u]:[],l,p,m,d,f,g,R,h];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_PULL_REQUESTS:i,GITHUB_ISSUES:s,GITHUB_COMMITS:a,GITHUB_RELEASES:c,GITHUB_DISCUSSIONS:u,PACKAGE_SEARCH:l,GITHUB_CLONE_REPO:p,LOCAL_RIPGREP:m,LOCAL_VIEW_STRUCTURE:d,LOCAL_FIND_FILES:f,LOCAL_FIND_DEAD_CODE:g,LOCAL_FETCH_CONTENT:R,LSP_GET_SEMANTIC_CONTENT:h,ALL_TOOLS:y}}var Ce=VE(),TV=Ce.GITHUB_SEARCH_CODE,EV=Ce.GITHUB_FETCH_CONTENT,LV=Ce.GITHUB_VIEW_REPO_STRUCTURE,AV=Ce.GITHUB_SEARCH_REPOSITORIES,kV=Ce.GITHUB_PULL_REQUESTS,_V=Ce.GITHUB_ISSUES,IV=Ce.GITHUB_COMMITS,OV=Ce.GITHUB_RELEASES,FV=Ce.GITHUB_DISCUSSIONS,vV=Ce.PACKAGE_SEARCH,DV=Ce.GITHUB_CLONE_REPO,MV=Ce.LOCAL_RIPGREP,NV=Ce.LOCAL_VIEW_STRUCTURE,GV=Ce.LOCAL_FIND_FILES,HV=Ce.LOCAL_FIND_DEAD_CODE,BV=Ce.LOCAL_FETCH_CONTENT,UV=Ce.LSP_GET_SEMANTIC_CONTENT,ty=Ce.ALL_TOOLS;import{completeMetadata as KE}from"@octocodeai/octocode-core";var Fo=null;function ny(){return Fo||(Fo=KE),Fo}async function jV(){return ny()}async function zV(){ny()}function WV(){return Fo}function VV(){Fo=null}var ry=["GitHub","Local Code","Package","Other"],oy=new Map([D.GITHUB_SEARCH_CODE,D.GITHUB_SEARCH_REPOSITORIES,D.GITHUB_PULL_REQUESTS,D.GITHUB_ISSUES,D.GITHUB_COMMITS,D.GITHUB_FETCH_CONTENT,D.GITHUB_VIEW_REPO_STRUCTURE,D.GITHUB_CLONE_REPO,D.LOCAL_RIPGREP,D.LOCAL_FIND_FILES,D.LOCAL_FIND_DEAD_CODE,D.LOCAL_FETCH_CONTENT,D.LOCAL_VIEW_STRUCTURE,ge,D.PACKAGE_SEARCH,...Wn()?[D.GITHUB_DISCUSSIONS]:[]].map((e,t)=>[e,t])),qe=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},YE=["id","mainResearchGoal","researchGoal","reasoning"],vo=new Set([...YE]),XE=[{name:D.GITHUB_SEARCH_CODE,schema:Vr,inputSchema:Kr},{name:D.GITHUB_FETCH_CONTENT,schema:en,inputSchema:zr},{name:D.GITHUB_VIEW_REPO_STRUCTURE,schema:ao,inputSchema:co},{name:D.GITHUB_SEARCH_REPOSITORIES,schema:io,inputSchema:so},{name:D.GITHUB_PULL_REQUESTS,schema:Zr,inputSchema:eo},{name:D.GITHUB_ISSUES,schema:to,inputSchema:no},{name:D.GITHUB_COMMITS,schema:ro,inputSchema:oo},...ho()?[{name:D.GITHUB_RELEASES,schema:Un,inputSchema:Qn}]:[],...Wn()?[{name:D.GITHUB_DISCUSSIONS,schema:$n,inputSchema:jn}]:[],{name:D.PACKAGE_SEARCH,schema:Io,inputSchema:Oo},{name:D.GITHUB_CLONE_REPO,schema:Nn,inputSchema:jr},{name:D.LOCAL_RIPGREP,schema:ht,inputSchema:Ro},{name:D.LOCAL_VIEW_STRUCTURE,schema:cn,inputSchema:Po},{name:D.LOCAL_FIND_FILES,schema:on,inputSchema:lo},{name:D.LOCAL_FIND_DEAD_CODE,schema:sn,inputSchema:fo},{name:D.LOCAL_FETCH_CONTENT,schema:rn,inputSchema:uo},{name:ge,schema:Yn,inputSchema:Xn}],qE=[...ho()?[]:[{name:D.GITHUB_RELEASES,schema:Un,inputSchema:Qn,disabled:{envVar:"ENABLE_RELEASES"}}],...Wn()?[]:[{name:D.GITHUB_DISCUSSIONS,schema:$n,inputSchema:jn,disabled:{envVar:"ENABLE_DISCUSSIONS"}}]];function $t(e){return XE.find(t=>t.name===e)??qE.find(t=>t.name===e)}function Zn(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===D.PACKAGE_SEARCH?"Package":"Other"}function JV(e){return[...e].sort((t,n)=>{let r=ry.indexOf(Zn(t)),o=ry.indexOf(Zn(n));if(r!==o)return r-o;let i=oy.get(t)??Number.MAX_SAFE_INTEGER,s=oy.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}import{z as iy}from"zod";var JE=["id","researchGoal","reasoning"];function n2(e){let t=$t(e);if(!t)return"{}";try{return JSON.stringify(iy.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(iy.toJSONSchema(t.schema,{io:"input"}),null,2)}}function r2(e){return JSON.stringify(e??{},null,2)}function o2(e){let t=Zn(e),n=[...JE];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function i2(e,t){return t?.tools?.[e]?.description??e}import{z as ZE}from"zod";function Cs(e){let t=$t(e);if(!t)return[];let n=ZE.toJSONSchema(t.schema,{io:"input"});if(!er(n))return[];let r=St(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!vo.has(i)&&!$u(r[i])):[]);return Qu(r,o)}function eL(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 Uu(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=er(e.items)?e.items:void 0;return`array<${n?Uu(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(er).map(Uu).filter(r=>r!=="value");if(n.length>0)return[...new Set(n)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Qu(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&vo.has(o))continue;let s=er(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Uu(s),constraints:eL(s),description:typeof s.description=="string"?s.description:void 0}),St(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!$u(s.properties?.[l]):!1):[]);r.push(...Qu(s.properties,u,a))}let c=s.type==="array"&&er(s.items)?s.items:void 0;if(c&&St(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!$u(c.properties?.[l]):!1):[]);r.push(...Qu(c.properties,u,a))}}return r}function ay(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[sy(e,n)]}return sy(e,t)}function sy(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return e}}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e){return St(e)}function $u(e){return er(e)&&"default"in e}function cy(e){return e===D.GITHUB_PULL_REQUESTS?[{label:"PR search (list)",query:{owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"PR detail (diffs + reviews)",query:{owner:"sindresorhus",repo:"slugify",prNumber:1,content:{comments:{discussion:!0},reviews:!0,patches:{mode:"all"}}}}]:e===D.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===D.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===D.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===D.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===D.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===D.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===D.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===D.LOCAL_FIND_DEAD_CODE?[{label:"default entrypoints (package.json + tests)",query:{path:"packages/octocode-tools-core",itemsPerPage:20}},{label:"explicit entrypoints",query:{path:"packages/octocode-tools-core",entrypoints:["src/index.ts","src/direct.ts"],includeTests:!1}}]:e===D.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,entryType:"f",itemsPerPage:100}}]:e===D.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===D.GITHUB_COMMITS?[{label:"file history (bounded window)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",since:"6m",itemsPerPage:10}},{label:"compare two refs (base...head)",query:{owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===D.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{packageName:"schema validation",page:1}}]:e===ge?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function uy(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function tL(e){let t=cy(e);if(t.length>0)return t.map(r=>({...r,command:uy(e,r.query)}));let n=nL(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:uy(e,n)}]}function g2(e){return tL(e)[0]?.query??{}}function nL(e){if(!$t(e))return{};let t=Cs(e),n=t.filter(i=>!i.name.includes(".")),r=rL(n),o={};for(let i of r)o[i.name]=ay(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}var ly=4,ju=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),py=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function rL(e){let t=e.filter(i=>i.required),n=new Map;for(let i of t)n.set(i.name,i);let r=e.filter(i=>!i.required&&oL(i)).sort(iL),o=Math.max(ly,t.length);for(let i of r){if(n.size>=o)break;n.set(i.name,i)}return n.size>0?[...n.values()]:e.filter(i=>!py.has(i.name)).filter(i=>i.type!=="boolean").slice(0,ly)}function oL(e){return py.has(e.name)||e.type==="boolean"?!1:sL(e)?ju.has(e.name):!0}function iL(e,t){let n=ju.get(e.name)??Number.MAX_SAFE_INTEGER,r=ju.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function sL(e){return e.constraints?.includes("default ")===!0}function b2(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 aL(e,r,n)}function aL(e,t,n={}){let r=uL(e,t,n),o=$t(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.",cL(i.error));return i.data}function cL(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function uL(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(St(t)&&Array.isArray(t.queries))r=t.queries;else if(St(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=St(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>lL(e,a,yL(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function lL(e,t,n,r){let o={...n},i=Zn(e),s=r.sourceLabel??"direct tool execution",a=pL(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 pL(e,t){return`Execute ${e} via ${t}`}function dL(e,t){let n=e.length+1,r=t.length+1,o=Array.from({length:n*r},()=>0);for(let i=0;i<n;i++)o[i*r]=i;for(let i=0;i<r;i++)o[i]=i;for(let i=1;i<n;i++)for(let s=1;s<r;s++){let a=e[i-1]===t[s-1]?0:1;o[i*r+s]=Math.min(o[(i-1)*r+s]+1,o[i*r+s-1]+1,o[(i-1)*r+s-1]+a)}return o[n*r-1]}function mL(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),u=dL(n,c);if(c.includes(n)||n.includes(c)){u<o&&(r=a,o=u);continue}if(n.length<3)continue;let l=Math.max(2,Math.floor(a.length/3));u<=l&&u<s&&(i=a,s=u)}return r??i}var fL=new Set(["none","standard","symbols"]),hL={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"searchText",keywords:"searchText",language:"langType"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:{field:"minify",map:e=>{if(e===!0)return"standard";if(e===!1)return"none";if(typeof e=="string"&&fL.has(e))return e}}},ghSearchPullRequests:{merged:{field:"state",map:e=>e===!0?"merged":void 0}},ghSearchCommits:{filePath:"path"},localFindFiles:{maxResults:"limit"}};function gL(e,t){let n=hL[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n)){if(!(o in t))continue;let s=typeof i=="string"?i:i.field;if(s in t){r??={...t},delete r[o];continue}let a=typeof i=="string"?t[o]:i.map(t[o]);a!==void 0&&(r??={...t},r[s]=a,delete r[o])}return r??t}function yL(e,t,n,r={}){if(!St(t))throw new qe("Tool input must be a JSON object or an array of objects.");let o=gL(e,t),i=new Set([...Cs(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...vo]),s={},a=[];for(let[c,u]of Object.entries(o)){if(i.has(c)){s[c]=u;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(u=>{let l=mL(u,i);return l?`'${u}' \u2192 did you mean '${l}'?`:""}).filter(Boolean);throw new qe(`Unknown field(s): ${a.join(", ")}`,[...c,`Remove unknown field(s) from query ${n+1}: ${a.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return s}import{getConfigSync as kL}from"@octocodeai/config";import{ContentSanitizer as RL}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as SL}from"@octocodeai/config";var my="OCTOCODE_MCP_FULL_TEXT",bL="[content withheld: sanitization failed \u2014 retry the call; if this persists, report it]";function zu(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:Ve(t.structuredContent)}}catch{t={...t,structuredContent:{status:"error",code:"SANITIZATION_FAILED",error:"structuredContent withheld: sanitization failed \u2014 retry the call; if this persists, report it"},isError:!0}}return CL(t)?xL(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=RL.sanitizeContent(n.text);return{...n,text:r}}catch{return{...n,text:bL}}return n})}),t)}function CL(e){return SL()==="mcp"&&process.env[my]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function xL(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:PL(e.structuredContent)},...t]}}var dy=3;function PL(e){let t=["structuredContent available"];if(Do(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=TL(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;if(Do(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`),Array.isArray(e.results)&&e.results.length>0){let r=e.results.slice(0,dy).map(wL).filter(Boolean);if(r.length>0){let o=e.results.length-dy;t.push(`[${r.join(" \xB7 ")}${o>0?` \xB7 +${o} more`:""}]`)}}}return`${t.join(" \xB7 ")}. Read structuredContent for full data; if your client cannot read structuredContent, set ${my}=true.`}function wL(e){if(!Do(e))return"";let t=[];typeof e.id=="string"&&t.push(e.id),t.push(typeof e.status=="string"?e.status:"ok");let n=e.data;return Do(n)&&typeof n.path=="string"&&n.path&&t.push(n.path.split("/").slice(-2).join("/").slice(0,80)),t.join(" ")}function TL(e){let t=0,n=0;for(let r of e)Do(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Do(e){return typeof e=="object"&&e!==null}var EL="TOOL_CALLBACK_EXCEPTION";function Wu(e,t){let n=LL(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
67
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:EL,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return zu(r)}catch{return r}}function LL(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:AL(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 AL(e){try{return JSON.stringify(e)}catch{return}}var xs=null,Ps=null,_L=Zl;function IL(e){let t=e;return n=>t(n)}function OL(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:IL(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var FL=ty.map(OL);function vL(e){return FL.find(t=>t.name===e)}async function DL(e,t){let n=vL(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=ML(n,t);return await NL(n),GL(n),await HL(n,r)}catch(r){return Wu(n.name,r)}}function ML(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function NL(e){e.requiresServerRuntime&&(xs||(xs=_L().catch(t=>{throw xs=null,t})),await xs),e.requiresProviders&&(Ps||(Ps=Td().then(()=>{}).catch(t=>{throw Ps=null,t})),await Ps)}function GL(e){if(!e.isLocal&&!e.isClone)return;let t=kL();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function HL(e,t){try{let n=e.security==="remote"?await BL(e,t):await UL(e,t);return zu(n)}catch(n){return Wu(e.name,n)}}async function BL(e,t){return Vu(e.name,async(r,o)=>e.execute({...r,authInfo:o.authInfo,sessionId:o.sessionId,signal:o.signal}))(t,{})}async function UL(e,t){return Ku(e.execute,e.name)(t)}var $2={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};import{getConfigSync as fy}from"@octocodeai/config";function W2(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function V2(){try{return fy().local.enabled}catch{return!1}}function K2(){try{if(!fy().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}import{validateCommand as QL}from"@octocodeai/octocode-engine/commandValidator";async function J2(e,t=[],n={}){let r=QL(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Fi(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 Zt(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}}import{z as G}from"zod";var ws=G.object({text:G.string()}),$L=G.object({match:G.object({text:G.string()}).optional(),start:G.number(),end:G.number()}),jL=G.object({type:G.literal("match"),data:G.object({path:ws,lines:G.object({text:G.string()}),line_number:G.number(),absolute_offset:G.number(),submatches:G.array($L)})}),zL=G.object({type:G.literal("context"),data:G.object({path:ws,lines:G.object({text:G.string()}),line_number:G.number(),absolute_offset:G.number()})}),WL=G.object({type:G.literal("begin"),data:G.object({path:ws})}),VL=G.object({type:G.literal("end"),data:G.object({path:ws,stats:G.object({elapsed:G.object({human:G.string()}),searches:G.number(),searches_with_match:G.number()}).optional()})}),KL=G.object({type:G.literal("summary"),data:G.object({elapsed_total:G.object({human:G.string()}),stats:G.object({elapsed:G.object({human:G.string()}),searches:G.number(),searches_with_match:G.number(),bytes_searched:G.number(),bytes_printed:G.number(),matched_lines:G.number(),matches:G.number()})})}),tK=G.discriminatedUnion("type",[jL,zL,WL,VL,KL]);import{securityRegistry as qY,ContentSanitizer as JY}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as eX}from"@octocodeai/octocode-engine/mask";import{configureSecurity as nX}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as lX}from"@octocodeai/octocode-core";import{z as dX}from"zod";export{eA as ALL_ERROR_CODES,ty as ALL_TOOLS,_S as BASE_SCHEMA,jr as BulkCloneRepoLocalSchema,Xn as BulkLspGetSemanticsQuerySchema,Ts as CONFIG_ERRORS,Br as CORE_ALLOWED_ENV_VARS,lt as CREDENTIALS_FILE,Eu as CircuitOpenError,Nn as CloneRepoQueryLocalSchema,JY as ContentSanitizer,UB as DEFAULTS,Gz as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,Ju as DEFAULT_MATCH_SNIPPET_CHARS,bs as DEFAULT_TOOL_METADATA_GATEWAY,ba as DESCRIPTIONS,ZS as DIFF_PREVIEW_MAX_LINES,vo as DIRECT_TOOL_AUTO_FILLED_FIELDS,ry as DIRECT_TOOL_CATEGORIES,XE as DIRECT_TOOL_DEFINITIONS,qe as DirectToolInputError,z as ERROR_CODES,ye as ERROR_MESSAGES,nr as FETCH_ERRORS,Ct as FILE_OPERATION_ERRORS,zr as FileContentBulkQueryLocalSchema,ox as FileContentQueryBaseLocalSchema,en as FileContentQueryLocalSchema,DV as GITHUB_CLONE_REPO,IV as GITHUB_COMMITS,FV as GITHUB_DISCUSSIONS,EV as GITHUB_FETCH_CONTENT,qu as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,_V as GITHUB_ISSUES,kV as GITHUB_PULL_REQUESTS,OV as GITHUB_RELEASES,TV as GITHUB_SEARCH_CODE,me as GITHUB_SEARCH_DEFAULT_LIMIT,oe as GITHUB_SEARCH_MAX_LIMIT,qL as GITHUB_SEARCH_MAX_PAGES,AV as GITHUB_SEARCH_REPOSITORIES,Mt as GITHUB_STRUCTURE_DEFAULTS,JL as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Yu as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,LV as GITHUB_VIEW_REPO_STRUCTURE,iD as GenericToolResultRowSchema,Kr as GitHubCodeSearchBulkQueryLocalSchema,Vr as GitHubCodeSearchQueryLocalSchema,Li as GitHubProvider,sP as GitHubPullRequestSearchBulkQueryLocalSchema,Sc as GitHubPullRequestSearchQueryLocalSchema,so as GitHubReposSearchBulkQueryLocalSchema,io as GitHubReposSearchSingleQueryLocalSchema,co as GitHubViewRepoStructureBulkQueryLocalSchema,ao as GitHubViewRepoStructureQueryLocalSchema,mn as HOME,J_ as IGNORED_FILE_EXTENSIONS,Z_ as IGNORED_FILE_NAMES,eI as IGNORED_FOLDER_NAMES,et as KEY_FILE,Mo as LOCAL_DEFAULT_FILES_PER_PAGE,BV as LOCAL_FETCH_CONTENT,HV as LOCAL_FIND_DEAD_CODE,GV as LOCAL_FIND_FILES,bt as LOCAL_MAX_DEPTH,ln as LOCAL_MAX_FILES_PER_PAGE,Je as LOCAL_MAX_LIMIT,MV as LOCAL_RIPGREP,H as LOCAL_TOOL_ERROR_CODES,Zu as LOCAL_TOOL_ERROR_REGISTRY,NV as LOCAL_VIEW_STRUCTURE,ge as LSP_GET_SEMANTICS_TOOL_NAME,UV as LSP_GET_SEMANTIC_CONTENT,Qn as ListReleasesBulkLocalSchema,Un as ListReleasesLocalSchema,uo as LocalFetchContentBulkQuerySchema,rn as LocalFetchContentQuerySchema,fo as LocalFindDeadCodeBulkQuerySchema,sn as LocalFindDeadCodeQuerySchema,lo as LocalFindFilesBulkQuerySchema,on as LocalFindFilesQuerySchema,Ro as LocalRipgrepBulkQuerySchema,ht as LocalRipgrepQuerySchema,by as LocalToolErrorCategory,Po as LocalViewStructureBulkQuerySchema,cn as LocalViewStructureQuerySchema,Yn as LspGetSemanticsQueryDisplaySchema,dE as LspGetSemanticsQuerySchema,xR as MAX_BRANCH_CACHE_SIZE,pn as MAX_CHAR_LENGTH,Xu as MAX_CONTEXT_LINES,Wp as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,xr as MAX_DIRECTORY_FILES,Go as MAX_MATCH_CONTENT_LENGTH,No as MAX_PAGE_NUMBER,ci as MAX_TOTAL_SIZE,Xs as NETWORK_ERROR_PATTERNS,Ug as NpmDeprecationOutputSchema,Bg as NpmRegistrySearchSchema,Oo as NpmSearchBulkQueryLocalSchema,Io as NpmSearchQueryLocalSchema,ds as NpmViewResultSchema,As as OCTOCODE_DIR,Ie as OCTOCODE_HOME,ql as OctocodeConfigSchema,gR as OctokitWithThrottling,vV as PACKAGE_SEARCH,rr as PROMISE_ERRORS,Rd as PROVIDER_CAPABILITIES,Ld as PROXY_ENV_VARS,Ne as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,ct as PR_CONTENT_MAX_ITEMS_PER_PAGE,ac as ProviderInitializationError,ii as RATE_LIMIT_CONFIG,qs as RATE_LIMIT_PATTERNS,xt as REPOSITORY_ERRORS,Gt as RESOURCE_LIMITS,tK as RipgrepJsonMessageSchema,Ee as SEARCH_ERRORS,jh as SEMANTIC_CONTENT_TYPES,yD as SENSITIVE_ENV_VARS,Vt as SESSION_FILE,Ry as STARTUP_ERRORS,D as STATIC_TOOL_NAMES,Kt as STATS_FILE,lp as STATUS_TO_ERROR_CODE,oo as SearchCommitsBulkLocalSchema,ro as SearchCommitsLocalSchema,jn as SearchDiscussionsBulkLocalSchema,$n as SearchDiscussionsLocalSchema,no as SearchIssuesBulkLocalSchema,to as SearchIssuesLocalSchema,eo as SearchPullRequestsBulkLocalSchema,Zr as SearchPullRequestsLocalSchema,$2 as StatusEmojis,vn as TOOLING_ALLOWED_ENV_VARS,Sy as TOOL_ERRORS,yy as TOOL_METADATA_ERRORS,x as TOOL_NAMES,xe as ToolError,Le as ToolErrors,tr as VALIDATION_ERRORS,Kg as _packageNameToSearchKeywords,VV as _resetMetadataState,bE as _resetNpmRegistryUrlCache,Xl as _resetSessionState,Wk as _resetTokenResolvers,zk as _setTokenResolvers,gP as applyConfiguredAllowedRoots,ka as applyContentPagination,Gh as applyEntryFilters,pc as applyExactMatchRanking,gi as applyPagination,vr as applyPartialContentFilter,ld as applyStructurePagination,Ng as assertCircuitAvailable,$ as attachRawResponseChars,NO as buildBlockBoundaryHint,Oi as buildChildProcessEnv,na as buildCodeSearchQuery,oF as buildDiffPreview,tL as buildDirectToolCommandPatterns,g2 as buildDirectToolExampleQuery,vP as buildEntryPaginationHints,ay as buildExampleValue,dc as buildGhSearchCodeFinalizer,Gb as buildGitHubPullRequestsSearchParams,hm as buildGithubFetchContentFinalizer,ca as buildIssueSearchQuery,Pc as buildMergedPagination,zE as buildPackagePagination,xc as buildPartialFailureWarnings,ub as buildPullRequestSearchCacheKey,ia as buildPullRequestSearchQuery,ra as buildRepoSearchQuery,Cc as buildResultPagination,sy as buildScalarExampleValue,Rh as buildSearchNextMap,ss as buildSearchResult,Wu as buildToolErrorResult,mo as buildWalkWarnings,sD as bulkOutputEnvelopeFields,WS as byteSlice,hi as byteToCharIndex,Vp as charToByteIndex,HB as checkLargeOutputSafety,vz as checkNpmAvailability,Yg as checkNpmDeprecation,CE as checkNpmRegistryReachable,Jc as checkRegexSafety,_ as clampedInt,Jt as cleanJsonObject,Vk as cleanup,H_ as clearAllCache,U_ as clearLSPToolCache,B_ as clearLocalToolCache,s_ as clearOctokitInstances,U0 as clearProviderCache,Q_ as clearRemoteAPICache,Od as cloneRepo,Qu as collectDisplayFields,Ui as collectFlatErrors,HC as commonDirPrefix,Zc as compactLocation,jE as compactPackageRepositories,gt as compactResolvedSymbol,ff as compareIsoDateDescending,lX as completeMetadata,Bd as computeQueryTimeout,Bz as configureCircuitBreaker,nX as configureSecurity,In as contextLinesField,_O as convertByteMatchToChar,rt as countLines,N as countSerializedChars,Oa as createBasePRTransformation,Ln as createCacheMeta,To as createCallItemKey,F as createErrorResult,mt as createGitHubProviderError,Ei as createGitHubProviderErrorFromResult,Be as createLazyProviderContext,Aa as createPaginationInfo,JC as createProviderExecutionContext,Y as createRelaxedBulkQuerySchema,Nt as createResponseFormat,W0 as createResult,Tj as createSafeRegExp,se as createSuccessResult,zo as decrypt,hl as deleteCredentials,Yl as deleteSession,eL as describeSchemaConstraints,Uu as describeSchemaType,W2 as detectEnvironment,jo as encrypt,ol as ensureClone,vt as ensureCloneParentDir,Qo as ensureHome,Pt as ensureOctocodeDir,wy as ensureRepos,Ls as ensureTmp,Ty as ensureTree,br as etagSoftCache,pi as evictExpiredClones,wn as evictExpiredTrees,te as executeBulkOperation,Kd as executeCloneRepo,DL as executeDirectTool,Wf as executeFetchContent,dh as executeFindDeadCode,Jf as executeFindFiles,Tu as executeLspGetSemantics,Ut as executeNpmCommand,ft as executeProviderOperation,Vd as executeProviderOperations,Oh as executeRipgrepSearch,Ch as executeRipgrepSearchInternal,$h as executeViewStructure,Nd as executeWithErrorIsolation,Fe as executeWithToolBoundary,Pf as exploreMultipleRepositoryStructures,xn as extractEtag,mi as extractMatchingLines,kf as fallbackOnBestEffortFailure,$f as fetchContent,Ra as fetchDirectoryContents,Gr as fetchDirectoryContentsRecursivelyAPI,Ea as fetchFileContentToDisk,_a as fetchFileTimestamp,qp as fetchGitHubFileContentAPI,BF as fetchGitHubPullRequestByNumberAPI,Qa as fetchGitHubPullRequestByNumberAPIInternal,sd as fetchHistory,gm as fetchMultipleGitHubFileContents,Ar as fetchRawGitHubFileContent,st as fetchWithRetries,Jp as filterPatch,hP as filterStructure,Sh as finalizeRipgrepResult,ph as findDeadCode,$t as findDirectToolDefinition,qf as findFiles,Ir as findNextBlockBoundary,Bl as flushSession,Ul as flushSessionSync,Nu as foldKeywords,cR as formatBytes,V0 as formatCallToolResultForOutput,uy as formatDirectToolCommandPattern,r2 as formatDirectToolMetadataSchemaText,n2 as formatDirectToolSchemaText,cL as formatDirectToolValidationIssues,zn as formatFileSize,Qi as formatFinalizedResponse,An as formatPRForResponse,$E as formatPackageData,su as gatherIncomingCallsRecursive,au as gatherOutgoingCallsRecursive,ce as generateCacheKey,Ev as generatePaginationHints,wi as generateStructurePaginationHints,Ws as getActiveProvider,Vs as getActiveProviderConfig,Tl as getAppDataPath,Al as getArchitecture,LO as getBulkDefaultCharLength,Kp as getByteLength,$_ as getCacheStats,RS as getCacheTTL,Pr as getCloneBaseDir,ha as getCloneDir,Wt as getCredentials,bl as getCredentialsFilePath,Ko as getCredentialsSync,rl as getDefaultOctocodeHome,Bu as getDescription,o2 as getDirectToolAutoFilledFields,Zn as getDirectToolCategory,i2 as getDirectToolDescription,Cs as getDirectToolDisplayFields,hr as getDirectorySizeBytes,fp as getExtension,Cd as getFileContent,Wo as getGhCliToken,zs as getGitHubToken,El as getLocalAppDataPath,K2 as getLspEnvironmentHint,SS as getMaxCacheSizeBytes,bS as getMaxCloneCount,WV as getMetadataOrNull,Ao as getNpmRegistryUrl,zt as getOctocodeDir,Q as getOctokit,Ql as getOrCreateSession,Dt as getOutputCharLimit,dp as getOwnerQualifier,Ll as getPlatformName,qa as getProvider,ne as getRawResponseChars,Nr as getRecursiveFetchFailureCount,Pd as getRepoStructure,iS as getReposBaseDir,gr as getServerConfig,$l as getSessionId,Cl as getToken,Yk as getTokenSource,xl as getTokenSync,Ds as getTokenWithRefresh,li as getTreeBaseDir,wr as getTreeDir,be as handleCatchError,V as handleGitHubAPIError,Ii as handleProviderError,Rl as hasCredentials,Sl as hasCredentialsSync,WN as hasExpensiveContentRequest,$u as hasSchemaDefault,Gx as hasValidCodeSearchParams,sp as hashGitHubToken,Mn as hoistSharedFields,$B as ignoreBestEffortFailure,zl as incrementErrors,ni as incrementGitHubCacheHits,ri as incrementGitHubCacheRateLimits,Vl as incrementPackageRegistryFailures,Wl as incrementRateLimitByProvider,ei as incrementRateLimits,jl as incrementToolCalls,ti as incrementToolCharSavings,Dw as inferLspSymbolName,Zl as initialize,Td as initializeProviders,zV as initializeToolMetadata,ar as invalidateCredentialsCache,mD as invokeCallbackSafely,En as isCacheHit,Op as isCacheValid,Hg as isCircuitOpen,ep as isCloneEnabled,Wn as isDiscussionsEnabled,un as isExactPackageName,Oe as isGitHubAPIError,Eb as isGitHubAPISuccess,er as isJsonSchemaObject,Ns as isLinux,Kk as isLocalEnabled,bQ as isLocalTool,Ms as isMac,_r as isMidBlockCut,nt as isNoResultsSearchError,Gu as isPackageNotFoundError,XC as isProviderError,vi as isProviderSuccess,St as isRecord,ir as isRefreshTokenExpired,ho as isReleasesEnabled,Lb as isRepository,ut as isTokenExpired,Es as isToolError,Ca as isToolInMetadata,cr as isWindows,On as lineNumberField,of as listMultipleGitHubReleases,gl as listStoredHosts,yl as listStoredHostsSync,jV as loadToolContent,uC as makeToolResultRowSchema,tm as mapCodeSearchProviderResult,em as mapCodeSearchToolQuery,am as mapFileContentProviderResult,sm as mapFileContentToolQuery,im as mapPullRequestProviderResultData,om as mapPullRequestToolQuery,rm as mapRepoSearchProviderRepositories,nm as mapRepoSearchToolQuery,cm as mapRepoStructureProviderResult,cc as mapRepoStructureToolQuery,eX as maskSensitiveData,Fr as normalizeOwnerRepo,Em as normalizePullRequestContentRequest,QE as normalizeRepoUrl,Cn as normalizeResponseHeaders,Ic as paginateEntries,po as parseFileSize,Re as parseGitHubProjectId,_n as parseHasMore,we as paths,bh as preflightValidateRipgrepPattern,aL as prepareDirectToolInput,b2 as prepareDirectToolInputFromJsonText,Xp as processFileContentAPI,Di as providerSupports,yp as rateLimitWarning,ga as readCacheMeta,pt as readCredentialsStore,Rp as recomputeMatchPositions,Gg as recordCircuitFailure,Au as recordCircuitSuccess,tp as recordPackageRegistryFailure,_t as recordRateLimit,or as redactPath,Pl as refreshAuthToken,Dn as relativizeResultPaths,K as relaxedPageNumberField,di as removeCloneDir,Hz as resetCircuitBreaker,Kl as resetSessionStats,Is as resetTokenResolution,fe as resolveCacheAuthFingerprint,Ae as resolveDefaultBranch,eu as resolveFileAnchor,Qr as resolveQueryId,Wh as resolveSymbolAnchor,Os as resolveToken,Tt as resolveTokenFull,Fs as resolveTokenWithRefresh,$r as resolveUniqueQueryIds,Ed as responseEnvelopeFields,J2 as safeExec,ke as safeParseOrError,zu as sanitizeCallToolResult,Ve as sanitizeStructuredContent,Sd as searchCode,as as searchContentRipgrep,bp as searchGitHubCodeAPI,id as searchGitHubPullRequestsAPI,ud as searchGitHubReposAPI,Pm as searchMultipleGitHubCode,rf as searchMultipleGitHubCommits,uf as searchMultipleGitHubDiscussions,nf as searchMultipleGitHubIssues,Jr as searchMultipleGitHubPullRequests,tf as searchMultipleGitHubPullRequestsSplit,Sf as searchMultipleGitHubRepos,Mu as searchNpmPackage,Xg as searchPackage,Jg as searchPackages,xd as searchPullRequests,bd as searchRepos,qY as securityRegistry,FO as serializeForPagination,Om as shapePullRequestForContent,Fa as shouldEnrichPullRequestFromSearch,Cr as shouldIgnoreDir,bn as shouldIgnoreFile,V2 as shouldUseMCPLsp,ua as shouldUseSearchForIssues,sa as shouldUseSearchForPRs,vO as sliceByCharRespectLines,La as sliceContent,yi as snapToSemanticBoundary,JV as sortDirectToolNames,Ad as spawnCheckSuccess,PD as spawnCollectStdout,Zt as spawnWithTimeout,kr as splitLines,LI as startCacheGC,AI as stopCacheGC,vs as storeCredentials,_c as summarizeEntries,Bh as toEntryObject,Hh as toGroupedLists,el as toToolError,Ib as transformCodeSearchResult,vb as transformFileContentResult,Dr as transformPullRequestItemFromREST,Ua as transformPullRequestItemFromSearch,Nb as transformPullRequestResult,Ob as transformRepoSearchResult,jb as transformRepoStructureResult,Zp as trimDiffContext,ix as truncateSnippetChars,Ge as updateSessionStats,Yo as updateToken,Fi as validateArgs,ve as validateToolPath,Ya as viewGitHubRepositoryStructureAPI,Qh as viewStructure,Ku as withBasicSecurityValidation,he as withDataCache,ai as withDataCacheConditional,oD as withResponseEnvelope,Vu as withSecurityValidation,Tn as writeCacheMeta,dX as z};