@octocodeai/octocode-tools-core 17.0.1 → 17.0.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/direct.js +30 -30
- package/dist/index.js +33 -33
- package/dist/oql/index.js +30 -30
- package/dist/schema.js +2 -2
- package/dist/tools/github_fetch_content/scheme.d.ts +9 -11
- package/dist/tools/lsp/semantic_content/scheme.d.ts +13 -0
- package/dist/utils/file/toolHelpers.d.ts +12 -0
- package/package.json +41 -40
package/dist/index.js
CHANGED
|
@@ -5,48 +5,48 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
var
|
|
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}}}});import{redactPath as
|
|
10
|
-
`)}return null}async function $u(e=Sn){let t=await Pn({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function qu(e=Sn,t=Hr){let n=await Pn({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var Ma,ny=f(()=>{"use strict";zu();ju();Ma=null});async function Wu(e){let t=Mt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Jt();return r.credentials[t]=n,Qu(r),Zo(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Zn(e="github.com",t){let n=Mt(e);if(!t?.bypassCache){let i=Gg(n);if(i!==void 0)return i}let o=Jt().credentials[n]||null;return Hg(n,o),o}function Da(e="github.com"){let t=Mt(e);return Jt().credentials[t]||null}async function ry(e="github.com"){let t=Mt(e),n=!1,r=Jt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Xg():Qu(r),n=!0),Zo(t),{success:n,deletedFromFile:n}}async function oy(){let e=Jt();return Object.keys(e.credentials)}function iy(){let e=Jt();return Object.keys(e.credentials)}async function sy(e="github.com"){return await Zn(e)!==null}function ay(e="github.com"){return Da(e)!==null}async function Na(e,t){let n=await Zn(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Wu(n),!0):!1}function cy(){return Xt}async function ly(e="github.com"){let t=await Zn(e);return!t||!t.token||Yt(t)?null:t.token.token}function uy(e="github.com"){let t=Da(e);return!t||!t.token||Yt(t)?null:t.token.token}async function dy(e,t){return Bu({getCredentials:Zn,updateToken:Na},e,t)}async function Vu(e,t){return Zg({getCredentials:Zn,updateToken:Na},e,t)}var Ku=f(()=>{"use strict";Qg();Jg();ey();ny();Ea();ty({getTokenWithRefresh:Vu})});var Yu=f(()=>{"use strict";Ku();zu()});import jr from"node:os";import py from"node:path";function my(){return ti?process.env.APPDATA||py.join(Qr,"AppData","Roaming"):Qr}function fy(){return ti?process.env.LOCALAPPDATA||py.join(Qr,"AppData","Local"):Qr}function hy(){return Xu?"macOS":ti?"Windows":Ju?"Linux":jr.platform()}function gy(){return jr.arch()}var ti,Xu,Ju,Qr,yy=f(()=>{"use strict";ti=jr.platform()==="win32",Xu=jr.platform()==="darwin",Ju=jr.platform()==="linux",Qr=jr.homedir()});var Zu=f(()=>{"use strict";yy()});import{z as J}from"zod";var DO,NO,Ga,GO,Ha,by,Ry,Sy=f(()=>{"use strict";DO=J.object({rawChars:J.number(),responseChars:J.number(),savedChars:J.number(),calls:J.number()}),NO=J.object({hits:J.record(J.string(),J.number()).default({}),rateLimits:J.number().default(0)}),Ga=J.record(J.string(),J.number()).default({}),GO=J.object({toolCalls:J.number(),errors:J.number(),rateLimits:J.number(),rateLimitsByProvider:Ga,rawChars:J.number(),responseChars:J.number(),savedChars:J.number(),charSavingsCalls:J.number(),githubCacheHits:J.number(),githubCacheRateLimits:J.number(),packageRegistryFailures:J.number().default(0),packageRegistryFailuresByRegistry:Ga}),Ha=J.object({toolCalls:J.number(),errors:J.number(),rateLimits:J.number(),rateLimitsByProvider:Ga,charsSavedByTool:J.record(J.string(),DO).default({}),githubCacheHits:NO.default({hits:{},rateLimits:0}),packageRegistryFailures:Ga,totalUsage:GO.optional()}),by=J.object({version:J.literal(1),sessionId:J.string(),createdAt:J.string(),lastActiveAt:J.string(),stats:Ha.optional()}),Ry=J.object({version:J.literal(1),stats:Ha})});function Py(e){return Object.values(e).reduce((t,n)=>t+n,0)}function HO(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:Py(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Py(o),packageRegistryFailuresByRegistry:o}}function xn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:HO(t)}}function Cn(){return xn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var ed=f(()=>{"use strict"});import{existsSync as td,readFileSync as Cy,writeFileSync as QO,unlinkSync as jO,renameSync as BO}from"node:fs";import{isStatsEnabled as wy}from"@octocodeai/config";function xy(e,t){let n=`${e}.tmp`;QO(n,JSON.stringify(t,null,2),{mode:384}),BO(n,e)}function zO(e){let t=JSON.parse(e),n=Ry.safeParse(t);if(n.success)return xn(n.data.stats);let r=Ha.safeParse(t);return r.success?xn(r.data):null}function UO(){if(!td(tr))return Cn();try{let e=Cy(tr,"utf8");return zO(e)??Cn()}catch{return Cn()}}function Qa(e){Rn(),wy()&&xy(tr,{version:e.version,stats:xn(e.stats)});let{stats:t,...n}=e;xy(er,n)}function Ty(){if(!td(er))return null;try{let e=Cy(er,"utf8"),t=JSON.parse(e),n=by.safeParse(t);return n.success?{...n.data,stats:wy()?UO():Cn()}:null}catch{return null}}function Ey(){let e=!1;for(let t of[er,tr])if(td(t))try{jO(t),e=!0}catch{return!1}return e}var er,tr,ja=f(()=>{"use strict";Ku();ei();Sy();ed();er=Ue.session,tr=Ue.stats});function qO(){nd||(nd=!0,ni=()=>{ii()},ri=()=>{ii()},oi=()=>{ii()},process.on("exit",ni),process.on("SIGINT",ri),process.on("SIGTERM",oi))}function rd(){ni&&(process.removeListener("exit",ni),ni=null),ri&&(process.removeListener("SIGINT",ri),ri=null),oi&&(process.removeListener("SIGTERM",oi),oi=null),nd=!1}function WO(){Br||(Br=setInterval(()=>{wn&&Tt&&(Qa(Tt),wn=!1)},$O),Br.unref())}function od(){Br&&(clearInterval(Br),Br=null)}function si(){if(Tt)return Tt;let e=Ty();return e&&(Tt=e),e}function zr(e){Tt=e,wn=!0,qO(),WO()}function ai(){wn&&Tt&&(Qa(Tt),wn=!1)}function ii(){if(!Ba&&wn&&Tt){Ba=!0;try{Qa(Tt),wn=!1}catch{}finally{Ba=!1}}}function id(){Tt=null,wn=!1,Ba=!1}function ky(){id(),od(),rd()}var $O,Tt,wn,Br,nd,ni,ri,oi,Ba,Oy=f(()=>{"use strict";ja();$O=6e4,Tt=null,wn=!1,Br=null,nd=!1,ni=null,ri=null,oi=null,Ba=!1});import{randomUUID as VO}from"node:crypto";function YO(e){return xn(e)}function XO(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 vy(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 JO(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 Ay(){let e=new Date().toISOString();return{version:KO,sessionId:VO(),createdAt:e,lastActiveAt:e,stats:Cn()}}function Ly(){ai()}function _y(){ii()}function Fy(e){if(e?.forceNew){let r=Ay();return zr(r),ai(),r}let t=si();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return zr(r),ai(),r}let n=Ay();return zr(n),ai(),n}function Iy(){return si()?.sessionId??null}function ct(e){let t=si();if(!t)return{success:!1,session:null};let n=YO(t.stats),r=xn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:vy(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:XO(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:JO(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:vy(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return zr(o),{success:!0,session:o}}function My(e=1){return ct({toolCalls:e})}function Dy(e=1){return ct({errors:e})}function za(e=1){return ct({rateLimits:e})}function Ny(e,t=1){return ct({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function Ua(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return ct({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function $a(e,t=1){return ct({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function qa(e=1){return ct({githubCacheHits:{hits:{},rateLimits:e}})}function Gy(e,t=1){return ct({packageRegistryFailures:{[e]:t}})}function Hy(){let e=si();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Cn()};return zr(t),{success:!0,session:t}}function Qy(){return id(),od(),rd(),Ey()}function jy(){ky()}var KO,ci=f(()=>{"use strict";ja();ed();Oy();ja();KO=1});var sd=f(()=>{"use strict";ci();ci();ci();ci()});import{z as we}from"zod";var By,ad=f(()=>{"use strict";By=we.looseObject({$schema:we.string().optional(),version:we.number().int().optional(),github:we.record(we.string(),we.unknown()).optional(),local:we.record(we.string(),we.unknown()).optional(),tools:we.record(we.string(),we.unknown()).optional(),network:we.record(we.string(),we.unknown()).optional(),lsp:we.record(we.string(),we.unknown()).optional(),output:we.record(we.string(),we.unknown()).optional()})});import{setRuntimeSurface as Yj,invalidateConfigCache as Xj}from"@octocodeai/config";var zy=f(()=>{"use strict";ad()});import{existsSync as ZO,readdirSync as ev,lstatSync as tv}from"node:fs";import{join as nv}from"node:path";function li(e){if(!ZO(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=ev(r)}catch{continue}for(let i of o){let s=nv(r,i);try{let a=tv(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function rv(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}var cd=f(()=>{"use strict"});var Nt=f(()=>{"use strict";Yu();Zu();sd();zy();ei();cd()});var nr,Wa=f(()=>{nr="17.0.1"});import{getConfigSync as Uy,invalidateConfigCache as iv}from"@octocodeai/config";import{maskSensitiveData as sv}from"@octocodeai/octocode-engine/mask";function fB(e){e.resolveTokenFull&&(ld=e.resolveTokenFull)}function hB(){ld=Pn}async function ud(){try{let e=await ld({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:av.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function $y(){if(Tn!==null)return;if(Ur!==null)return Ur;let e=(async()=>{let t=Uy(),n=await ud();Tn={version:nr,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}})();Ur=e;try{await e}catch(t){throw Ur===e&&(Tn=null,Ur=null),t}}function gB(){Tn=null,Ur=null,iv()}function ui(){if(!Tn){let e=sv(Mu.NOT_INITIALIZED.message);throw new Error(e)}return Tn}async function dd(){return(await ud()).token}function yB(){return ui().enableLocal}function bB(){let e=ui();return e.enableLocal&&e.enableClone}async function RB(){return Tn!==null?Tn.tokenSource:(await ud()).source}function pd(){return"github"}function md(){let e=Uy().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var Tn,Ur,ld,av,$r=f(()=>{"use strict";Nt();Wa();st();Tn=null,Ur=null,ld=Pn;av=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});function En(e){(e.provider?ct({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):za(1)).session&&e.provider==="github"&&qa(1)}function qy(e){ct({packageRegistryFailures:{[e]:1}})}var di=f(()=>{"use strict";Nt()});import{Octokit as cv}from"octokit";import{throttling as lv}from"@octokit/plugin-throttling";import{createHash as uv}from"crypto";function Xy(e){return uv("sha256").update(e).digest("hex").substring(0,16)}async function Ge(e){let t=e?.token??await dd(),n=t?Xy(t):"anon",r=ui().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}function Jy(e){return Date.now()-e.createdAt>pv}function Zy(){for(let[e,t]of Gt.entries())Jy(t)&&Gt.delete(e);if(Gt.size>fd){let e=Gt.size-fd,t=0;for(let[n]of Gt){if(t>=e)break;Gt.delete(n),t++}}}function fv(){kn||(kn=setInterval(Zy,mv),typeof kn=="object"&&"unref"in kn&&kn.unref())}function Ky(e,t,n){En({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function gv(e){let t=ui(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${nr}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:hv(),log:r,...e&&{auth:e}};return new dv(o)}async function oe(e){fv();let t=e?.token??await dd(),n=t?Xy(t):"ANONYMOUS",r=Gt.get(n);if(r&&!Jy(r))return r.client;Gt.size>=fd&&Zy();let o=gv(t??void 0);return Gt.set(n,{client:o,createdAt:Date.now()}),o}async function Ye(e,t,n){let r=`${e}/${t}`,o=qr.get(r);if(o)return o;let i=await oe(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Yy(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}),Yy(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 Yy(e,t){if(qr.size>=yv){let n=qr.keys().next().value;n!==void 0&&qr.delete(n)}qr.set(e,t)}function AB(){Gt.clear(),qr.clear(),kn&&(clearInterval(kn),kn=null)}var dv,pv,fd,mv,Gt,kn,Wy,Vy,hv,yv,qr,Ae=f(()=>{"use strict";$r();$r();Wa();di();dv=cv.plugin(lv),pv=300*1e3,fd=50,mv=60*1e3;Gt=new Map,kn=null;Wy=3,Vy=60;hv=()=>({onRateLimit:(e,t,n,r)=>(Ky("primary",e,t),r<Wy&&e<Vy),onSecondaryRateLimit:(e,t,n,r)=>(Ky("secondary",e,t),r<Wy&&e<Vy)});yv=200,qr=new Map});import{createRequire as bv}from"node:module";function ae(){if(Va)return Va;try{return Va=Sv(),Va}catch(e){throw new hd(e)}}var Rv,eb,Va,Sv,hd,D,Le=f(()=>{"use strict";Rv=bv(import.meta.url),eb="@octocodeai/octocode-engine",Sv=()=>Rv(eb),hd=class extends Error{constructor(n){super(`Failed to load native dependency ${eb}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return ae().applyContentViewMinification(e,t)},applyMinification(e,t){return ae().applyMinification(e,t)},minifyContent(e,t){return ae().minifyContent(e,t)},minifyContentSync(e,t){return ae().minifyContentSync(e,t)},minifyContentResult(e,t){return ae().minifyContentResult(e,t)},minifyMarkdownCore(e){return ae().minifyMarkdownCore(e)},extractSignatures(e,t){return ae().extractSignatures(e,t)},extractJsSymbols(e,t){return ae().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ae().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ae().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return ae().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ae().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ae().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ae().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ae().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return ae().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return ae().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ae().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ae().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ae().parseRipgrepJson(e,t)},searchRipgrep(e){return ae().searchRipgrep(e)},queryFileSystem(e){return ae().queryFileSystem(e)},extractMatchingLines(e,t,n){return ae().extractMatchingLines(e,t,n)},filterPatch(e,t){return ae().filterPatch(e,t)},computeLineDiff(e,t){return ae().computeLineDiff(e,t)},charToByteOffset(e,t){return ae().charToByteOffset(e,t)},byteToCharOffset(e,t){return ae().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ae().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ae().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ae().SIGNATURES_ONLY_HINT}}});var K,Fe,tb,gd,yd,Ka,bd=f(()=>{"use strict";K={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"},Fe={[K.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."},[K.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."},[K.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},[K.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)."},[K.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."},[K.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."},[K.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."},[K.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."},[K.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."},[K.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},tb={401:K.AUTH_REQUIRED,403:K.FORBIDDEN_PERMISSIONS,404:K.NOT_FOUND,422:K.INVALID_REQUEST,502:K.SERVER_UNAVAILABLE,503:K.SERVER_UNAVAILABLE,504:K.SERVER_UNAVAILABLE},gd={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},yd={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ka={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as nb}from"octokit";function Ht(e){if(!(e instanceof nb)||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 Pv.some(o=>r.includes(o))})}function re(e){return e instanceof nb?xv(e):e instanceof Error?Av(e):{error:typeof e=="string"?e:Fe[K.UNKNOWN].message,type:"unknown"}}function xv(e){let{status:t,message:n,response:r}=e;if(t===403)return wv(n,r);if(t===429)return Cv(n,r);let o=tb[t];return o?vv(o,t):Wr(K.UNKNOWN,{error:n||Fe[K.UNKNOWN].message,status:t})}function Rd(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function Cv(e,t){let n=t?.headers,r=Rd(n,"retry-after"),o=Rd(n,"x-ratelimit-reset"),i=Rd(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ka.RESET_BUFFER_SECONDS,0):void 0);return En({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Wr(K.RATE_LIMIT_PRIMARY,{error:e||Fe[K.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Fe[K.RATE_LIMIT_PRIMARY].suggestion})}function wv(e,t){let n=t?.headers;if(yd.SECONDARY.test(e))return Tv(n);let r=n?.["x-ratelimit-remaining"],o=Ov(t);return r!==void 0&&String(r)==="0"||o?Ev(n):kv(n)}function Tv(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ka.SECONDARY_FALLBACK_SECONDS:t;return En({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Wr(K.RATE_LIMIT_SECONDARY,{error:Fe[K.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Fe[K.RATE_LIMIT_SECONDARY].suggestion})}function Ev(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)+Ka.RESET_BUFFER_SECONDS,0):void 0,i=r?Fe[K.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Fe[K.RATE_LIMIT_PRIMARY].messageWithoutTime;return En({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Wr(K.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Fe[K.RATE_LIMIT_PRIMARY].suggestion})}function kv(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Fe[K.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Lv(String(t),String(n))),Wr(K.FORBIDDEN_PERMISSIONS,{error:Fe[K.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Ov(e){return e?.data?.errors?.some(n=>n.type===yd.GRAPHQL_TYPE)??!1}function vv(e,t){let n=Fe[e];return Wr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function Av(e){return gd.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Fe[K.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Fe[K.NETWORK_CONNECTION_FAILED].suggestion}:gd.TIMEOUT.some(t=>e.message.includes(t))?{error:Fe[K.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Fe[K.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Wr(e,t){return{type:"http",...t}}function Lv(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?Fe[K.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Fe[K.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var Pv,tt=f(()=>{"use strict";bd();di();Pv=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function rb(e){return`user:${e}`}function Sd(e){return e.startsWith('"')||Fv.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var _v,Fv,Zt,pi=f(()=>{"use strict";_v=/[@/]/,Fv=/^[A-Za-z0-9_-]+$/;Zt=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(rb(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=_v.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.addSimpleFilter(t.interactions,"interactions"),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()}}});function Cd(e){return new Pd().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function wd(e){return new xd().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var Iv,Pd,xd,ob=f(()=>{"use strict";pi();Iv=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Pd=class extends Zt{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(Sd))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Iv):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}},xd=class extends Zt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Sd)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}}});function Ed(e){return new Td().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function kd(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Td,ib=f(()=>{"use strict";pi();Td=class extends Zt{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.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});function vd(e){return new Od().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ad(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.involves!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.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)}var Od,sb=f(()=>{"use strict";pi();Od=class extends Zt{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.addSimpleFilter(t.involves,"involves"),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}}});var rr=f(()=>{"use strict";pi();ob();ib();sb()});import Mv from"crypto";function Gv(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(Nv.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Te(e,t,n){let r=Ld(Gv(t)),o=n?`${n}:${r}`:r,i=Mv.createHash("sha256").update(o).digest("hex");return`${Dv}-${e}:${i}`}function Ld(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=>Ld(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Ld(i,t)}`}).join(",")}}`)}var Dv,Nv,ab=f(()=>{"use strict";Dv="v2",Nv=new Set([])});import Hv from"node-cache";function jv(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Bv(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function mi(e){let t=jv(e);if(!(!t||!Bv(t)))try{$a(t,1)}catch{}}function Ya(){let e=Date.now();for(let[t,n]of ft.entries())e-n.startedAt>Qv&&ft.delete(t)}function fi(e){return cb[e]||cb.default}function hi(e,t,n){try{return $e.set(e,t,n),Se.sets++,Se.totalKeys=$e.keys().length,!0}catch{try{let r=$e.keys();for(let o of r)$e.get(o);return $e.set(e,t,n),Se.sets++,Se.totalKeys=$e.keys().length,!0}catch{return!1}}}var Qv,$e,Se,cb,ft,Xa=f(()=>{"use strict";Nt();Qv=300*1e3,$e=new Hv({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Se={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},cb={"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},ft=new Map});async function He(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=$e.get(e);if(i!==void 0)return Se.hits++,mi(e),i}catch{}Ya();let r=ft.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Se.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=fi(l)}hi(e,i,a)}return i}finally{ft.delete(e)}})();return ft.set(e,{promise:o,startedAt:Date.now()}),o}var lb=f(()=>{"use strict";Xa()});import zv from"node-cache";async function Ja(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=$e.get(e);if(i!==void 0)return Se.hits++,mi(e),i}catch{}Ya();let r=ft.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:gi.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){Se.hits++,mi(e);let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=fi(u)}return hi(e,i.data,c),i.data}if(n.forceRefresh||Se.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=fi(u)}hi(e,s.value,c),gi.set(e,{data:s.value,etag:s.etag})}return s.value}finally{ft.delete(e)}})();return ft.set(e,{promise:o,startedAt:Date.now()}),o}var gi,_d=f(()=>{"use strict";Xa();gi=new zv({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1})});function lz(){$e.flushAll(),gi.flushAll(),ft.clear(),Se.hits=0,Se.misses=0,Se.sets=0,Se.totalKeys=0,Se.lastReset=new Date}function On(e){let t=$e.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||$e.del(r)>0&&n++}return n>0&&(Se.totalKeys=$e.keys().length),n}function uz(){return On("local-")}function dz(){return On("lsp-")}function pz(){let e=0;return e+=On("gh-api-"),e+=On("bb-api-"),e+=On("gh-repo-"),e+=On("bb-repo-"),e+=On("github-user"),e+=On("npm-search"),gi.flushAll(),e}function mz(){let e=Se.hits+Se.misses;return{...Se,hitRate:e>0?Se.hits/e*100:0,cacheSize:$e.keys().length}}var ub=f(()=>{"use strict";Xa();_d()});var lt=f(()=>{"use strict";ab();lb();_d();ub()});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as xz,DISCOVERY_IGNORED_FILE_NAMES as Cz,DISCOVERY_IGNORED_FOLDER_NAMES as wz,getDiscoveryExtension as db,shouldIgnoreDiscoveryDir as yi,shouldIgnoreDiscoveryFile as Vr}from"@octocodeai/octocode-engine/security";var Kr=f(()=>{"use strict"});function Q(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function mb(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function V(e,t){let n=typeof t=="number"?mb(t):Q(t);if(n===void 0)return e;try{Object.defineProperty(e,pb,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ue(e){if(!(typeof e!="object"||e===null))return mb(e[pb])}var pb,le=f(()=>{"use strict";pb=Symbol.for("octocode.rawResponseChars")});function bi(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 Yr(e){let t=bi(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}var or=f(()=>{"use strict"});import{ContentSanitizer as Uv}from"@octocodeai/octocode-engine/contentSanitizer";async function hb(e,t,n){let r=await Ge(t),o=Te("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 $v(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function $v(e,t){try{let n=await oe(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(b=>b&&b.trim()).length===0)return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let r=Cd(e);if(!r.trim())return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:fb,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 qv(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),h=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:h,...h?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:bi(a.headers),rawResponseChars:Q(a.data)}}catch(n){if(Ht(n)){let o=Math.min(typeof e.limit=="number"?e.limit:fb,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 re(n)}}async function qv(e,t){let n=Wv(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Vr(p.path)),c=0,l=0,u=await Promise.allSettled(a.map(async p=>{s.add(p.path);let h=[],g=await Promise.allSettled((p.text_matches||[]).map(async k=>{let E=k.fragment,_=Uv.sanitizeContent(E||"",p.path);E=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(w=>r.add(`${p.path}: ${w}`));try{let w=await D.minifyContent(E||"",p.path);E=w.content,w.failed?o=!0:w.type!=="failed"&&(h.push(w.type),i.push(w.type))}catch{o=!0}return{context:E||"",positions:k.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),y=g.filter(k=>k.status==="fulfilled").map(k=>k.value),b=g.filter(k=>k.status==="rejected").length;b>0&&(l+=b);let S=p,C=Array.from(new Set(h));return{path:p.path,matches:y,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...C.length>0&&{minificationType:C.join(",")}}})),d=u.filter(p=>p.status==="fulfilled").map(p=>p.value);c=u.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function Wv(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var fb,Fd=f(()=>{"use strict";Le();Ae();tt();rr();lt();Kr();st();le();or();ce();fb=30});import{readdirSync as Vv,statSync as gb}from"node:fs";import{join as Kv}from"node:path";function Dd(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function Rb(e){return Object.values(e).every(t=>t===0)}function Nd(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 Sb(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 Jv(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function Jv(e,t){try{let o=new URL(e);if(!Xv.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(),Yv);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 Pb(e,t){let n=[],r=0;function o(i){let s;try{s=Vv(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Kv(i,a);try{let l=gb(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function xb(e){try{return gb(e).size}catch{return 0}}var Ri,Za,Id,yb,Yv,bb,Md,Xv,ec=f(()=>{"use strict";Ri=50,Za=5*1024*1024,Id=300*1024,yb=5,Yv=1e4,bb=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"]),Md={maxDirectoryFiles:Ri,maxTotalSize:Za,maxFileSize:Id};Xv=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});import{join as tc}from"node:path";import{createHash as Cb}from"node:crypto";function Zv(e){return Si(e)}function Si(e){return tc(e,"tmp","clone")}function nc(e){return tc(e,"tmp","tree")}function eA(e){return e?`__sp_${Cb("sha256").update(e).digest("hex").substring(0,6)}`:""}function wb(e){if(!/[\\/]/.test(e))return e;let t=Cb("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function Gd(e,t,n,r,o){let i=`${wb(r)}${eA(o)}`;return tc(Si(e),t,n,i)}function Pi(e,t,n,r){return tc(nc(e),t,n,wb(r))}var Hd=f(()=>{"use strict"});import{existsSync as wi,readFileSync as tA,writeFileSync as nA,mkdirSync as rA,rmSync as Ci,readdirSync as oA,statSync as iA}from"node:fs";import{join as vn}from"node:path";function uA(e){return typeof e=="object"&&e!==null}function dA(e){if(!uA(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 Qd(e){let t=vn(e,Eb);if(!wi(t))return null;try{return dA(JSON.parse(tA(t,"utf-8")))}catch{return null}}function Zr(e,t){try{nA(vn(e,Eb),JSON.stringify(t,null,2),"utf-8")}catch{}}function kb(e){return Date.now()<new Date(e.expiresAt).getTime()}function eo(e){let t=Qd(e);return t?kb(t)?wi(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function pA(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return sA}function mA(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return cA}function fA(){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 lA}function to(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+pA()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function An(e){let t=vn(e,"..");try{wi(t)||rA(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 oc(e){try{wi(e)&&Ci(e,{recursive:!0,force:!0})}catch{}}function xi(e){try{return iA(e).isDirectory()}catch{return!1}}function ir(e){try{return oA(e)}catch{return[]}}function*Ob(e){for(let t of ir(e)){let n=vn(e,t);if(xi(n))for(let r of ir(n)){let o=vn(n,r);if(xi(o))for(let i of ir(o)){let s=vn(o,i);xi(s)&&(yield s)}}}}function Tb(e){for(let t of[...ir(e)]){let n=vn(e,t);if(xi(n)){for(let r of[...ir(n)]){let o=vn(n,r);if(xi(o)&&ir(o).length===0)try{Ci(o,{recursive:!0,force:!0})}catch{}}if(ir(n).length===0)try{Ci(n,{recursive:!0,force:!0})}catch{}}}}function hA(e){let t=0;for(let n of Ob(e))try{let r=Qd(n);(!r||!kb(r))&&(Ci(n,{recursive:!0,force:!0}),t++)}catch{}return t}function gA(e){let t=[];for(let n of Ob(e)){let r=Qd(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??li(n)})}return t}function yA(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{Ci(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function vb(e){if(!wi(e))return 0;let t=0;try{t+=hA(e)}catch{return t}Tb(e);let n=yA(gA(e),mA(),fA());return t+=n,n>0&&Tb(e),t}function rc(e){return vb(Si(e))}function Jr(e){return vb(nc(e))}function Kz(e){Xr||(rc(e),Jr(e),Xr=setInterval(()=>{rc(e),Jr(e)},aA),Xr.unref())}function Yz(){Xr&&(clearInterval(Xr),Xr=null)}var sA,aA,cA,lA,Eb,Xr,Ti=f(()=>{"use strict";Nt();Hd();Hd();sA=1440*60*1e3,aA=600*1e3,cA=2*1024*1024*1024,lA=50,Eb=".octocode-clone-meta.json",Xr=null});import{writeFileSync as bA,mkdirSync as Ab,existsSync as jd,rmSync as RA}from"node:fs";import{join as Lb,dirname as SA,resolve as _b,sep as Fb}from"node:path";async function Bd(e,t,n,r,o,i=!1){let s=Jn(),a=Pi(s,e,t,r),c=_b(Lb(a,n));if(!c.startsWith(a+Fb)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=eo(a);if(l.hit&&!i&&jd(c)){let A=Pb(c,a),W=Dd();return{localPath:c,repoRoot:a,files:A.files,fileCount:A.fileCount,totalSize:A.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:A.fileCount,eligibleFileCount:A.fileCount,savedFileCount:A.fileCount,skipped:W,limits:Md,warnings:Nd(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await oe(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await u.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 p=m,h=Dd(),g=[];for(let A of p){if(A.type!=="file"){h.nonFile+=1;continue}if(!A.download_url){h.missingDownloadUrl+=1;continue}if(A.size>Id){h.oversized+=1;continue}let W=db(A.name,{lowercase:!0,leadingDot:!0});if(bb.has(W)){h.binary+=1;continue}g.push(A)}h.fileLimit=Math.max(0,g.length-Ri);let y=g.slice(0,Ri),b=o?.token,S=await Sb(y,yb,b);h.fetchFailed=y.length-S.length;let C=0,k=[];for(let A=0;A<S.length;A+=1){let{entry:W,content:H}=S[A];if(C+H.length>Za){h.totalSizeLimit=S.length-A;break}C+=H.length,k.push({entry:W,content:H})}Jr(s),An(a),jd(c)&&RA(c,{recursive:!0,force:!0}),Ab(c,{recursive:!0,mode:448});let E=[];for(let{entry:A,content:W}of k){let H=_b(Lb(a,A.path));if(!H.startsWith(a+Fb)){h.pathTraversal+=1;continue}let Y=SA(H);jd(Y)||Ab(Y,{recursive:!0,mode:448}),bA(H,W,"utf-8"),E.push({path:A.path,size:W.length,type:"file"})}let _=to(e,t,r,"treeFetch",void 0,void 0,d);Zr(a,_);let w=Rb(h),G=w,M=h.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:C,complete:w,verified:G,...d?{commitSha:d}:{},...M?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:h,limits:Md,warnings:Nd(w,G),cached:!1,expiresAt:_.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}var Ib=f(()=>{"use strict";Nt();Ae();Ti();Kr();ec()});import{completeMetadata as zd}from"@octocodeai/octocode-core";var v,Ud=f(()=>{"use strict";v=new Proxy({},{get(e,t){return zd.toolNames[t]},ownKeys(){return Object.keys(zd.toolNames)},getOwnPropertyDescriptor(e,t){let n=zd.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as $d}from"@octocodeai/octocode-core";function ic(e=$d){if(qd&&e===$d)return qd;let t=e,n=t.tools?.localFindFiles;n?.description&&Mb.test(n.description)&&(t={...t,tools:{...t.tools,localFindFiles:{...n,description:n.description.replace(Mb,PA)}}});let r=t.tools?.ghHistoryResearch;return r?.description&&Db.test(r.description)&&(t={...t,tools:{...t.tools,ghHistoryResearch:{...r,description:r.description.replace(Db,xA)}}}),e===$d&&(qd=t),t}var Mb,PA,Db,xA,qd,Wd=f(()=>{"use strict";Mb=/Default excludeDir skips common generated\/vendor dirs; pass \[\] to search all\./,PA='Nothing is excluded by default \u2014 pass excludeDir (e.g. ["node_modules","dist","coverage"]) to prune build/vendor dirs.',Db=/type:"prs" searches PRs; add prNumber to read selected content\. type:"commits" reads owner\/repo\/path history\./,xA='type:"prs" searches PRs; add prNumber to read selected content. type:"commits" reads owner/repo/path history. type:"issues" searches or reads GitHub issues; add issueNumber to read a specific issue (body + comments). type:"releases" lists repo releases.',qd=null});var Vd,Kd=f(()=>{"use strict";Wd();Vd=new Proxy({},{get(e,t){return ic().tools[t]?.description??""}})});import{completeMetadata as CA}from"@octocodeai/octocode-core";function Yd(e){return Object.prototype.hasOwnProperty.call(CA.tools,e)}var Xd=f(()=>{"use strict"});import{completeMetadata as wA}from"@octocodeai/octocode-core";function Jd(){return wA.baseSchema}var TA,Zd=f(()=>{"use strict";TA=new Proxy({},{get(e,t){return Jd()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Jd())]))},getOwnPropertyDescriptor(e,t){let n=Jd();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var me=f(()=>{"use strict";Ud();Kd();Xd();Zd()});function ep(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 tp(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(p=>p.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>l.push(p.path)),l.length===0&&d.length>=3&&c.filter(h=>{let g=h.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(h=>l.push(h.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var Nb=f(()=>{"use strict"});import{RequestError as np}from"octokit";async function EA(e,t,n,r,o,i,s,a){let c=await Ye(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=re(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await tp(e,r,o,i,s||c);return m.length>0&&(u.hints=[...u.hints||[],...ep(i,m)]),{...u,...d&&{scopesSuggestion:d}}}async function kA(e,t,n,r,o,i){let s=re(t),a=await tp(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...ep(o,a)]),s}async function Gb(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:gn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:gn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:gn.DECODE_FAILED.message,type:"unknown",status:422}}}async function Hb(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"?Gb(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return re(i)}}async function OA(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 Ye(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(m=>m.name===a&&m.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await Hb(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return re(s)}}async function Ei(e,t,n={}){try{let r=await oe(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(p){if(p instanceof np&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof np&&p.status===404)if(a){let h=await EA(r,p,c,o,i,s,a,t);if("result"in h)l=h.result,u=h.actualBranch;else return h}else return await kA(r,p,o,i,s,a);else{if(p instanceof np&&p.status===413)return await OA(r,o,i,s,a||u,t);throw p}}let d=l.data,m=Yr(l.headers);if(Array.isArray(d))return{error:gn.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",h=d.size??0,g;if(p.length>0)g=await Gb(p,s);else if(h>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await Hb(r,o,i,d.sha,s);else return{error:gn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!u&&!a)try{u=await Ye(o,i,t)}catch{}return{data:{rawContent:g.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:Q(d),...m?{etag:m}:{}}}return{error:gn.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return re(r)}}var Qb=f(()=>{"use strict";Ae();tt();me();st();le();or();Nb()});var sc=f(()=>{"use strict";Qb()});import{writeFileSync as vA,mkdirSync as AA,existsSync as jb}from"node:fs";import{join as LA,dirname as _A,resolve as FA,sep as IA}from"node:path";async function rp(e,t,n,r,o,i=!1){let s=Jn(),a=Pi(s,e,t,r),c=FA(LA(a,n));if(!c.startsWith(a+IA)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=eo(a);if(!i&&l.hit&&jb(c))return{localPath:c,repoRoot:a,path:n,size:xb(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await Ei({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 u)||!u.data){let h="error"in u?u.error:void 0;throw new Error(h||`Failed to fetch ${e}/${t}/${n}`)}Jr(s),An(a);let d=_A(c);jb(d)||AA(d,{recursive:!0,mode:448}),vA(c,u.data.rawContent,"utf-8");let m=u.data.branch||r,p=to(e,t,m,"treeFetch");return Zr(a,p),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}var Bb=f(()=>{"use strict";Nt();sc();Ti();ec()});var op=f(()=>{"use strict";ec();Ib();Bb()});function ki(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Qt(e){return ki(e).length}var sr=f(()=>{"use strict"});function ac(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
11
|
-
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var
|
|
12
|
-
`)}function Ub(e,t){let n=zb(e,t);return n===null?null:n.map(qb)}function
|
|
8
|
+
var uO=Object.defineProperty;var f=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var dO=(e,t)=>{for(var n in t)uO(e,n,{get:t[n],enumerable:!0})};import{withSecurityValidation as pO,withBasicSecurityValidation as mO}from"@octocodeai/octocode-engine/security";function Og(e,t){let n=pO(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function vg(e,t){let n=mO(r=>e(r),t);return(r,o)=>n(r,o)}var Iu=f(()=>{"use strict"});var ve,he,bQ,RQ,Ag,Vt,Lg,_g,wa,Kt,Nr,Ta,Fg,Gr,Ig,Ea,Mg,ce=f(()=>{"use strict";ve=30,he=100,bQ=10,RQ=100,Ag=200,Vt=20,Lg=100,_g=20,wa=50,Kt=1e4,Nr=20,Ta=1e3,Fg=100,Gr=5e4,Ig=8e3,Ea=1e5,Mg=500});var Mu,qo,Wo,fO,gn,yn,Ke,hO,Vo,gO,PQ,st=f(()=>{"use strict";Mu={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},qo={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"}},Wo={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})`}},fO={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"}},gn={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}`}},yn={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"}},Ke={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}`}},hO={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}`}},Vo={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},gO={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}`}},PQ={...Mu,...qo,...Wo,...fO,...gn,...yn,...Ke,...hO,...Vo,...gO}});var q,yO,Dg,bn=f(()=>{"use strict";q={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"},yO=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(yO||{}),Dg={[q.PATH_VALIDATION_FAILED]:{code:q.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[q.FILE_ACCESS_FAILED]:{code:q.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[q.FILE_READ_FAILED]:{code:q.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[q.FILE_TOO_LARGE]:{code:q.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[q.BINARY_FILE_UNSUPPORTED]:{code:q.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[q.NO_MATCHES]:{code:q.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[q.OUTPUT_TOO_LARGE]:{code:q.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[q.COMMAND_NOT_AVAILABLE]:{code:q.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[q.COMMAND_EXECUTION_FAILED]:{code:q.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[q.COMMAND_TIMEOUT]:{code:q.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[q.TOOL_EXECUTION_FAILED]:{code:q.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[q.LSP_SERVER_UNAVAILABLE]:{code:q.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function Du(e){return e instanceof ze}function Ng(e,t=q.TOOL_EXECUTION_FAILED,n){if(Du(e))return e;if(e instanceof Error)return new ze(t,e.message,n,e);let r=String(e);return new ze(t,r,n)}var ze,Ko=f(()=>{"use strict";bn();ze=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Dg[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}}}});import{redactPath as Yo}from"@octocodeai/octocode-engine/pathUtils";var Nu=f(()=>{"use strict"});var at,Xo=f(()=>{"use strict";Ko();bn();Nu();at={pathValidationFailed:(e,t,n)=>new ze(q.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Yo(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Yo(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 ze(q.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new ze(q.FILE_READ_FAILED,`Failed to read file: ${Yo(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new ze(q.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new ze(q.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Yo(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new ze(q.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new ze(q.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new ze(q.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new ze(q.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});function Mt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function Yt(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 Jo(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var ka=f(()=>{"use strict"});function RO(e){let t=Mt(e),n=Zo.get(t);return!n||Date.now()-n.cachedAt>=bO?!1:n.credentials?!Yt(n.credentials):!0}function ei(e){e?Zo.delete(Mt(e)):Zo.clear()}function Gg(e){let t=Mt(e);if(RO(t))return Zo.get(t).credentials}function Hg(e,t){let n=Mt(e);Zo.set(n,{credentials:t,cachedAt:Date.now()})}var Zo,bO,Qg=f(()=>{"use strict";ka();Zo=new Map,bO=300*1e3});import{existsSync as Oa,mkdirSync as va}from"node:fs";import{join as wt}from"node:path";import{getOctocodeHome as SO}from"@octocodeai/config";function jg(){return SO(process.env)}function Jn(){return et}function La(){Oa(Ue.home)||va(Ue.home,{recursive:!0,mode:Aa})}function PO(){Bg()}function Gu(){La(),Oa(Ue.tmp)||va(Ue.tmp,{recursive:!0,mode:Aa})}function Bg(){Gu(),Oa(Ue.clone)||va(Ue.clone,{recursive:!0,mode:Aa})}function xO(){Gu(),Oa(Ue.tree)||va(Ue.tree,{recursive:!0,mode:Aa})}var Aa,et,Ue,ti=f(()=>{"use strict";Aa=448;et=jg(),Ue={home:et,config:wt(et,".octocoderc"),credentials:wt(et,"credentials.json"),key:wt(et,".key"),session:wt(et,"session.json"),stats:wt(et,"stats.json"),tmp:wt(et,"tmp"),clone:wt(et,"tmp","clone"),tree:wt(et,"tmp","tree"),repos:wt(et,"tmp","clone"),cliConfig:wt(et,"config.json"),lspConfig:wt(et,"lsp-servers.json")}});import{z as Ne}from"zod";var CO,wO,zg,Ug=f(()=>{"use strict";CO=Ne.object({token:Ne.string(),tokenType:Ne.literal("oauth"),scopes:Ne.array(Ne.string()).optional(),refreshToken:Ne.string().optional(),expiresAt:Ne.string().optional(),refreshTokenExpiresAt:Ne.string().optional()}),wO=Ne.object({hostname:Ne.string(),username:Ne.string(),token:CO,gitProtocol:Ne.enum(["ssh","https"]),createdAt:Ne.string(),updatedAt:Ne.string()}),zg=Ne.object({version:Ne.number(),credentials:Ne.record(Ne.string(),wO)})});import{existsSync as _a,readFileSync as qg,writeFileSync as Wg,unlinkSync as $g,statSync as TO,chmodSync as EO}from"node:fs";import{createCipheriv as kO,createDecipheriv as OO,randomBytes as Vg}from"node:crypto";function Rn(){La()}function Yg(){if(Rn(),_a(Dt))return TO(Dt).mode&511&63&&EO(Dt,384),Buffer.from(qg(Dt,"utf8"),"hex");let e=Vg(32);return Wg(Dt,e.toString("hex"),{mode:384}),e}function Fa(e){let t=Yg(),n=Vg(vO),r=kO(Kg,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 Ia(e){let t=Yg(),[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=OO(Kg,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function Jt(){if(Rn(),!_a(Xt))return{version:1,credentials:{}};try{let e=qg(Xt,"utf8"),t=Ia(e),n=JSON.parse(t),r=zg.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Qu(e){Rn();let t=Fa(JSON.stringify(e,null,2));Wg(Xt,t,{mode:384})}function Xg(){try{_a(Xt)&&$g(Xt),_a(Dt)&&$g(Dt)}catch{}}var Hu,Xt,Dt,Kg,vO,Jg=f(()=>{"use strict";ti();Ug();Hu=Ue.home,Xt=Ue.credentials,Dt=Ue.key,Kg="aes-256-gcm",vO=16});var Hr,Sn,ju=f(()=>{"use strict";Hr="178c6fc778ccc68e1d6a",Sn="github.com"});import{refreshToken as AO}from"@octokit/oauth-methods";import{request as LO}from"@octokit/request";function _O(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 FO(e){return e==="github.com"||e===Sn?"https://api.github.com":`https://${e}/api/v3`}async function Bu(e,t=Sn,n=Hr){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(Jo(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await AO({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:LO.defaults({baseUrl:FO(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?_O(o.message):"Token refresh failed"}}}async function Zg(e,t=Sn,n=Hr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!Yt(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Bu(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var ey=f(()=>{"use strict";ka();ju()});import{execFile as IO}from"child_process";function Ma(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=MO.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;IO("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var MO,zu=f(()=>{"use strict";MO=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});import{resolveEnvToken as DO}from"@octocodeai/config";function ty(e){Da=e}function Uu(){Da=null}function NO(){if(!Da)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Da}async function Pn(e){let t=e?.hostname??Sn,n=e?.clientId??Hr,r=e?.getGhCliToken??Ma,o=DO();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await NO().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 $u(e=Sn){let t=await Pn({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function qu(e=Sn,t=Hr){let n=await Pn({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var Da,ny=f(()=>{"use strict";zu();ju();Da=null});async function Wu(e){let t=Mt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Jt();return r.credentials[t]=n,Qu(r),ei(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Zn(e="github.com",t){let n=Mt(e);if(!t?.bypassCache){let i=Gg(n);if(i!==void 0)return i}let o=Jt().credentials[n]||null;return Hg(n,o),o}function Na(e="github.com"){let t=Mt(e);return Jt().credentials[t]||null}async function ry(e="github.com"){let t=Mt(e),n=!1,r=Jt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Xg():Qu(r),n=!0),ei(t),{success:n,deletedFromFile:n}}async function oy(){let e=Jt();return Object.keys(e.credentials)}function iy(){let e=Jt();return Object.keys(e.credentials)}async function sy(e="github.com"){return await Zn(e)!==null}function ay(e="github.com"){return Na(e)!==null}async function Ga(e,t){let n=await Zn(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Wu(n),!0):!1}function cy(){return Xt}async function ly(e="github.com"){let t=await Zn(e);return!t||!t.token||Yt(t)?null:t.token.token}function uy(e="github.com"){let t=Na(e);return!t||!t.token||Yt(t)?null:t.token.token}async function dy(e,t){return Bu({getCredentials:Zn,updateToken:Ga},e,t)}async function Vu(e,t){return Zg({getCredentials:Zn,updateToken:Ga},e,t)}var Ku=f(()=>{"use strict";Qg();Jg();ey();ny();ka();ty({getTokenWithRefresh:Vu})});var Yu=f(()=>{"use strict";Ku();zu()});import jr from"node:os";import py from"node:path";function my(){return ni?process.env.APPDATA||py.join(Qr,"AppData","Roaming"):Qr}function fy(){return ni?process.env.LOCALAPPDATA||py.join(Qr,"AppData","Local"):Qr}function hy(){return Xu?"macOS":ni?"Windows":Ju?"Linux":jr.platform()}function gy(){return jr.arch()}var ni,Xu,Ju,Qr,yy=f(()=>{"use strict";ni=jr.platform()==="win32",Xu=jr.platform()==="darwin",Ju=jr.platform()==="linux",Qr=jr.homedir()});var Zu=f(()=>{"use strict";yy()});import{z as J}from"zod";var GO,HO,Ha,QO,Qa,by,Ry,Sy=f(()=>{"use strict";GO=J.object({rawChars:J.number(),responseChars:J.number(),savedChars:J.number(),calls:J.number()}),HO=J.object({hits:J.record(J.string(),J.number()).default({}),rateLimits:J.number().default(0)}),Ha=J.record(J.string(),J.number()).default({}),QO=J.object({toolCalls:J.number(),errors:J.number(),rateLimits:J.number(),rateLimitsByProvider:Ha,rawChars:J.number(),responseChars:J.number(),savedChars:J.number(),charSavingsCalls:J.number(),githubCacheHits:J.number(),githubCacheRateLimits:J.number(),packageRegistryFailures:J.number().default(0),packageRegistryFailuresByRegistry:Ha}),Qa=J.object({toolCalls:J.number(),errors:J.number(),rateLimits:J.number(),rateLimitsByProvider:Ha,charsSavedByTool:J.record(J.string(),GO).default({}),githubCacheHits:HO.default({hits:{},rateLimits:0}),packageRegistryFailures:Ha,totalUsage:QO.optional()}),by=J.object({version:J.literal(1),sessionId:J.string(),createdAt:J.string(),lastActiveAt:J.string(),stats:Qa.optional()}),Ry=J.object({version:J.literal(1),stats:Qa})});function Py(e){return Object.values(e).reduce((t,n)=>t+n,0)}function jO(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:Py(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Py(o),packageRegistryFailuresByRegistry:o}}function xn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:jO(t)}}function Cn(){return xn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var ed=f(()=>{"use strict"});import{existsSync as td,readFileSync as Cy,writeFileSync as BO,unlinkSync as zO,renameSync as UO}from"node:fs";import{isStatsEnabled as wy}from"@octocodeai/config";function xy(e,t){let n=`${e}.tmp`;BO(n,JSON.stringify(t,null,2),{mode:384}),UO(n,e)}function $O(e){let t=JSON.parse(e),n=Ry.safeParse(t);if(n.success)return xn(n.data.stats);let r=Qa.safeParse(t);return r.success?xn(r.data):null}function qO(){if(!td(tr))return Cn();try{let e=Cy(tr,"utf8");return $O(e)??Cn()}catch{return Cn()}}function ja(e){Rn(),wy()&&xy(tr,{version:e.version,stats:xn(e.stats)});let{stats:t,...n}=e;xy(er,n)}function Ty(){if(!td(er))return null;try{let e=Cy(er,"utf8"),t=JSON.parse(e),n=by.safeParse(t);return n.success?{...n.data,stats:wy()?qO():Cn()}:null}catch{return null}}function Ey(){let e=!1;for(let t of[er,tr])if(td(t))try{zO(t),e=!0}catch{return!1}return e}var er,tr,Ba=f(()=>{"use strict";Ku();ti();Sy();ed();er=Ue.session,tr=Ue.stats});function VO(){nd||(nd=!0,ri=()=>{si()},oi=()=>{si()},ii=()=>{si()},process.on("exit",ri),process.on("SIGINT",oi),process.on("SIGTERM",ii))}function rd(){ri&&(process.removeListener("exit",ri),ri=null),oi&&(process.removeListener("SIGINT",oi),oi=null),ii&&(process.removeListener("SIGTERM",ii),ii=null),nd=!1}function KO(){Br||(Br=setInterval(()=>{wn&&Tt&&(ja(Tt),wn=!1)},WO),Br.unref())}function od(){Br&&(clearInterval(Br),Br=null)}function ai(){if(Tt)return Tt;let e=Ty();return e&&(Tt=e),e}function zr(e){Tt=e,wn=!0,VO(),KO()}function ci(){wn&&Tt&&(ja(Tt),wn=!1)}function si(){if(!za&&wn&&Tt){za=!0;try{ja(Tt),wn=!1}catch{}finally{za=!1}}}function id(){Tt=null,wn=!1,za=!1}function ky(){id(),od(),rd()}var WO,Tt,wn,Br,nd,ri,oi,ii,za,Oy=f(()=>{"use strict";Ba();WO=6e4,Tt=null,wn=!1,Br=null,nd=!1,ri=null,oi=null,ii=null,za=!1});import{randomUUID as YO}from"node:crypto";function JO(e){return xn(e)}function ZO(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 vy(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 ev(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 Ay(){let e=new Date().toISOString();return{version:XO,sessionId:YO(),createdAt:e,lastActiveAt:e,stats:Cn()}}function Ly(){ci()}function _y(){si()}function Fy(e){if(e?.forceNew){let r=Ay();return zr(r),ci(),r}let t=ai();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return zr(r),ci(),r}let n=Ay();return zr(n),ci(),n}function Iy(){return ai()?.sessionId??null}function ct(e){let t=ai();if(!t)return{success:!1,session:null};let n=JO(t.stats),r=xn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:vy(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:ZO(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:ev(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:vy(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return zr(o),{success:!0,session:o}}function My(e=1){return ct({toolCalls:e})}function Dy(e=1){return ct({errors:e})}function Ua(e=1){return ct({rateLimits:e})}function Ny(e,t=1){return ct({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function $a(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return ct({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function qa(e,t=1){return ct({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function Wa(e=1){return ct({githubCacheHits:{hits:{},rateLimits:e}})}function Gy(e,t=1){return ct({packageRegistryFailures:{[e]:t}})}function Hy(){let e=ai();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Cn()};return zr(t),{success:!0,session:t}}function Qy(){return id(),od(),rd(),Ey()}function jy(){ky()}var XO,li=f(()=>{"use strict";Ba();ed();Oy();Ba();XO=1});var sd=f(()=>{"use strict";li();li();li();li()});import{z as we}from"zod";var By,ad=f(()=>{"use strict";By=we.looseObject({$schema:we.string().optional(),version:we.number().int().optional(),github:we.record(we.string(),we.unknown()).optional(),local:we.record(we.string(),we.unknown()).optional(),tools:we.record(we.string(),we.unknown()).optional(),network:we.record(we.string(),we.unknown()).optional(),lsp:we.record(we.string(),we.unknown()).optional(),output:we.record(we.string(),we.unknown()).optional()})});import{setRuntimeSurface as Xj,invalidateConfigCache as Jj}from"@octocodeai/config";var zy=f(()=>{"use strict";ad()});import{existsSync as tv,readdirSync as nv,lstatSync as rv}from"node:fs";import{join as ov}from"node:path";function ui(e){if(!tv(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=nv(r)}catch{continue}for(let i of o){let s=ov(r,i);try{let a=rv(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function iv(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}var cd=f(()=>{"use strict"});var Nt=f(()=>{"use strict";Yu();Zu();sd();zy();ti();cd()});var nr,Va=f(()=>{nr="17.0.2"});import{getConfigSync as Uy,invalidateConfigCache as av}from"@octocodeai/config";import{maskSensitiveData as cv}from"@octocodeai/octocode-engine/mask";function hB(e){e.resolveTokenFull&&(ld=e.resolveTokenFull)}function gB(){ld=Pn}async function ud(){try{let e=await ld({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:lv.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function $y(){if(Tn!==null)return;if(Ur!==null)return Ur;let e=(async()=>{let t=Uy(),n=await ud();Tn={version:nr,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}})();Ur=e;try{await e}catch(t){throw Ur===e&&(Tn=null,Ur=null),t}}function yB(){Tn=null,Ur=null,av()}function di(){if(!Tn){let e=cv(Mu.NOT_INITIALIZED.message);throw new Error(e)}return Tn}async function dd(){return(await ud()).token}function bB(){return di().enableLocal}function RB(){let e=di();return e.enableLocal&&e.enableClone}async function SB(){return Tn!==null?Tn.tokenSource:(await ud()).source}function pd(){return"github"}function md(){let e=Uy().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var Tn,Ur,ld,lv,$r=f(()=>{"use strict";Nt();Va();st();Tn=null,Ur=null,ld=Pn;lv=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});function En(e){(e.provider?ct({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Ua(1)).session&&e.provider==="github"&&Wa(1)}function qy(e){ct({packageRegistryFailures:{[e]:1}})}var pi=f(()=>{"use strict";Nt()});import{Octokit as uv}from"octokit";import{throttling as dv}from"@octokit/plugin-throttling";import{createHash as pv}from"crypto";function Xy(e){return pv("sha256").update(e).digest("hex").substring(0,16)}async function Ge(e){let t=e?.token??await dd(),n=t?Xy(t):"anon",r=di().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}function Jy(e){return Date.now()-e.createdAt>fv}function Zy(){for(let[e,t]of Gt.entries())Jy(t)&&Gt.delete(e);if(Gt.size>fd){let e=Gt.size-fd,t=0;for(let[n]of Gt){if(t>=e)break;Gt.delete(n),t++}}}function gv(){kn||(kn=setInterval(Zy,hv),typeof kn=="object"&&"unref"in kn&&kn.unref())}function Ky(e,t,n){En({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function bv(e){let t=di(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${nr}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:yv(),log:r,...e&&{auth:e}};return new mv(o)}async function oe(e){gv();let t=e?.token??await dd(),n=t?Xy(t):"ANONYMOUS",r=Gt.get(n);if(r&&!Jy(r))return r.client;Gt.size>=fd&&Zy();let o=bv(t??void 0);return Gt.set(n,{client:o,createdAt:Date.now()}),o}async function Ye(e,t,n){let r=`${e}/${t}`,o=qr.get(r);if(o)return o;let i=await oe(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Yy(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}),Yy(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 Yy(e,t){if(qr.size>=Rv){let n=qr.keys().next().value;n!==void 0&&qr.delete(n)}qr.set(e,t)}function LB(){Gt.clear(),qr.clear(),kn&&(clearInterval(kn),kn=null)}var mv,fv,fd,hv,Gt,kn,Wy,Vy,yv,Rv,qr,Ae=f(()=>{"use strict";$r();$r();Va();pi();mv=uv.plugin(dv),fv=300*1e3,fd=50,hv=60*1e3;Gt=new Map,kn=null;Wy=3,Vy=60;yv=()=>({onRateLimit:(e,t,n,r)=>(Ky("primary",e,t),r<Wy&&e<Vy),onSecondaryRateLimit:(e,t,n,r)=>(Ky("secondary",e,t),r<Wy&&e<Vy)});Rv=200,qr=new Map});import{createRequire as Sv}from"node:module";function ae(){if(Ka)return Ka;try{return Ka=xv(),Ka}catch(e){throw new hd(e)}}var Pv,eb,Ka,xv,hd,D,Le=f(()=>{"use strict";Pv=Sv(import.meta.url),eb="@octocodeai/octocode-engine",xv=()=>Pv(eb),hd=class extends Error{constructor(n){super(`Failed to load native dependency ${eb}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return ae().applyContentViewMinification(e,t)},applyMinification(e,t){return ae().applyMinification(e,t)},minifyContent(e,t){return ae().minifyContent(e,t)},minifyContentSync(e,t){return ae().minifyContentSync(e,t)},minifyContentResult(e,t){return ae().minifyContentResult(e,t)},minifyMarkdownCore(e){return ae().minifyMarkdownCore(e)},extractSignatures(e,t){return ae().extractSignatures(e,t)},extractJsSymbols(e,t){return ae().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ae().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ae().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return ae().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ae().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ae().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ae().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ae().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return ae().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return ae().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ae().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ae().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ae().parseRipgrepJson(e,t)},searchRipgrep(e){return ae().searchRipgrep(e)},queryFileSystem(e){return ae().queryFileSystem(e)},extractMatchingLines(e,t,n){return ae().extractMatchingLines(e,t,n)},filterPatch(e,t){return ae().filterPatch(e,t)},computeLineDiff(e,t){return ae().computeLineDiff(e,t)},charToByteOffset(e,t){return ae().charToByteOffset(e,t)},byteToCharOffset(e,t){return ae().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ae().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ae().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ae().SIGNATURES_ONLY_HINT}}});var K,Fe,tb,gd,yd,Ya,bd=f(()=>{"use strict";K={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"},Fe={[K.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."},[K.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."},[K.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},[K.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)."},[K.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."},[K.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."},[K.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."},[K.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."},[K.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."},[K.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},tb={401:K.AUTH_REQUIRED,403:K.FORBIDDEN_PERMISSIONS,404:K.NOT_FOUND,422:K.INVALID_REQUEST,502:K.SERVER_UNAVAILABLE,503:K.SERVER_UNAVAILABLE,504:K.SERVER_UNAVAILABLE},gd={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},yd={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ya={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as nb}from"octokit";function Ht(e){if(!(e instanceof nb)||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 Cv.some(o=>r.includes(o))})}function re(e){return e instanceof nb?wv(e):e instanceof Error?_v(e):{error:typeof e=="string"?e:Fe[K.UNKNOWN].message,type:"unknown"}}function wv(e){let{status:t,message:n,response:r}=e;if(t===403)return Ev(n,r);if(t===429)return Tv(n,r);let o=tb[t];return o?Lv(o,t):Wr(K.UNKNOWN,{error:n||Fe[K.UNKNOWN].message,status:t})}function Rd(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function Tv(e,t){let n=t?.headers,r=Rd(n,"retry-after"),o=Rd(n,"x-ratelimit-reset"),i=Rd(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ya.RESET_BUFFER_SECONDS,0):void 0);return En({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Wr(K.RATE_LIMIT_PRIMARY,{error:e||Fe[K.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Fe[K.RATE_LIMIT_PRIMARY].suggestion})}function Ev(e,t){let n=t?.headers;if(yd.SECONDARY.test(e))return kv(n);let r=n?.["x-ratelimit-remaining"],o=Av(t);return r!==void 0&&String(r)==="0"||o?Ov(n):vv(n)}function kv(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ya.SECONDARY_FALLBACK_SECONDS:t;return En({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Wr(K.RATE_LIMIT_SECONDARY,{error:Fe[K.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Fe[K.RATE_LIMIT_SECONDARY].suggestion})}function Ov(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)+Ya.RESET_BUFFER_SECONDS,0):void 0,i=r?Fe[K.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Fe[K.RATE_LIMIT_PRIMARY].messageWithoutTime;return En({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Wr(K.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Fe[K.RATE_LIMIT_PRIMARY].suggestion})}function vv(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Fe[K.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Fv(String(t),String(n))),Wr(K.FORBIDDEN_PERMISSIONS,{error:Fe[K.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Av(e){return e?.data?.errors?.some(n=>n.type===yd.GRAPHQL_TYPE)??!1}function Lv(e,t){let n=Fe[e];return Wr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function _v(e){return gd.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Fe[K.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Fe[K.NETWORK_CONNECTION_FAILED].suggestion}:gd.TIMEOUT.some(t=>e.message.includes(t))?{error:Fe[K.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Fe[K.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Wr(e,t){return{type:"http",...t}}function Fv(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?Fe[K.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Fe[K.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var Cv,tt=f(()=>{"use strict";bd();pi();Cv=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function rb(e){return`user:${e}`}function Sd(e){return e.startsWith('"')||Mv.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var Iv,Mv,Zt,mi=f(()=>{"use strict";Iv=/[@/]/,Mv=/^[A-Za-z0-9_-]+$/;Zt=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(rb(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=Iv.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.addSimpleFilter(t.interactions,"interactions"),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()}}});function Cd(e){return new Pd().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function wd(e){return new xd().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var Dv,Pd,xd,ob=f(()=>{"use strict";mi();Dv=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Pd=class extends Zt{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(Sd))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Dv):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}},xd=class extends Zt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Sd)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}}});function Ed(e){return new Td().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function kd(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Td,ib=f(()=>{"use strict";mi();Td=class extends Zt{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.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});function vd(e){return new Od().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ad(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.involves!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.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)}var Od,sb=f(()=>{"use strict";mi();Od=class extends Zt{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.addSimpleFilter(t.involves,"involves"),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}}});var rr=f(()=>{"use strict";mi();ob();ib();sb()});import Nv from"crypto";function Qv(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(Hv.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Te(e,t,n){let r=Ld(Qv(t)),o=n?`${n}:${r}`:r,i=Nv.createHash("sha256").update(o).digest("hex");return`${Gv}-${e}:${i}`}function Ld(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=>Ld(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Ld(i,t)}`}).join(",")}}`)}var Gv,Hv,ab=f(()=>{"use strict";Gv="v2",Hv=new Set([])});import jv from"node-cache";function zv(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Uv(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function fi(e){let t=zv(e);if(!(!t||!Uv(t)))try{qa(t,1)}catch{}}function Xa(){let e=Date.now();for(let[t,n]of ft.entries())e-n.startedAt>Bv&&ft.delete(t)}function hi(e){return cb[e]||cb.default}function gi(e,t,n){try{return $e.set(e,t,n),Se.sets++,Se.totalKeys=$e.keys().length,!0}catch{try{let r=$e.keys();for(let o of r)$e.get(o);return $e.set(e,t,n),Se.sets++,Se.totalKeys=$e.keys().length,!0}catch{return!1}}}var Bv,$e,Se,cb,ft,Ja=f(()=>{"use strict";Nt();Bv=300*1e3,$e=new jv({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Se={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},cb={"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},ft=new Map});async function He(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=$e.get(e);if(i!==void 0)return Se.hits++,fi(e),i}catch{}Xa();let r=ft.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Se.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=hi(l)}gi(e,i,a)}return i}finally{ft.delete(e)}})();return ft.set(e,{promise:o,startedAt:Date.now()}),o}var lb=f(()=>{"use strict";Ja()});import $v from"node-cache";async function Za(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=$e.get(e);if(i!==void 0)return Se.hits++,fi(e),i}catch{}Xa();let r=ft.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:yi.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){Se.hits++,fi(e);let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=hi(u)}return gi(e,i.data,c),i.data}if(n.forceRefresh||Se.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=hi(u)}gi(e,s.value,c),yi.set(e,{data:s.value,etag:s.etag})}return s.value}finally{ft.delete(e)}})();return ft.set(e,{promise:o,startedAt:Date.now()}),o}var yi,_d=f(()=>{"use strict";Ja();yi=new $v({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1})});function uz(){$e.flushAll(),yi.flushAll(),ft.clear(),Se.hits=0,Se.misses=0,Se.sets=0,Se.totalKeys=0,Se.lastReset=new Date}function On(e){let t=$e.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||$e.del(r)>0&&n++}return n>0&&(Se.totalKeys=$e.keys().length),n}function dz(){return On("local-")}function pz(){return On("lsp-")}function mz(){let e=0;return e+=On("gh-api-"),e+=On("bb-api-"),e+=On("gh-repo-"),e+=On("bb-repo-"),e+=On("github-user"),e+=On("npm-search"),yi.flushAll(),e}function fz(){let e=Se.hits+Se.misses;return{...Se,hitRate:e>0?Se.hits/e*100:0,cacheSize:$e.keys().length}}var ub=f(()=>{"use strict";Ja();_d()});var lt=f(()=>{"use strict";ab();lb();_d();ub()});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as Cz,DISCOVERY_IGNORED_FILE_NAMES as wz,DISCOVERY_IGNORED_FOLDER_NAMES as Tz,getDiscoveryExtension as db,shouldIgnoreDiscoveryDir as bi,shouldIgnoreDiscoveryFile as Vr}from"@octocodeai/octocode-engine/security";var Kr=f(()=>{"use strict"});function Q(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function mb(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function V(e,t){let n=typeof t=="number"?mb(t):Q(t);if(n===void 0)return e;try{Object.defineProperty(e,pb,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ue(e){if(!(typeof e!="object"||e===null))return mb(e[pb])}var pb,le=f(()=>{"use strict";pb=Symbol.for("octocode.rawResponseChars")});function Ri(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 Yr(e){let t=Ri(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}var or=f(()=>{"use strict"});import{ContentSanitizer as qv}from"@octocodeai/octocode-engine/contentSanitizer";async function hb(e,t,n){let r=await Ge(t),o=Te("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 Wv(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function Wv(e,t){try{let n=await oe(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(b=>b&&b.trim()).length===0)return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let r=Cd(e);if(!r.trim())return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:fb,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 Vv(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),h=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:h,...h?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Ri(a.headers),rawResponseChars:Q(a.data)}}catch(n){if(Ht(n)){let o=Math.min(typeof e.limit=="number"?e.limit:fb,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 re(n)}}async function Vv(e,t){let n=Kv(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Vr(p.path)),c=0,l=0,u=await Promise.allSettled(a.map(async p=>{s.add(p.path);let h=[],g=await Promise.allSettled((p.text_matches||[]).map(async k=>{let E=k.fragment,_=qv.sanitizeContent(E||"",p.path);E=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(w=>r.add(`${p.path}: ${w}`));try{let w=await D.minifyContent(E||"",p.path);E=w.content,w.failed?o=!0:w.type!=="failed"&&(h.push(w.type),i.push(w.type))}catch{o=!0}return{context:E||"",positions:k.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),y=g.filter(k=>k.status==="fulfilled").map(k=>k.value),b=g.filter(k=>k.status==="rejected").length;b>0&&(l+=b);let S=p,C=Array.from(new Set(h));return{path:p.path,matches:y,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...C.length>0&&{minificationType:C.join(",")}}})),d=u.filter(p=>p.status==="fulfilled").map(p=>p.value);c=u.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function Kv(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var fb,Fd=f(()=>{"use strict";Le();Ae();tt();rr();lt();Kr();st();le();or();ce();fb=30});import{readdirSync as Yv,statSync as gb}from"node:fs";import{join as Xv}from"node:path";function Dd(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function Rb(e){return Object.values(e).every(t=>t===0)}function Nd(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 Sb(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 eA(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function eA(e,t){try{let o=new URL(e);if(!Zv.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(),Jv);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 Pb(e,t){let n=[],r=0;function o(i){let s;try{s=Yv(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Xv(i,a);try{let l=gb(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function xb(e){try{return gb(e).size}catch{return 0}}var Si,ec,Id,yb,Jv,bb,Md,Zv,tc=f(()=>{"use strict";Si=50,ec=5*1024*1024,Id=300*1024,yb=5,Jv=1e4,bb=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"]),Md={maxDirectoryFiles:Si,maxTotalSize:ec,maxFileSize:Id};Zv=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});import{join as nc}from"node:path";import{createHash as Cb}from"node:crypto";function tA(e){return Pi(e)}function Pi(e){return nc(e,"tmp","clone")}function rc(e){return nc(e,"tmp","tree")}function nA(e){return e?`__sp_${Cb("sha256").update(e).digest("hex").substring(0,6)}`:""}function wb(e){if(!/[\\/]/.test(e))return e;let t=Cb("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function Gd(e,t,n,r,o){let i=`${wb(r)}${nA(o)}`;return nc(Pi(e),t,n,i)}function xi(e,t,n,r){return nc(rc(e),t,n,wb(r))}var Hd=f(()=>{"use strict"});import{existsSync as Ti,readFileSync as rA,writeFileSync as oA,mkdirSync as iA,rmSync as wi,readdirSync as sA,statSync as aA}from"node:fs";import{join as vn}from"node:path";function pA(e){return typeof e=="object"&&e!==null}function mA(e){if(!pA(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 Qd(e){let t=vn(e,Eb);if(!Ti(t))return null;try{return mA(JSON.parse(rA(t,"utf-8")))}catch{return null}}function Zr(e,t){try{oA(vn(e,Eb),JSON.stringify(t,null,2),"utf-8")}catch{}}function kb(e){return Date.now()<new Date(e.expiresAt).getTime()}function eo(e){let t=Qd(e);return t?kb(t)?Ti(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function fA(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return cA}function hA(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return uA}function gA(){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 dA}function to(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+fA()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function An(e){let t=vn(e,"..");try{Ti(t)||iA(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 ic(e){try{Ti(e)&&wi(e,{recursive:!0,force:!0})}catch{}}function Ci(e){try{return aA(e).isDirectory()}catch{return!1}}function ir(e){try{return sA(e)}catch{return[]}}function*Ob(e){for(let t of ir(e)){let n=vn(e,t);if(Ci(n))for(let r of ir(n)){let o=vn(n,r);if(Ci(o))for(let i of ir(o)){let s=vn(o,i);Ci(s)&&(yield s)}}}}function Tb(e){for(let t of[...ir(e)]){let n=vn(e,t);if(Ci(n)){for(let r of[...ir(n)]){let o=vn(n,r);if(Ci(o)&&ir(o).length===0)try{wi(o,{recursive:!0,force:!0})}catch{}}if(ir(n).length===0)try{wi(n,{recursive:!0,force:!0})}catch{}}}}function yA(e){let t=0;for(let n of Ob(e))try{let r=Qd(n);(!r||!kb(r))&&(wi(n,{recursive:!0,force:!0}),t++)}catch{}return t}function bA(e){let t=[];for(let n of Ob(e)){let r=Qd(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??ui(n)})}return t}function RA(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{wi(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function vb(e){if(!Ti(e))return 0;let t=0;try{t+=yA(e)}catch{return t}Tb(e);let n=RA(bA(e),hA(),gA());return t+=n,n>0&&Tb(e),t}function oc(e){return vb(Pi(e))}function Jr(e){return vb(rc(e))}function Yz(e){Xr||(oc(e),Jr(e),Xr=setInterval(()=>{oc(e),Jr(e)},lA),Xr.unref())}function Xz(){Xr&&(clearInterval(Xr),Xr=null)}var cA,lA,uA,dA,Eb,Xr,Ei=f(()=>{"use strict";Nt();Hd();Hd();cA=1440*60*1e3,lA=600*1e3,uA=2*1024*1024*1024,dA=50,Eb=".octocode-clone-meta.json",Xr=null});import{writeFileSync as SA,mkdirSync as Ab,existsSync as jd,rmSync as PA}from"node:fs";import{join as Lb,dirname as xA,resolve as _b,sep as Fb}from"node:path";async function Bd(e,t,n,r,o,i=!1){let s=Jn(),a=xi(s,e,t,r),c=_b(Lb(a,n));if(!c.startsWith(a+Fb)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=eo(a);if(l.hit&&!i&&jd(c)){let A=Pb(c,a),W=Dd();return{localPath:c,repoRoot:a,files:A.files,fileCount:A.fileCount,totalSize:A.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:A.fileCount,eligibleFileCount:A.fileCount,savedFileCount:A.fileCount,skipped:W,limits:Md,warnings:Nd(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await oe(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await u.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 p=m,h=Dd(),g=[];for(let A of p){if(A.type!=="file"){h.nonFile+=1;continue}if(!A.download_url){h.missingDownloadUrl+=1;continue}if(A.size>Id){h.oversized+=1;continue}let W=db(A.name,{lowercase:!0,leadingDot:!0});if(bb.has(W)){h.binary+=1;continue}g.push(A)}h.fileLimit=Math.max(0,g.length-Si);let y=g.slice(0,Si),b=o?.token,S=await Sb(y,yb,b);h.fetchFailed=y.length-S.length;let C=0,k=[];for(let A=0;A<S.length;A+=1){let{entry:W,content:H}=S[A];if(C+H.length>ec){h.totalSizeLimit=S.length-A;break}C+=H.length,k.push({entry:W,content:H})}Jr(s),An(a),jd(c)&&PA(c,{recursive:!0,force:!0}),Ab(c,{recursive:!0,mode:448});let E=[];for(let{entry:A,content:W}of k){let H=_b(Lb(a,A.path));if(!H.startsWith(a+Fb)){h.pathTraversal+=1;continue}let Y=xA(H);jd(Y)||Ab(Y,{recursive:!0,mode:448}),SA(H,W,"utf-8"),E.push({path:A.path,size:W.length,type:"file"})}let _=to(e,t,r,"treeFetch",void 0,void 0,d);Zr(a,_);let w=Rb(h),G=w,M=h.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:C,complete:w,verified:G,...d?{commitSha:d}:{},...M?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:h,limits:Md,warnings:Nd(w,G),cached:!1,expiresAt:_.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}var Ib=f(()=>{"use strict";Nt();Ae();Ei();Kr();tc()});import{completeMetadata as zd}from"@octocodeai/octocode-core";var v,Ud=f(()=>{"use strict";v=new Proxy({},{get(e,t){return zd.toolNames[t]},ownKeys(){return Object.keys(zd.toolNames)},getOwnPropertyDescriptor(e,t){let n=zd.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as $d}from"@octocodeai/octocode-core";function sc(e=$d){if(qd&&e===$d)return qd;let t=e,n=t.tools?.localFindFiles;n?.description&&Mb.test(n.description)&&(t={...t,tools:{...t.tools,localFindFiles:{...n,description:n.description.replace(Mb,CA)}}});let r=t.tools?.ghHistoryResearch;return r?.description&&Db.test(r.description)&&(t={...t,tools:{...t.tools,ghHistoryResearch:{...r,description:r.description.replace(Db,wA)}}}),e===$d&&(qd=t),t}var Mb,CA,Db,wA,qd,Wd=f(()=>{"use strict";Mb=/Default excludeDir skips common generated\/vendor dirs; pass \[\] to search all\./,CA='Nothing is excluded by default \u2014 pass excludeDir (e.g. ["node_modules","dist","coverage"]) to prune build/vendor dirs.',Db=/type:"prs" searches PRs; add prNumber to read selected content\. type:"commits" reads owner\/repo\/path history\./,wA='type:"prs" searches PRs; add prNumber to read selected content. type:"commits" reads owner/repo/path history. type:"issues" searches or reads GitHub issues; add issueNumber to read a specific issue (body + comments). type:"releases" lists repo releases.',qd=null});var Vd,Kd=f(()=>{"use strict";Wd();Vd=new Proxy({},{get(e,t){return sc().tools[t]?.description??""}})});import{completeMetadata as TA}from"@octocodeai/octocode-core";function Yd(e){return Object.prototype.hasOwnProperty.call(TA.tools,e)}var Xd=f(()=>{"use strict"});import{completeMetadata as EA}from"@octocodeai/octocode-core";function Jd(){return EA.baseSchema}var kA,Zd=f(()=>{"use strict";kA=new Proxy({},{get(e,t){return Jd()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Jd())]))},getOwnPropertyDescriptor(e,t){let n=Jd();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var me=f(()=>{"use strict";Ud();Kd();Xd();Zd()});function ep(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 tp(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(p=>p.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>l.push(p.path)),l.length===0&&d.length>=3&&c.filter(h=>{let g=h.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(h=>l.push(h.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var Nb=f(()=>{"use strict"});import{RequestError as np}from"octokit";async function OA(e,t,n,r,o,i,s,a){let c=await Ye(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=re(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await tp(e,r,o,i,s||c);return m.length>0&&(u.hints=[...u.hints||[],...ep(i,m)]),{...u,...d&&{scopesSuggestion:d}}}async function vA(e,t,n,r,o,i){let s=re(t),a=await tp(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...ep(o,a)]),s}async function Gb(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:gn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:gn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:gn.DECODE_FAILED.message,type:"unknown",status:422}}}async function Hb(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"?Gb(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return re(i)}}async function AA(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 Ye(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(m=>m.name===a&&m.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await Hb(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return re(s)}}async function ki(e,t,n={}){try{let r=await oe(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(p){if(p instanceof np&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof np&&p.status===404)if(a){let h=await OA(r,p,c,o,i,s,a,t);if("result"in h)l=h.result,u=h.actualBranch;else return h}else return await vA(r,p,o,i,s,a);else{if(p instanceof np&&p.status===413)return await AA(r,o,i,s,a||u,t);throw p}}let d=l.data,m=Yr(l.headers);if(Array.isArray(d))return{error:gn.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",h=d.size??0,g;if(p.length>0)g=await Gb(p,s);else if(h>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await Hb(r,o,i,d.sha,s);else return{error:gn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!u&&!a)try{u=await Ye(o,i,t)}catch{}return{data:{rawContent:g.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:Q(d),...m?{etag:m}:{}}}return{error:gn.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return re(r)}}var Qb=f(()=>{"use strict";Ae();tt();me();st();le();or();Nb()});var ac=f(()=>{"use strict";Qb()});import{writeFileSync as LA,mkdirSync as _A,existsSync as jb}from"node:fs";import{join as FA,dirname as IA,resolve as MA,sep as DA}from"node:path";async function rp(e,t,n,r,o,i=!1){let s=Jn(),a=xi(s,e,t,r),c=MA(FA(a,n));if(!c.startsWith(a+DA)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=eo(a);if(!i&&l.hit&&jb(c))return{localPath:c,repoRoot:a,path:n,size:xb(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await ki({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 u)||!u.data){let h="error"in u?u.error:void 0;throw new Error(h||`Failed to fetch ${e}/${t}/${n}`)}Jr(s),An(a);let d=IA(c);jb(d)||_A(d,{recursive:!0,mode:448}),LA(c,u.data.rawContent,"utf-8");let m=u.data.branch||r,p=to(e,t,m,"treeFetch");return Zr(a,p),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}var Bb=f(()=>{"use strict";Nt();ac();Ei();tc()});var op=f(()=>{"use strict";tc();Ib();Bb()});function Oi(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Qt(e){return Oi(e).length}var sr=f(()=>{"use strict"});function cc(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
11
|
+
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var lc=f(()=>{"use strict";Le()});function GA(e){return NA.test(e.split(/[?#]/,1)[0]??e)}function zb(e,t){return GA(t)?QA(HA(e)):null}function uc(e,t){let n=zb(e,t);if(n===null||n.length===0)return null;let r=[];return $b(n,r),r.join(`
|
|
12
|
+
`)}function Ub(e,t){let n=zb(e,t);return n===null?null:n.map(qb)}function HA(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function QA(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 $b(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}`),$b(n.children,t)}}function qb(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(qb)}}var NA,dc=f(()=>{"use strict";NA=/\.(?:md|markdown|mdx)$/i});import{getConfigSync as jA,DEFAULT_OUTPUT_CONFIG as BA}from"@octocodeai/config";function Ln(){try{return jA().output.pagination.defaultCharLength}catch{return BA.pagination.defaultCharLength}}function JU(e){let t=Math.min(Math.max(Ln(),1),Wb),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,Wb)}var Wb,vi=f(()=>{"use strict";Wb=1e5});function zA(e,t,n){return D.byteSliceContent(e,t,n)}function pc(e,t){return D.byteToCharOffset(e,t)}function Vb(e,t){return D.charToByteOffset(e,t)}function Kb(e){return D.charToByteOffset(e,e.length)}function t$(e,t,n){let r=zA(e,t,t+n);return{charOffset:pc(e,t),charLength:r.length,text:r}}function ip(e,t,n,r){return D.sliceContent(e,t,n,r)}var sp=f(()=>{"use strict";Le()});function mc(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Kb(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,m,p,h,g;if(o==="bytes"){let y=Math.min(t,s),b=Math.min(y+n,s);d=pc(e,y),m=pc(e,b),m<i&&Vb(e,m)<b&&(m+=1);let S=ip(e,d,m-d);c=S.text,d=S.charOffset,m=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,p=u<s;let C=r.actualOffset??y;h=Math.floor(C/a)+1,g=Math.max(h,Math.ceil(s/a))}else{let y=ip(e,t,n);c=y.text,d=y.charOffset,m=y.charOffset+y.charLength,l=y.byteOffset,u=y.byteOffset+y.byteLength,p=m<i;let b=r.actualOffset??d;h=Math.floor(b/a)+1,g=Math.max(h,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:p?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:h,totalPages:g}}function o$(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function ap(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 i$(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 l=e.lastIndexOf(`
|
|
14
14
|
`,o-1);o=l===-1?0:l+1}let i=o,s=0;for(;i<r;){let l=e.indexOf(`
|
|
15
|
-
`,i);if(l===-1){i=r;break}if(i=l+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
|
|
16
|
-
`,t);return n===-1?void 0:n+1}function
|
|
17
|
-
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function
|
|
18
|
-
`),E=Qt(C),_=e,w,G,M=!1,A;if(i)_=e;else if(l){let Y=d===!0,I;try{I=
|
|
19
|
-
`);let Re=I.matchRanges[0],Oe=I.matchRanges[I.matchRanges.length-1];s=Re.start,a=Oe.end,w=Re.start,G=Oe.end,M=!0,I.matchRanges.length>1&&(A=I.matchRanges);let hn=I.matchingLines.slice(0,5).join(", "),
|
|
20
|
-
`),I>E&&S.add(`Requested endLine ${I} adjusted to ${E} (file end)`)}}let W=up.sanitizeContent(_,o);if(_=g?D.applyContentViewMinification(W.content,o):W.content,W.hasSecrets&&S.add(`Secrets detected and redacted: ${W.secretsDetected.join(", ")}`),W.warnings.length>0&&W.warnings.forEach(Y=>S.add(Y)),E>2e3&&m!=="symbols"&&!l&&!s&&!a&&!i){let Y=Math.max(1,E-200);S.add(`Large file (${E} lines) \u2014 minify:"symbols" for an export index, or startLine=${Y} for the tail.`)}let H=Array.from(S);return{owner:t,repo:n,path:o,content:_,contentView:y,branch:r,totalLines:E,...
|
|
15
|
+
`,i);if(l===-1){i=r;break}if(i=l+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 fc=f(()=>{"use strict";sp()});function qA(e){return e&&e.trim().length>0?e:$A}async function Yb(e,t){return(await D.getSemanticBoundaryOffsets(e,qA(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function WA(e,t){let n=e.indexOf(`
|
|
16
|
+
`,t);return n===-1?void 0:n+1}function Ai(e){let t=e.trimEnd().split(`
|
|
17
|
+
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function Li(e,t,n){let r=WA(e,Math.max(0,t));return r===void 0?void 0:(await Yb(e,n)).find(i=>i>=r&&i>t)}async function c$(e,t,n,r,o){if(!Ai(e))return;let i=await Li(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 hc(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 Yb(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=UA?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var UA,$A,gc=f(()=>{"use strict";Le();UA=8e3,$A="__octocode_generic__.unknown"});function VA(){let e=Ln();return Math.min(e,8e3)}async function cp(e,t,n){let r=e.content??"",o=n??VA();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await hc(r,t,o,i),c=mc(r,t,s,{pageSize:o}),l;if(c.hasMore&&a==="char-limit"&&Ai(c.paginatedContent)){let u=c.charOffset+c.charLength;l=await Li(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function lp(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}}var Xb=f(()=>{"use strict";vi();ce();fc();gc()});import{ContentSanitizer as up}from"@octocodeai/octocode-engine/contentSanitizer";function _i(e,t){return{sourceChars:e,sourceBytes:t}}async function Jb(e,t,n,r,o,i,s,a,c=5,l,u,d,m="standard"){let p=e.length,h=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",y=g?"standard":"none",b;if(m==="symbols"){let Y=D.extractSignatures(e,o);if(Y===null){let I=uc(e,o);if(I!==null){let Re=up.sanitizeContent(I,o),Oe=[D.SIGNATURES_ONLY_HINT];return Re.hasSecrets&&Oe.push(`Secrets detected and redacted: ${Re.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Re.content,contentView:"symbols",branch:r,totalLines:Qt(e),..._i(p,h),isPartial:!1,signaturesExtracted:!0,hints:Oe}}b=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(Y!==null){let I=up.sanitizeContent(Y,o),Re=D.applyContentViewMinification(I.content,o),Oe=[D.SIGNATURES_ONLY_HINT];return l&&Oe.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),I.hasSecrets&&Oe.push(`Secrets detected and redacted: ${I.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Re,contentView:"symbols",branch:r,totalLines:Qt(e),..._i(p,h),isPartial:!1,signaturesExtracted:!0,hints:Oe}}}let S=new Set,C=e,k=C.split(`
|
|
18
|
+
`),E=Qt(C),_=e,w,G,M=!1,A;if(i)_=e;else if(l){let Y=d===!0,I;try{I=cc(k,l,c,u??!1,Y)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,..._i(p,h),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(I.matchCount===0){let Ca=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${Y?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${Y?" (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:E,..._i(p,h),matchNotFound:!0,searchedFor:l,hints:Ca}}_=I.lines.join(`
|
|
19
|
+
`);let Re=I.matchRanges[0],Oe=I.matchRanges[I.matchRanges.length-1];s=Re.start,a=Oe.end,w=Re.start,G=Oe.end,M=!0,I.matchRanges.length>1&&(A=I.matchRanges);let hn=I.matchingLines.slice(0,5).join(", "),Uo=I.matchingLines.length>5?` and ${I.matchingLines.length-5} more`:"";S.add(I.matchCount>1?`Found ${I.matchCount} occurrences of "${l}" on lines ${hn}${Uo} \u2014 all shown as ${I.matchRanges.length} slice${I.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${I.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let Y=s||1,I=a||E;if(Y<1||Y>E)_=e,S.add(`Requested startLine ${Y} is out of range for this ${E}-line file \u2014 returning the full file instead of a range.`);else if(I<Y)_=e,S.add(`Requested range startLine=${Y}, endLine=${I} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let Re=Math.max(1,Y),Oe=Math.min(E,I),hn=k.slice(Re-1,Oe);w=Re,G=Oe,M=!0,_=hn.join(`
|
|
20
|
+
`),I>E&&S.add(`Requested endLine ${I} adjusted to ${E} (file end)`)}}let W=up.sanitizeContent(_,o);if(_=g?D.applyContentViewMinification(W.content,o):W.content,W.hasSecrets&&S.add(`Secrets detected and redacted: ${W.secretsDetected.join(", ")}`),W.warnings.length>0&&W.warnings.forEach(Y=>S.add(Y)),E>2e3&&m!=="symbols"&&!l&&!s&&!a&&!i){let Y=Math.max(1,E-200);S.add(`Large file (${E} lines) \u2014 minify:"symbols" for an export index, or startLine=${Y} for the tail.`)}let H=Array.from(S);return{owner:t,repo:n,path:o,content:_,contentView:y,branch:r,totalLines:E,..._i(p,h),...M&&{startLine:w,endLine:G,isPartial:M},...A&&{matchRanges:A},...H.length>0&&{matchLocations:H},...(H.length>0||b)&&{warnings:[...b?[b]:[],...H]}}}var dp=f(()=>{"use strict";Le();sr();lc();dc();Xb()});async function Zb(e,t,n){let r=await Ge(t),o=Te("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await Za(o,async({ifNoneMatch:g})=>{let y=await ki(e,t,{ifNoneMatch:g}),{etag:b,notModified:S,...C}=y;return{value:C,etag:b,notModified:S}},{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 Jb(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...l}=a,u=e.charOffset??0,d=e.charLength,m=e.fullContent===!0&&u===0&&d===void 0,p=c||m?l:await cp(l,u,d),h=(e.charOffset??0)>0;if(!e.noTimestamp&&!h)try{let g=await oe(t),y=await He(Te("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>lp(g,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});y&&(p.lastModified=y.lastModified,p.lastModifiedBy=y.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:i.rawResponseChars}}var pp=f(()=>{"use strict";Ae();lt();ac();dp()});function Fi(e,t=YA){let n=e?Oi(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function eR(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function tR(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:KA}):""}var KA,YA,Ii=f(()=>{"use strict";Le();sr();KA=2,YA=20});import{ContentSanitizer as nR}from"@octocodeai/octocode-engine/contentSanitizer";function mp(e){let t=nR.sanitizeContent(e.title??""),n=e.body?nR.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}}function oR(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 no(e,t={}){let n=t.charOffset??0,r=t.charLength??XA,o=t.charLength??JA,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=oR(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((h,g)=>{let y=h.commentType==="review_inline"?0:1,b=g.commentType==="review_inline"?0:1;return y-b}),c=a.filter(h=>h.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,rR),d=u.map(h=>{let g=oR(h.body,n,o,!t.includeFullCommentDetails);return{...h,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>u.length||d.some(h=>"body_pagination"in h)),p=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...m?[`PR comments are paginated/summarized to ${rR} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(h=>({id:0,name:h,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((h,g)=>h+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((h,g)=>h+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(h=>({filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,patch:h.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function Mi(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 Di(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?eR(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?tR(a.patch):a.patch}))}var XA,JA,rR,ar=f(()=>{"use strict";Ii();Le();vi();XA=Ln(),JA=Math.round(Ln()/4),rR=3});function ro(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function iR(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function yc(e){let t=iR(e);return t?t.discussion!==!1:!1}function bc(e){let t=iR(e);return t?t.reviewInline!==!1:!1}function Rc(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function Sc(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function fp(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:ro(e)||yc(e)||bc(e)||Rc(e)||Sc(e)}function hp(e){return!!e.content?.comments?.includeBots}function Pc(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()}var Pc=f(()=>{"use strict"});function cr(e){let t=e.toLowerCase();return t.endsWith("[bot]")||XA.has(t)}var XA,xc=f(()=>{"use strict";XA=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});async function Cc(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=Q(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function gp(e,t,n,r){let o=await oe(r),{items:i,rawResponseChars:s}=await Cc(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return V({total_count:i.length,files:i},s)}async function JA(e,t,n,r){let o=await oe(r),{items:i,rawResponseChars:s}=await Cc(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return V(i,s)}async function ZA(e,t,n,r){try{let i=await(await oe(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return V(i.data.files||[],i.data)}catch{return null}}async function tL(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 yp(e,t,n,r,o){let i=await JA(e,t,n,o);if(!i)return null;let s=ue(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await tL(a,eL,async l=>{let u=await ZA(e,t,l.sha,o),d=[];return u&&(s+=ue(u)??0,d=Mi(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}});return V(c,s)}var eL,bp=f(()=>{"use strict";Ae();ar();le();eL=5});import{ContentSanitizer as Rp}from"@octocodeai/octocode-engine/contentSanitizer";async function Sp(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=Q(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!cr(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(Sc(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Rp.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return u>0&&m.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:V(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:V([],0)}}}async function Pp(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Cc(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return V(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Rp.sanitizeContent(D.minifyMarkdownCore(Sc(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return V([],0)}}async function xp(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=Q(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!cr(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(Sc(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Rp.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return u>0&&m.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:V(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:V([],0)}}}var sR=f(()=>{"use strict";Le();xc();le();Pc();bp()});async function Cp(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=mp(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&fp(t))try{let{owner:l,repo:u}=Ii(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=Q(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,ro(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),ro(t))){let m=await gp(l,u,e.number);m&&(s+=ue(m)??0,m.files=Mi(m.files,t),o.file_changes=m)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=gc(t),c=yc(t);if(a||c){let{owner:l,repo:u}=Ii(t);if(l&&u){let d=hp(t),m=()=>Promise.resolve({comments:V([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([a?Sp(n,l,u,e.number,d):m(),c?xp(n,l,u,e.number,d):m()]);o.comments=[...p,...g],s+=(ue(p)??0)+(ue(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(Rc(t))try{let{owner:l,repo:u}=Ii(t);if(l&&u){let d=await Pp(n,l,u,e.number);s+=ue(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(bc(t))try{let{owner:l,repo:u}=Ii(t);if(l&&u){let d=await yp(l,u,e.number,t);d&&(s+=ue(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return V(o,s)}async function Di(e,t,n,r){let{prData:o,sanitizationWarnings:i}=mp(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,ro(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),ro(t))try{let d=await gp(a,c,e.number,r);d&&(s+=ue(d)??0,d.files=Mi(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=gc(t),u=yc(t);if(l||u){let d=hp(t),m=()=>Promise.resolve({comments:V([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([l?Sp(n,a,c,e.number,d):m(),u?xp(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(ue(p)??0)+(ue(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(Rc(t))try{let d=await Pp(n,a,c,e.number);s+=ue(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(bc(t))try{let d=await yp(a,c,e.number,t,r);d&&(s+=ue(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return V(o,s)}var aR=f(()=>{"use strict";ar();le();Pc();sR();bp()});var Ni=f(()=>{"use strict";Pc();aR()});function nL(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function l1(e,t,n){let r=await Ge(t),o=Te("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 wp(e,t),{shouldCache:s=>!s.error})}async function wp(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:Ke.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:Ke.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await oe(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Di(a,e,i,t);return{pull_requests:[no(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:Q(s.data)+(ue(c)??0)}}catch(i){let s=re(i);return nL(s,Ke.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"])}}var Tp=f(()=>{"use strict";st();Ae();tt();lt();ar();Ni();le()});function Ep(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function kp(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function cR(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 Di(m,t,e))),c=a.reduce((m,p)=>m+(ue(p)??0),0),l=a.map(m=>no(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:Q(s.data)+c}}catch(n){if(Ht(n))return kp(t);let r=re(n);return Ep(r,Ke.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var lR=f(()=>{"use strict";ce();st();tt();le();ar();Ni()});async function rL(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 oL(e,t,n="anon"){return Te("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function uR(e,t,n){let r=await Ge(t),o=oL(e,n,r);return await He(o,async()=>await iL(e,t,n),{shouldCache:s=>!s.error})}async function iL(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await wp(e,t);let r=await oe(t);if(!kd(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await cR(r,e);let i=await rL(r,e),s=Ed(i);if(!s)return{pull_requests:[],total_count:0,error:Ke.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),m=d.data.items?.filter(_=>!!_.pull_request)||[],p=await Promise.all(m.map(async _=>await Cp(_,i,r))),h=p.reduce((_,w)=>_+(ue(w)??0),0),g=p.map(_=>no(_,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),y=d.data.total_count,b=Math.min(y,1e3),S=Math.min(Math.ceil(b/c),10),C=Math.min(l,Math.max(1,S)),k=C<S,E=Math.min(b,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:C,totalPages:S,perPage:c,totalMatches:b,reportedTotalMatches:y,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:y>b,hasMore:k,...k?{nextPage:C+1}:{}},rawResponseChars:Q(d.data)+h}}catch(r){if(Ht(r))return kp(e);let o=re(r);return Ep(o,Ke.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var Op=f(()=>{"use strict";ce();st();Ae();tt();rr();lt();le();ar();Ni();Tp();lR()});function oo(e){return e?e.includes('rel="next"'):!1}async function aL(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}function dR(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}:{}}}}async function pR(e,t,n){let r=await Ge(t),o=Te("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,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,()=>cL(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function cL(e,t){try{let n=await oe(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=oo(i),a=o.data.map(u=>{let d=u.commit.author,m=u.commit.committer,p=m?.date??d?.date??"",h=u.commit.message,g=h.split(`
|
|
22
|
+
`).trim()}var xc=f(()=>{"use strict"});function cr(e){let t=e.toLowerCase();return t.endsWith("[bot]")||ZA.has(t)}var ZA,Cc=f(()=>{"use strict";ZA=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});async function wc(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=Q(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function gp(e,t,n,r){let o=await oe(r),{items:i,rawResponseChars:s}=await wc(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return V({total_count:i.length,files:i},s)}async function eL(e,t,n,r){let o=await oe(r),{items:i,rawResponseChars:s}=await wc(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return V(i,s)}async function tL(e,t,n,r){try{let i=await(await oe(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return V(i.data.files||[],i.data)}catch{return null}}async function rL(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 yp(e,t,n,r,o){let i=await eL(e,t,n,o);if(!i)return null;let s=ue(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await rL(a,nL,async l=>{let u=await tL(e,t,l.sha,o),d=[];return u&&(s+=ue(u)??0,d=Di(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}});return V(c,s)}var nL,bp=f(()=>{"use strict";Ae();ar();le();nL=5});import{ContentSanitizer as Rp}from"@octocodeai/octocode-engine/contentSanitizer";async function Sp(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=Q(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!cr(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(Pc(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Rp.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return u>0&&m.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:V(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:V([],0)}}}async function Pp(e,t,n,r){try{let{items:o,rawResponseChars:i}=await wc(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return V(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Rp.sanitizeContent(D.minifyMarkdownCore(Pc(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return V([],0)}}async function xp(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=Q(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!cr(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(Pc(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Rp.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return u>0&&m.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:V(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:V([],0)}}}var sR=f(()=>{"use strict";Le();Cc();le();xc();bp()});async function Cp(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=mp(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&fp(t))try{let{owner:l,repo:u}=Mi(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=Q(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,ro(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),ro(t))){let m=await gp(l,u,e.number);m&&(s+=ue(m)??0,m.files=Di(m.files,t),o.file_changes=m)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=yc(t),c=bc(t);if(a||c){let{owner:l,repo:u}=Mi(t);if(l&&u){let d=hp(t),m=()=>Promise.resolve({comments:V([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([a?Sp(n,l,u,e.number,d):m(),c?xp(n,l,u,e.number,d):m()]);o.comments=[...p,...g],s+=(ue(p)??0)+(ue(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(Sc(t))try{let{owner:l,repo:u}=Mi(t);if(l&&u){let d=await Pp(n,l,u,e.number);s+=ue(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(Rc(t))try{let{owner:l,repo:u}=Mi(t);if(l&&u){let d=await yp(l,u,e.number,t);d&&(s+=ue(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return V(o,s)}async function Ni(e,t,n,r){let{prData:o,sanitizationWarnings:i}=mp(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,ro(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),ro(t))try{let d=await gp(a,c,e.number,r);d&&(s+=ue(d)??0,d.files=Di(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=yc(t),u=bc(t);if(l||u){let d=hp(t),m=()=>Promise.resolve({comments:V([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([l?Sp(n,a,c,e.number,d):m(),u?xp(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(ue(p)??0)+(ue(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(Sc(t))try{let d=await Pp(n,a,c,e.number);s+=ue(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(Rc(t))try{let d=await yp(a,c,e.number,t,r);d&&(s+=ue(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return V(o,s)}var aR=f(()=>{"use strict";ar();le();xc();sR();bp()});var Gi=f(()=>{"use strict";xc();aR()});function oL(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function u1(e,t,n){let r=await Ge(t),o=Te("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 wp(e,t),{shouldCache:s=>!s.error})}async function wp(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:Ke.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:Ke.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await oe(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Ni(a,e,i,t);return{pull_requests:[no(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:Q(s.data)+(ue(c)??0)}}catch(i){let s=re(i);return oL(s,Ke.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"])}}var Tp=f(()=>{"use strict";st();Ae();tt();lt();ar();Gi();le()});function Ep(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function kp(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function cR(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 Ni(m,t,e))),c=a.reduce((m,p)=>m+(ue(p)??0),0),l=a.map(m=>no(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:Q(s.data)+c}}catch(n){if(Ht(n))return kp(t);let r=re(n);return Ep(r,Ke.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var lR=f(()=>{"use strict";ce();st();tt();le();ar();Gi()});async function iL(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 sL(e,t,n="anon"){return Te("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function uR(e,t,n){let r=await Ge(t),o=sL(e,n,r);return await He(o,async()=>await aL(e,t,n),{shouldCache:s=>!s.error})}async function aL(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await wp(e,t);let r=await oe(t);if(!kd(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await cR(r,e);let i=await iL(r,e),s=Ed(i);if(!s)return{pull_requests:[],total_count:0,error:Ke.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),m=d.data.items?.filter(_=>!!_.pull_request)||[],p=await Promise.all(m.map(async _=>await Cp(_,i,r))),h=p.reduce((_,w)=>_+(ue(w)??0),0),g=p.map(_=>no(_,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),y=d.data.total_count,b=Math.min(y,1e3),S=Math.min(Math.ceil(b/c),10),C=Math.min(l,Math.max(1,S)),k=C<S,E=Math.min(b,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:C,totalPages:S,perPage:c,totalMatches:b,reportedTotalMatches:y,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:y>b,hasMore:k,...k?{nextPage:C+1}:{}},rawResponseChars:Q(d.data)+h}}catch(r){if(Ht(r))return kp(e);let o=re(r);return Ep(o,Ke.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var Op=f(()=>{"use strict";ce();st();Ae();tt();rr();lt();le();ar();Gi();Tp();lR()});function oo(e){return e?e.includes('rel="next"'):!1}async function lL(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}function dR(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}:{}}}}async function pR(e,t,n){let r=await Ge(t),o=Te("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,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,()=>uL(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function uL(e,t){try{let n=await oe(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=oo(i),a=o.data.map(u=>{let d=u.commit.author,m=u.commit.committer,p=m?.date??d?.date??"",h=u.commit.message,g=h.split(`
|
|
23
23
|
`)[0]??h,y=h.slice(g.length).trim(),b=y.length>500,S=y.length===0?g:`${g}
|
|
24
|
-
${b?`${y.slice(0,500)}\u2026`:y}`,C=m?.name===d?.name&&m?.email===d?.email||u.committer?.login==="web-flow";return{sha:u.sha,date:p,...S===g?{}:{message:S},...b?{messageTruncated:!0}:{},messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...m&&!C?{committer:{name:m.name??"unknown",email:m.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await aL(a,sL,async(u,d)=>{try{let m=o.data[d]?.sha??u.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let h=e.path,g=p.data.files?.find(y=>y.filename===h||y.previous_filename===h);if(g){let y=g.patch!==void 0?dR(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...y!==void 0?{patch:y.patch,...y.patchPagination?{patchPagination:y.patchPagination}:{},diff:_i(y.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let h=e.path,g=(p.data.files??[]).filter(w=>!h||w.filename.startsWith(h)).map(w=>{let G=w.patch!==void 0?dR(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...G!==void 0?{patch:G.patch,...G.patchPagination?{patchPagination:G.patchPagination}:{},diff:_i(G.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),y=Math.max(1,e.filePage??1),b=Math.max(1,e.itemsPerPage??20),S=g.length,C=Math.max(1,Math.ceil(S/b)),k=Math.min(y,C),E=(k-1)*b,_=g.slice(E,E+b);return{...u,files:_,filesPagination:{currentPage:k,totalPages:C,itemsPerPage:b,totalFiles:S,hasMore:k<C,...k<C?{nextFilePage:k+1}:{}}}}}catch{}return u});return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return re(n)}}var sL,Gi=f(()=>{"use strict";Ae();tt();Fi();lt();sL=5});function fR(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 hR(e,t,n){let r=await Ge(t),o=e,i=Te("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await He(i,async()=>await uL(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function lL(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(p){if(p?.status!==404)return re(p);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return re(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),y=g[0]||"",b=g[1]||"";return{owner:y,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...fR(p)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:m,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:Q(i)}}async function uL(e,t){try{let n=await oe(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 lL({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=wd(e);if(!i.trim())return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||mR,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let k=S.full_name.split("/"),E=k[0]||"",_=k[1]||"";return{owner:E,repo:_,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...fR(S)}}),m=u.data.total_count,p=Math.min(m,1e3),h=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,h)),y=g<h,b=Math.min(p,h*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:h,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:y,...y?{nextPage:g+1}:{}}},status:200,headers:bi(u.headers),rawResponseChars:Q(u.data)}}catch(n){if(Ht(n)){let r=Math.min(e.limit||mR,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 re(n)}}var mR,vp=f(()=>{"use strict";Ae();tt();rr();lt();st();le();or();ce();mR=30});var _n,io=f(()=>{"use strict";_n={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function dL(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 pL(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 q1(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...dL(e.estimatedTokens,n)),o.push(...pL(e)),o}function wc(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Tc=f(()=>{"use strict"});function gR(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:M,...A}=e;return A}let r=t.itemsPerPage??_n.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,m=M=>{let A=M;d&&M.startsWith(d)&&(A=M.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let W=A.lastIndexOf("/");return W===-1?".":A.slice(0,W)},p=M=>{let A=M.lastIndexOf("/");return A===-1?M:M.slice(A+1)};for(let M of l){let A=m(M.path);u[A]||(u[A]={files:[],folders:[]});let W=p(M.path);M.type==="file"?u[A].files.push(W):u[A].folders.push(W)}for(let M of Object.keys(u)){let A=u[M];A&&(A.files.sort(),A.folders.sort())}let h=Object.create(null),g=Object.keys(u).sort((M,A)=>M==="."?-1:A==="."?1:M.localeCompare(A));for(let M of g){let A=u[M];A&&(h[M]=A)}let y=l.filter(M=>M.type==="file").length,b=l.filter(M=>M.type==="dir").length,S=n.filter(M=>M.type==="file").length,C=n.filter(M=>M.type==="dir").length,k=o<s,E={currentPage:o,totalPages:s,hasMore:k,...k?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=wc(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:y,pageFolders:b,allFiles:S,allFolders:C}),w,G=e._cachedFileSizeMap;if(G){let M=new Set(l.filter(H=>H.type==="file").map(H=>H.path)),A=e.path==="/"?"":e.path,W=Object.create(null);for(let[H,Y]of Object.entries(G))for(let[I,Re]of Object.entries(Y)){let Oe=H==="."?A?`${A}/${I}`:I:A?`${A}/${H}/${I}`:`${H}/${I}`;M.has(Oe)&&(W[H]||(W[H]=Object.create(null)),W[H][I]=Re)}Object.keys(W).length>0&&(w=W)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:C,truncated:k,filtered:!0,originalCount:i},structure:h,...w!==void 0&&{fileSizeMap:w},...G!==void 0&&{_cachedFileSizeMap:G},pagination:E,hints:_,rawResponseChars:e.rawResponseChars}}var Ap=f(()=>{"use strict";io();Tc()});import{RequestError as mL}from"octokit";function yR(e){return e instanceof mL&&fL.has(e.status)}function Lp(e,t){try{Object.defineProperty(e,bR,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Hi(e){if(typeof e!="object"||e===null)return 0;let t=e[bR];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Qi(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Lp(V([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(h){if(yR(h))throw h;return Lp(V([],0),1)}let l=Q(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(h=>h.type==="file"||h.type==="dir").map(h=>({name:h.name,path:h.path,type:h.type,size:"size"in h?h.size:void 0,download_url:"download_url"in h?h.download_url:void 0,url:h.url,html_url:h.html_url,git_url:h.git_url,sha:h.sha})),m=[...d],p=0;if(i<s){let h=d.filter(y=>y.type==="dir"),g=3;for(let y=0;y<h.length;y+=g){let b=h.slice(y,y+g),S=await Promise.allSettled(b.map(C=>Qi(e,t,n,r,C.path,i+1,s,a)));for(let C of S)if(C.status==="fulfilled"){let k=C.value;l+=ue(k)??0,p+=Hi(k),m.push(...k)}else{if(yR(C.reason))throw C.reason;p+=1}}}return Lp(V(m,l),p)}var bR,fL,_p=f(()=>{"use strict";le();bR=Symbol.for("octocode.recursiveFetchFailures"),fL=new Set([401,403,429])});import{RequestError as hL}from"octokit";function gL(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let l=a.lastIndexOf("/"),u=l===-1?a:a.slice(l+1);i.push({name:u,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function RR(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function SR(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 hL&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=Yr(o.headers);return{items:gL(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:Q(n)+Q(i),...s?{etag:s}:{}}}var PR=f(()=>{"use strict";le();or()});import{RequestError as xR}from"octokit";async function Fp(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Ye(t,n,i),a=c)}catch(l){let u=re(l);return{error:yn.NOT_FOUND.message(t,n,u.error),status:u.status}}try{let l=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),u=Yr(l.headers);return{data:l.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...u?{etag:u}:{}}}catch(l){if(l instanceof xR&&l.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(l instanceof xR&&l.status===404)){let d=re(l);return{error:yn.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let u=re(l);return{error:yn.PATH_NOT_FOUND.message(r,t,n,a),status:u.status}}}function CR(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}})}var wR=f(()=>{"use strict";tt();st();Ae();or()});function yL(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function TR(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 Ec(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:l,includeSizes:u,extraHints:d=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!yi(I.name):!Vr(I.path));m.sort((I,Re)=>{if(I.type!==Re.type)return I.type==="dir"?-1:1;let Oe=I.path.split("/").length,hn=Re.path.split("/").length;return Oe!==hn?Oe-hn:I.path.localeCompare(Re.path)});let p=e.itemsPerPage??_n.ENTRIES_PER_PAGE,h=e.page??1,g=m.length,y=Math.max(1,Math.ceil(g/p)),b=(h-1)*p,S=Math.min(b+p,g),C=m.slice(b,S),k=yL(C,i),E=u?TR(m,i):void 0,_=E!==void 0?TR(C,i):void 0,w=C.filter(I=>I.type==="file").length,G=C.filter(I=>I.type==="dir").length,M=m.filter(I=>I.type==="file").length,A=m.filter(I=>I.type==="dir").length,W=h<y,H={currentPage:h,totalPages:y,hasMore:W,...W?{nextPage:h+1}:{},entriesPerPage:p,totalEntries:g},Y=wc(H,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:w,pageFolders:G,allFiles:M,allFolders:A});a>0&&Y.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 d)Y.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:M,totalFolders:A,truncated:W,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:k,..._!==void 0&&{fileSizeMap:_},...E!==void 0&&{_cachedFileSizeMap:E},pagination:H,hints:Y,rawResponseChars:l,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}var ER=f(()=>{"use strict";io();Tc();Kr()});async function Ip(e,t,n){let r=await Ge(t),o=Te("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await Ja(o,async({ifNoneMatch:s})=>{let a=await bL({...e,itemsPerPage:e.itemsPerPage??_n.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?gR(i,e):i}async function bL(e,t,n){try{let r=await oe(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,l=a.replace(/^\/+|\/+$/g,"");if(c>1&&RR())return await RL(r,e,l,c,t,n);let u=await Fp(r,o,i,l,s,t,c===1?n:void 0);if("error"in u)return{result:u};if(u.notModified)return{result:{error:"not-modified",status:304},etag:u.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:h}=u,g=Q(d),y=Array.isArray(d)?d:[d],b=CR(y),S=0;if(c>1){let C=await Qi(r,o,i,m,l,1,c);S=Hi(C),g=ue(C)??0,b=C}return{result:Ec({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:l,depth:c,allItems:b,partialTreeFailures:S,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&h?{etag:h}:{}}}catch(r){let o=re(r);return{result:{error:yn.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function RL(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,l,u;try{c?l=c:(u=await Ye(s,a,o),l=u)}catch(b){let S=re(b);return{result:{error:yn.NOT_FOUND.message(s,a,S.error),status:S.status}}}let d;try{d=await SR(e,{owner:s,repo:a,workingBranch:l,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(b){let S=await Fp(e,s,a,n,l,o);if("error"in S)return{result:S};let C=await Qi(e,s,a,S.workingBranch,n,1,r);return{result:Ec({owner:s,repo:a,workingBranch:S.workingBranch,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:C,partialTreeFailures:Hi(C),incompleteTree:!1,rawResponseChars:ue(C)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${b instanceof Error?b.message:String(b)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,h=d.rawResponseChars,g=d.truncated,y=[];if(g){y.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let b=await Qi(e,s,a,l,n,1,r);p=Hi(b),h+=ue(b)??0,m=[...m,...b].filter((C,k,E)=>E.findIndex(_=>_.path===C.path)===k)}catch{}}return{result:Ec({owner:s,repo:a,workingBranch:l,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:h,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:y}),...d.etag&&!g?{etag:d.etag}:{}}}var kR=f(()=>{"use strict";io();Ae();tt();lt();st();le();Ap();_p();PR();wR();ER()});var Mp=f(()=>{"use strict";kR()});var OR,Dp=f(()=>{"use strict";OR={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});function Et(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function SL(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function PL(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")}var lr=f(()=>{"use strict"});function Ie(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 xL(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 en(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:xL(e)}}function kc(e){return CL(e)?en({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 CL(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||wL(n)}function wL(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var kt=f(()=>{"use strict"});function ji(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}:{}}}var Np=f(()=>{"use strict"});function TL(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,...ji(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function EL(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,...ji(e.pagination)},nonExistentScope:e.nonExistentScope}}async function vR(e,t,n=Ie){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 hb(s,t);return Et(a)?en(a):a.data?{data:TL(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function AR(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 hR(n,t);return"error"in r?kc(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:EL(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??Q(r.data)}}var Gp=f(()=>{"use strict";Fd();vp();lr();le();kt();kt();Np()});function OL(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:vL(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function vL(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 LR(e,t,n=Ie){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 Zb(i,t);if(Et(s))return en(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:OL(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s.data),...a?.length?{hints:a}:{}}}var Hp=f(()=>{"use strict";pp();lr();le();kt();kt()});function LL(e,t,n=Ie){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ji(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function _R(e,t,n=Ie){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await uR(s,t);return a.error?en({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:LL(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a)}}var Qp=f(()=>{"use strict";Op();le();kt();kt();Np()});function FL(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 FR(e,t,n=Ie){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ip(i,t);return"error"in s?kc(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:FL(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s)}}var jp=f(()=>{"use strict";Mp();le();kt();kt()});var Oc,Bp=f(()=>{"use strict";Gp();Hp();Qp();jp();tt();Ae();Dp();kt();Oc=class{type="github";capabilities=OR.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await vR(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await LR(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await AR(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await _R(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await FR(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Ie(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ye(n,r,this.authInfo)}handleError(t){let n=re(t);return en(n)}}});import{createHash as ML}from"crypto";function IR(e){return Date.now()-e.createdAt<DL}function NL(){for(let[e,t]of Ot.entries())IR(t)||Ot.delete(e);if(Ot.size>zp){let e=[...Ot.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Ot.size-zp;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ot.delete(r[0])}}}function GL(e){return e?ML("sha256").update(e).digest("hex").slice(0,16):"default"}function HL(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 QL(e,t){let n=HL(t?.baseUrl||"default"),r=GL(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Up(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=QL(e,t),r=Ot.get(n);if(r&&IR(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Ot.delete(n),Ot.size>=zp&&NL();let o=new Oc({...t,type:e}),i=Date.now();return Ot.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function sW(){Ot.clear()}async function MR(){try{return Up("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}]}}var
|
|
26
|
-
`}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:Fn({data:t,instructions:n})}],isError:!!r}}function vt(e){if(e==null)return e;if(typeof e=="string")return
|
|
24
|
+
${b?`${y.slice(0,500)}\u2026`:y}`,C=m?.name===d?.name&&m?.email===d?.email||u.committer?.login==="web-flow";return{sha:u.sha,date:p,...S===g?{}:{message:S},...b?{messageTruncated:!0}:{},messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...m&&!C?{committer:{name:m.name??"unknown",email:m.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await lL(a,cL,async(u,d)=>{try{let m=o.data[d]?.sha??u.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let h=e.path,g=p.data.files?.find(y=>y.filename===h||y.previous_filename===h);if(g){let y=g.patch!==void 0?dR(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...y!==void 0?{patch:y.patch,...y.patchPagination?{patchPagination:y.patchPagination}:{},diff:Fi(y.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let h=e.path,g=(p.data.files??[]).filter(w=>!h||w.filename.startsWith(h)).map(w=>{let G=w.patch!==void 0?dR(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...G!==void 0?{patch:G.patch,...G.patchPagination?{patchPagination:G.patchPagination}:{},diff:Fi(G.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),y=Math.max(1,e.filePage??1),b=Math.max(1,e.itemsPerPage??20),S=g.length,C=Math.max(1,Math.ceil(S/b)),k=Math.min(y,C),E=(k-1)*b,_=g.slice(E,E+b);return{...u,files:_,filesPagination:{currentPage:k,totalPages:C,itemsPerPage:b,totalFiles:S,hasMore:k<C,...k<C?{nextFilePage:k+1}:{}}}}}catch{}return u});return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return re(n)}}var cL,Hi=f(()=>{"use strict";Ae();tt();Ii();lt();cL=5});function fR(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 hR(e,t,n){let r=await Ge(t),o=e,i=Te("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await He(i,async()=>await pL(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function dL(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(p){if(p?.status!==404)return re(p);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return re(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),y=g[0]||"",b=g[1]||"";return{owner:y,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...fR(p)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:m,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:Q(i)}}async function pL(e,t){try{let n=await oe(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 dL({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=wd(e);if(!i.trim())return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||mR,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let k=S.full_name.split("/"),E=k[0]||"",_=k[1]||"";return{owner:E,repo:_,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...fR(S)}}),m=u.data.total_count,p=Math.min(m,1e3),h=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,h)),y=g<h,b=Math.min(p,h*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:h,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:y,...y?{nextPage:g+1}:{}}},status:200,headers:Ri(u.headers),rawResponseChars:Q(u.data)}}catch(n){if(Ht(n)){let r=Math.min(e.limit||mR,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 re(n)}}var mR,vp=f(()=>{"use strict";Ae();tt();rr();lt();st();le();or();ce();mR=30});var _n,io=f(()=>{"use strict";_n={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function mL(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 fL(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 W1(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...mL(e.estimatedTokens,n)),o.push(...fL(e)),o}function Tc(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Ec=f(()=>{"use strict"});function gR(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:M,...A}=e;return A}let r=t.itemsPerPage??_n.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,m=M=>{let A=M;d&&M.startsWith(d)&&(A=M.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let W=A.lastIndexOf("/");return W===-1?".":A.slice(0,W)},p=M=>{let A=M.lastIndexOf("/");return A===-1?M:M.slice(A+1)};for(let M of l){let A=m(M.path);u[A]||(u[A]={files:[],folders:[]});let W=p(M.path);M.type==="file"?u[A].files.push(W):u[A].folders.push(W)}for(let M of Object.keys(u)){let A=u[M];A&&(A.files.sort(),A.folders.sort())}let h=Object.create(null),g=Object.keys(u).sort((M,A)=>M==="."?-1:A==="."?1:M.localeCompare(A));for(let M of g){let A=u[M];A&&(h[M]=A)}let y=l.filter(M=>M.type==="file").length,b=l.filter(M=>M.type==="dir").length,S=n.filter(M=>M.type==="file").length,C=n.filter(M=>M.type==="dir").length,k=o<s,E={currentPage:o,totalPages:s,hasMore:k,...k?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=Tc(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:y,pageFolders:b,allFiles:S,allFolders:C}),w,G=e._cachedFileSizeMap;if(G){let M=new Set(l.filter(H=>H.type==="file").map(H=>H.path)),A=e.path==="/"?"":e.path,W=Object.create(null);for(let[H,Y]of Object.entries(G))for(let[I,Re]of Object.entries(Y)){let Oe=H==="."?A?`${A}/${I}`:I:A?`${A}/${H}/${I}`:`${H}/${I}`;M.has(Oe)&&(W[H]||(W[H]=Object.create(null)),W[H][I]=Re)}Object.keys(W).length>0&&(w=W)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:C,truncated:k,filtered:!0,originalCount:i},structure:h,...w!==void 0&&{fileSizeMap:w},...G!==void 0&&{_cachedFileSizeMap:G},pagination:E,hints:_,rawResponseChars:e.rawResponseChars}}var Ap=f(()=>{"use strict";io();Ec()});import{RequestError as hL}from"octokit";function yR(e){return e instanceof hL&&gL.has(e.status)}function Lp(e,t){try{Object.defineProperty(e,bR,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Qi(e){if(typeof e!="object"||e===null)return 0;let t=e[bR];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function ji(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Lp(V([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(h){if(yR(h))throw h;return Lp(V([],0),1)}let l=Q(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(h=>h.type==="file"||h.type==="dir").map(h=>({name:h.name,path:h.path,type:h.type,size:"size"in h?h.size:void 0,download_url:"download_url"in h?h.download_url:void 0,url:h.url,html_url:h.html_url,git_url:h.git_url,sha:h.sha})),m=[...d],p=0;if(i<s){let h=d.filter(y=>y.type==="dir"),g=3;for(let y=0;y<h.length;y+=g){let b=h.slice(y,y+g),S=await Promise.allSettled(b.map(C=>ji(e,t,n,r,C.path,i+1,s,a)));for(let C of S)if(C.status==="fulfilled"){let k=C.value;l+=ue(k)??0,p+=Qi(k),m.push(...k)}else{if(yR(C.reason))throw C.reason;p+=1}}}return Lp(V(m,l),p)}var bR,gL,_p=f(()=>{"use strict";le();bR=Symbol.for("octocode.recursiveFetchFailures"),gL=new Set([401,403,429])});import{RequestError as yL}from"octokit";function bL(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let l=a.lastIndexOf("/"),u=l===-1?a:a.slice(l+1);i.push({name:u,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function RR(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function SR(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 yL&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=Yr(o.headers);return{items:bL(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:Q(n)+Q(i),...s?{etag:s}:{}}}var PR=f(()=>{"use strict";le();or()});import{RequestError as xR}from"octokit";async function Fp(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Ye(t,n,i),a=c)}catch(l){let u=re(l);return{error:yn.NOT_FOUND.message(t,n,u.error),status:u.status}}try{let l=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),u=Yr(l.headers);return{data:l.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...u?{etag:u}:{}}}catch(l){if(l instanceof xR&&l.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(l instanceof xR&&l.status===404)){let d=re(l);return{error:yn.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let u=re(l);return{error:yn.PATH_NOT_FOUND.message(r,t,n,a),status:u.status}}}function CR(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}})}var wR=f(()=>{"use strict";tt();st();Ae();or()});function RL(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function TR(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 kc(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:l,includeSizes:u,extraHints:d=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!bi(I.name):!Vr(I.path));m.sort((I,Re)=>{if(I.type!==Re.type)return I.type==="dir"?-1:1;let Oe=I.path.split("/").length,hn=Re.path.split("/").length;return Oe!==hn?Oe-hn:I.path.localeCompare(Re.path)});let p=e.itemsPerPage??_n.ENTRIES_PER_PAGE,h=e.page??1,g=m.length,y=Math.max(1,Math.ceil(g/p)),b=(h-1)*p,S=Math.min(b+p,g),C=m.slice(b,S),k=RL(C,i),E=u?TR(m,i):void 0,_=E!==void 0?TR(C,i):void 0,w=C.filter(I=>I.type==="file").length,G=C.filter(I=>I.type==="dir").length,M=m.filter(I=>I.type==="file").length,A=m.filter(I=>I.type==="dir").length,W=h<y,H={currentPage:h,totalPages:y,hasMore:W,...W?{nextPage:h+1}:{},entriesPerPage:p,totalEntries:g},Y=Tc(H,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:w,pageFolders:G,allFiles:M,allFolders:A});a>0&&Y.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 d)Y.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:M,totalFolders:A,truncated:W,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:k,..._!==void 0&&{fileSizeMap:_},...E!==void 0&&{_cachedFileSizeMap:E},pagination:H,hints:Y,rawResponseChars:l,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}var ER=f(()=>{"use strict";io();Ec();Kr()});async function Ip(e,t,n){let r=await Ge(t),o=Te("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await Za(o,async({ifNoneMatch:s})=>{let a=await SL({...e,itemsPerPage:e.itemsPerPage??_n.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?gR(i,e):i}async function SL(e,t,n){try{let r=await oe(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,l=a.replace(/^\/+|\/+$/g,"");if(c>1&&RR())return await PL(r,e,l,c,t,n);let u=await Fp(r,o,i,l,s,t,c===1?n:void 0);if("error"in u)return{result:u};if(u.notModified)return{result:{error:"not-modified",status:304},etag:u.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:h}=u,g=Q(d),y=Array.isArray(d)?d:[d],b=CR(y),S=0;if(c>1){let C=await ji(r,o,i,m,l,1,c);S=Qi(C),g=ue(C)??0,b=C}return{result:kc({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:l,depth:c,allItems:b,partialTreeFailures:S,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&h?{etag:h}:{}}}catch(r){let o=re(r);return{result:{error:yn.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function PL(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,l,u;try{c?l=c:(u=await Ye(s,a,o),l=u)}catch(b){let S=re(b);return{result:{error:yn.NOT_FOUND.message(s,a,S.error),status:S.status}}}let d;try{d=await SR(e,{owner:s,repo:a,workingBranch:l,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(b){let S=await Fp(e,s,a,n,l,o);if("error"in S)return{result:S};let C=await ji(e,s,a,S.workingBranch,n,1,r);return{result:kc({owner:s,repo:a,workingBranch:S.workingBranch,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:C,partialTreeFailures:Qi(C),incompleteTree:!1,rawResponseChars:ue(C)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${b instanceof Error?b.message:String(b)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,h=d.rawResponseChars,g=d.truncated,y=[];if(g){y.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let b=await ji(e,s,a,l,n,1,r);p=Qi(b),h+=ue(b)??0,m=[...m,...b].filter((C,k,E)=>E.findIndex(_=>_.path===C.path)===k)}catch{}}return{result:kc({owner:s,repo:a,workingBranch:l,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:h,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:y}),...d.etag&&!g?{etag:d.etag}:{}}}var kR=f(()=>{"use strict";io();Ae();tt();lt();st();le();Ap();_p();PR();wR();ER()});var Mp=f(()=>{"use strict";kR()});var OR,Dp=f(()=>{"use strict";OR={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});function Et(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function xL(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function CL(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")}var lr=f(()=>{"use strict"});function Ie(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 wL(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 en(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:wL(e)}}function Oc(e){return TL(e)?en({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 TL(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||EL(n)}function EL(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var kt=f(()=>{"use strict"});function Bi(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}:{}}}var Np=f(()=>{"use strict"});function kL(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,...Bi(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function OL(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,...Bi(e.pagination)},nonExistentScope:e.nonExistentScope}}async function vR(e,t,n=Ie){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 hb(s,t);return Et(a)?en(a):a.data?{data:kL(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function AR(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 hR(n,t);return"error"in r?Oc(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:OL(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??Q(r.data)}}var Gp=f(()=>{"use strict";Fd();vp();lr();le();kt();kt();Np()});function AL(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:LL(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function LL(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 LR(e,t,n=Ie){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 Zb(i,t);if(Et(s))return en(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:AL(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s.data),...a?.length?{hints:a}:{}}}var Hp=f(()=>{"use strict";pp();lr();le();kt();kt()});function FL(e,t,n=Ie){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Bi(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function _R(e,t,n=Ie){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await uR(s,t);return a.error?en({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:FL(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a)}}var Qp=f(()=>{"use strict";Op();le();kt();kt();Np()});function ML(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 FR(e,t,n=Ie){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ip(i,t);return"error"in s?Oc(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:ML(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s)}}var jp=f(()=>{"use strict";Mp();le();kt();kt()});var vc,Bp=f(()=>{"use strict";Gp();Hp();Qp();jp();tt();Ae();Dp();kt();vc=class{type="github";capabilities=OR.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await vR(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await LR(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await AR(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await _R(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await FR(t,this.authInfo,Ie)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Ie(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ye(n,r,this.authInfo)}handleError(t){let n=re(t);return en(n)}}});import{createHash as NL}from"crypto";function IR(e){return Date.now()-e.createdAt<GL}function HL(){for(let[e,t]of Ot.entries())IR(t)||Ot.delete(e);if(Ot.size>zp){let e=[...Ot.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Ot.size-zp;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ot.delete(r[0])}}}function QL(e){return e?NL("sha256").update(e).digest("hex").slice(0,16):"default"}function jL(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 BL(e,t){let n=jL(t?.baseUrl||"default"),r=QL(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Up(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=BL(e,t),r=Ot.get(n);if(r&&IR(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Ot.delete(n),Ot.size>=zp&&HL();let o=new vc({...t,type:e}),i=Date.now();return Ot.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function aW(){Ot.clear()}async function MR(){try{return Up("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}]}}var GL,zp,Ot,Ac=f(()=>{"use strict";Bp();GL=3600*1e3,zp=20,Ot=new Map});import{ContentSanitizer as zL}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as UL}from"@octocodeai/config";function $L(){try{return UL().output.format}catch{return"yaml"}}function pW(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:Fn({data:t,instructions:n})}],isError:!!r}}function vt(e){if(e==null)return e;if(typeof e=="string")return zL.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>vt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=vt(r);return t}return e}function mW(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 Fn(e,t){let n=ur(e)??{},r=vt(n),o=zL(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ac(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Ac(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ac(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ac(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ac(n[o],t));return r}function qL(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=>UL.has(r))||$L.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 ur(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=>ur(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(qL(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=ur(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var UL,$L,so=f(()=>{"use strict";Le();UL=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"]),$L=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});import{z as Lc}from"zod";function z(e,t){return Lc.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Lc.number().int().min(e).max(t))}function ge(e,t={}){let{maxQueries:n=5}=t;return Lc.object({queries:Lc.array(e).min(1).max(n).describe("Parallel queries."),...WL}).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))})})}var Pe,ao,co,WL,nt=f(()=>{"use strict";ce();Pe=z(1,1e3).optional().default(1),ao=z(0,100).optional(),co=z(1,1e9).optional(),WL={responseCharOffset:z(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:z(1,5e4).optional().describe("Full-response char window.")}});import{z as U}from"zod";function Fc(e,t,n="Continue to the next page of results."){return{tool:e,query:t,why:n,confidence:"exact"}}function Ic(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 ut,_c,xe,In,lo,qe=f(()=>{"use strict";ut=U.object({currentPage:U.number(),totalPages:U.number(),hasMore:U.boolean(),nextPage:U.number().optional(),pageSize:U.number().optional(),totalItems:U.number().optional(),perPage:U.number().optional(),totalFound:U.number().optional(),returned:U.number().optional(),totalMatches:U.number().optional(),reportedTotalMatches:U.number().optional(),reachableTotalMatches:U.number().optional(),totalMatchesKind:U.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:U.boolean().optional(),totalResults:U.number().optional(),itemsPerPage:U.number().optional()}),_c=U.object({charOffset:U.number(),charLength:U.number(),totalChars:U.number(),hasMore:U.boolean(),nextCharOffset:U.number().optional(),currentPage:U.number().optional(),totalPages:U.number().optional(),chunkMode:U.enum(["semantic","char-limit"]).optional()}),xe=U.object({tool:U.string(),query:U.record(U.string(),U.unknown()),why:U.string().optional(),confidence:U.enum(["exact","heuristic"]).optional()}),In=ut.extend({filesPerPage:U.number().optional(),entriesPerPage:U.number().optional(),matchesPerPage:U.number().optional(),totalFiles:U.number().optional(),totalEntries:U.number().optional(),totalMatches:U.number().optional(),totalFilesFound:U.number().optional(),nextMatchPage:U.number().optional()});lo=U.object({level:U.enum(["info","warning","error"]),message:U.string(),field:U.string().optional(),code:U.string().optional()})});import{z as ye}from"zod";function PW(e){return e.extend(We)}function KL(e){return ye.object({id:ye.string(),status:ye.enum(["empty","error"]).optional(),data:e,diagnostics:ye.array(lo).optional(),next:ye.record(ye.string(),xe).optional()})}var VL,We,xW,Mn,dt=f(()=>{"use strict";qe();VL=ye.object({currentPage:ye.number(),totalPages:ye.number(),hasMore:ye.boolean(),charOffset:ye.number(),charLength:ye.number(),totalChars:ye.number(),nextCharOffset:ye.number().optional()}).optional(),We={base:ye.string().optional(),shared:ye.record(ye.string(),ye.union([ye.string(),ye.number(),ye.boolean()])).optional(),responsePagination:VL};xW=KL(ye.record(ye.string(),ye.unknown()).optional()),Mn=We});function YL(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function N(e,t,n={}){let{extra:r}=n,o={status:"error"};if(YL(e))o.error=e;else if(Du(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Ng(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:V(o,n.rawResponse)}function pt(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:N(i,t,{toolName:n.toolName})}}var Mc=f(()=>{"use strict";Vo();le()});async function vW(e,t,n){if(e)try{await e(t,n)}catch{return}}function Ee(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:V(s,o.rawResponse)}function Dc(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return N(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Ve(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return N(i,t,{toolName:r})}var Me=f(()=>{"use strict";Mc();le()});async function ht({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Ve(o,t,r,e)}}var Dn=f(()=>{"use strict";Me()});function Nc(e={},t=Bi){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}var FW,Bi,uo,DR,$p=f(()=>{"use strict";FW=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Bi=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],uo=[...Bi,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],DR=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"]});import{spawn as qp}from"child_process";function tn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Bi,maxOutputSize:a=XL}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),m={cwd:o,env:Nc(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=qp(e,t,m)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let h,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Wp),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),y=()=>{clearTimeout(g),h!==void 0&&(clearTimeout(h),h=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",S=>{if(l.killed)return;let C=S.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stdoutChunks.push(C)}),p.stderr?.on("data",S=>{if(l.killed)return;let C=S.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stderrChunks.push(C)}),p.on("close",S=>{l.killed||(y(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),p.on("error",S=>{l.killed||(l.killed=!0,y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function NR(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Bi}=r,a;try{a=qp(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Nc({},s)})}catch{o(!1);return}let c,l=()=>{clearTimeout(u),c!==void 0&&(clearTimeout(c),c=void 0)},u=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Wp),o(!1)}},n);a.on("close",d=>{l(),i||o(d===0)}),a.on("error",()=>{l(),i||o(!1)})})}function HW(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=uo,maxOutputSize:l=JL}=r,u;try{u=qp(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Nc({},c)})}catch{o(null);return}let d,m=()=>{clearTimeout(p),d!==void 0&&(clearTimeout(d),d=void 0)};u.stdout?.on("data",h=>{if(i)return;let g=h.toString();if(a+=Buffer.byteLength(g),a>l){if(!i){i=!0;try{u.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(g)}),u.stderr?.on("data",()=>{});let p=setTimeout(()=>{if(!i){i=!0;try{u.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},Wp),o(null)}},n);u.on("close",h=>{if(m(),!i)if(h===0){let g=s.join("").trim();o(g||null)}else o(null)}),u.on("error",()=>{m(),i||o(null)})})}function Gc(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 XL,Wp,JL,GR=f(()=>{"use strict";$p();XL=10*1024*1024,Wp=5e3;JL=1*1024*1024});var po=f(()=>{"use strict";$p();GR()});import{existsSync as ZL,mkdirSync as Vp,renameSync as e_,rmSync as t_}from"fs";import{join as zi}from"path";import{createHash as n_}from"crypto";async function BR(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await h_();let a=e.branch??await Ye(r,o,t),c=Jn(),l=Gd(c,r,o,a,i);return a_(c,l,async()=>{let u=eo(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};rc(c),An(l);let d=f_(t,n),m=l_(c,l);oc(m);try{if(i){if(await m_(r,o,a,m,i,d),!ZL(zi(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 p_(r,o,a,m,d);let p=to(r,o,a,"clone",i);return Zr(m,p),u_(m,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw oc(m),p}})}async function a_(e,t,n){An(t);let r=c_(e,t);Vp(zi(e,"tmp",QR),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Vp(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>o_)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await d_(i_)}try{return await n()}finally{t_(r,{recursive:!0,force:!0})}}function zR(e){return n_("sha256").update(e).digest("hex").slice(0,16)}function c_(e,t){return zi(e,"tmp",QR,zR(t))}function l_(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=zi(e,"tmp",s_);return Vp(r,{recursive:!0,mode:448}),zi(r,`${zR(t)}-${n}`)}function u_(e,t){oc(t),An(t),e_(e,t)}function d_(e){return new Promise(t=>setTimeout(t,e))}async function p_(e,t,n,r,o){let i=$R(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",UR(e,t),r),await Kp(i,HR,`full clone of ${e}/${t}`,o)}async function m_(e,t,n,r,o,i){let s=$R(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",UR(e,t),r),await Kp(s,HR,`sparse clone of ${e}/${t}`,i),await Kp(["-C",r,"sparse-checkout","set","--skip-checks","--",o],r_,`sparse-checkout set ${o}`,void 0)}function UR(e,t){return`https://github.com/${e}/${t}.git`}function $R(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function f_(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function h_(){try{if(!(await tn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:jR,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 g_(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 Kp(e,t,n,r){let o=await tn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:jR,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=g_(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var HR,r_,o_,i_,QR,s_,jR,Yp=f(()=>{"use strict";Nt();Ae();po();Ti();HR=120*1e3,r_=30*1e3,o_=300*1e3,i_=100,QR="clone-locks",s_="clone-tmp",jR=[...uo,"GIT_TERMINAL_PROMPT"]});async function qR(e,t={}){if(!Array.isArray(e))throw new Error($o.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($o.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error($o.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Wo.NOT_A_FUNCTION.message(l))));if(r<i.length)return y_(i,r,n,o);let s=i.map((c,l)=>WR(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function WR(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Wo.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 y_(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Wo.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await WR(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Xp=f(()=>{"use strict";st()});function KR(e,t,n){if(e<=1)return VR;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(b_/o),s=Math.max(R_,Math.min(i,VR));return n?Math.max(s,n):s}async function YR(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await qR(s,{timeout:KR(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function Ui(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 $i(e){let t=new Set;return e.map((n,r)=>{let o=Ui(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}var VR,b_,R_,Jp=f(()=>{"use strict";Xp();VR=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,b_=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,R_=5e3});function S_(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):""}function Zp(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Zp(o,t,n+1);return}let r=e;for(let o of em){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))XR.has(o)||i&&typeof i=="object"&&Zp(i,t,n+1)}function Hc(e){let t=[];for(let i of e)Zp(i?.data,t,0);if(t.length===0)return;let n=S_(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return P_(e,r),n}function P_(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(XR.has(s))continue;let a=i[s];typeof a=="string"?!em.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function x_(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"}function Qc(e){let t=x_(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(w_.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}var em,XR,w_,jc=f(()=>{"use strict";em=["path","uri"],XR=new Set(["next","location"]);w_=new Set([...em,"owner","repo","name","id"])});function tm(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
|
|
28
|
+
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Fn(e,t){let n=ur(e)??{},r=vt(n),o=$L(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Lc(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Lc(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Lc(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Lc(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Lc(n[o],t));return r}function VL(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=>qL.has(r))||WL.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 ur(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=>ur(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(VL(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=ur(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var qL,WL,so=f(()=>{"use strict";Le();qL=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"]),WL=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});import{z as _c}from"zod";function z(e,t){return _c.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,_c.number().int().min(e).max(t))}function ge(e,t={}){let{maxQueries:n=5}=t;return _c.object({queries:_c.array(e).min(1).max(n).describe("Parallel queries."),...KL}).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))})})}var Pe,ao,co,KL,nt=f(()=>{"use strict";ce();Pe=z(1,1e3).optional().default(1),ao=z(0,100).optional(),co=z(1,1e9).optional(),KL={responseCharOffset:z(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:z(1,5e4).optional().describe("Full-response char window.")}});import{z as U}from"zod";function Fc(e,t,n="Continue to the next page of results."){return{tool:e,query:t,why:n,confidence:"exact"}}function Ic(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 ut,lo,xe,In,uo,qe=f(()=>{"use strict";ut=U.object({currentPage:U.number(),totalPages:U.number(),hasMore:U.boolean(),nextPage:U.number().optional(),pageSize:U.number().optional(),totalItems:U.number().optional(),perPage:U.number().optional(),totalFound:U.number().optional(),returned:U.number().optional(),totalMatches:U.number().optional(),reportedTotalMatches:U.number().optional(),reachableTotalMatches:U.number().optional(),totalMatchesKind:U.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:U.boolean().optional(),totalResults:U.number().optional(),itemsPerPage:U.number().optional()}),lo=U.object({charOffset:U.number(),charLength:U.number(),totalChars:U.number(),hasMore:U.boolean(),nextCharOffset:U.number().optional(),currentPage:U.number().optional(),totalPages:U.number().optional(),chunkMode:U.enum(["semantic","char-limit"]).optional()}),xe=U.object({tool:U.string(),query:U.record(U.string(),U.unknown()),why:U.string().optional(),confidence:U.enum(["exact","heuristic"]).optional()}),In=ut.extend({filesPerPage:U.number().optional(),entriesPerPage:U.number().optional(),matchesPerPage:U.number().optional(),totalFiles:U.number().optional(),totalEntries:U.number().optional(),totalMatches:U.number().optional(),totalFilesFound:U.number().optional(),nextMatchPage:U.number().optional()});uo=U.object({level:U.enum(["info","warning","error"]),message:U.string(),field:U.string().optional(),code:U.string().optional()})});import{z as ye}from"zod";function xW(e){return e.extend(We)}function XL(e){return ye.object({id:ye.string(),status:ye.enum(["empty","error"]).optional(),data:e,diagnostics:ye.array(uo).optional(),next:ye.record(ye.string(),xe).optional()})}var YL,We,CW,Mn,dt=f(()=>{"use strict";qe();YL=ye.object({currentPage:ye.number(),totalPages:ye.number(),hasMore:ye.boolean(),charOffset:ye.number(),charLength:ye.number(),totalChars:ye.number(),nextCharOffset:ye.number().optional()}).optional(),We={base:ye.string().optional(),shared:ye.record(ye.string(),ye.union([ye.string(),ye.number(),ye.boolean()])).optional(),responsePagination:YL};CW=XL(ye.record(ye.string(),ye.unknown()).optional()),Mn=We});function JL(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function N(e,t,n={}){let{extra:r}=n,o={status:"error"};if(JL(e))o.error=e;else if(Du(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Ng(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:V(o,n.rawResponse)}function pt(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:N(i,t,{toolName:n.toolName})}}var Mc=f(()=>{"use strict";Ko();le()});async function AW(e,t,n){if(e)try{await e(t,n)}catch{return}}function Ee(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:V(s,o.rawResponse)}function Dc(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return N(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Ve(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return N(i,t,{toolName:r})}var Me=f(()=>{"use strict";Mc();le()});async function ht({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Ve(o,t,r,e)}}var Dn=f(()=>{"use strict";Me()});function Nc(e={},t=zi){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}var IW,zi,po,DR,$p=f(()=>{"use strict";IW=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],zi=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],po=[...zi,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],DR=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"]});import{spawn as qp}from"child_process";function tn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=zi,maxOutputSize:a=ZL}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),m={cwd:o,env:Nc(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=qp(e,t,m)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let h,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Wp),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),y=()=>{clearTimeout(g),h!==void 0&&(clearTimeout(h),h=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",S=>{if(l.killed)return;let C=S.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stdoutChunks.push(C)}),p.stderr?.on("data",S=>{if(l.killed)return;let C=S.toString();l.totalOutputSize+=Buffer.byteLength(C),!b()&&l.stderrChunks.push(C)}),p.on("close",S=>{l.killed||(y(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),p.on("error",S=>{l.killed||(l.killed=!0,y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function NR(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=zi}=r,a;try{a=qp(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Nc({},s)})}catch{o(!1);return}let c,l=()=>{clearTimeout(u),c!==void 0&&(clearTimeout(c),c=void 0)},u=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Wp),o(!1)}},n);a.on("close",d=>{l(),i||o(d===0)}),a.on("error",()=>{l(),i||o(!1)})})}function QW(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=po,maxOutputSize:l=e_}=r,u;try{u=qp(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Nc({},c)})}catch{o(null);return}let d,m=()=>{clearTimeout(p),d!==void 0&&(clearTimeout(d),d=void 0)};u.stdout?.on("data",h=>{if(i)return;let g=h.toString();if(a+=Buffer.byteLength(g),a>l){if(!i){i=!0;try{u.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(g)}),u.stderr?.on("data",()=>{});let p=setTimeout(()=>{if(!i){i=!0;try{u.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},Wp),o(null)}},n);u.on("close",h=>{if(m(),!i)if(h===0){let g=s.join("").trim();o(g||null)}else o(null)}),u.on("error",()=>{m(),i||o(null)})})}function Gc(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 ZL,Wp,e_,GR=f(()=>{"use strict";$p();ZL=10*1024*1024,Wp=5e3;e_=1*1024*1024});var mo=f(()=>{"use strict";$p();GR()});import{existsSync as t_,mkdirSync as Vp,renameSync as n_,rmSync as r_}from"fs";import{join as Ui}from"path";import{createHash as o_}from"crypto";async function BR(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await y_();let a=e.branch??await Ye(r,o,t),c=Jn(),l=Gd(c,r,o,a,i);return l_(c,l,async()=>{let u=eo(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};oc(c),An(l);let d=g_(t,n),m=d_(c,l);ic(m);try{if(i){if(await h_(r,o,a,m,i,d),!t_(Ui(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 f_(r,o,a,m,d);let p=to(r,o,a,"clone",i);return Zr(m,p),p_(m,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw ic(m),p}})}async function l_(e,t,n){An(t);let r=u_(e,t);Vp(Ui(e,"tmp",QR),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Vp(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>s_)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await m_(a_)}try{return await n()}finally{r_(r,{recursive:!0,force:!0})}}function zR(e){return o_("sha256").update(e).digest("hex").slice(0,16)}function u_(e,t){return Ui(e,"tmp",QR,zR(t))}function d_(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Ui(e,"tmp",c_);return Vp(r,{recursive:!0,mode:448}),Ui(r,`${zR(t)}-${n}`)}function p_(e,t){ic(t),An(t),n_(e,t)}function m_(e){return new Promise(t=>setTimeout(t,e))}async function f_(e,t,n,r,o){let i=$R(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",UR(e,t),r),await Kp(i,HR,`full clone of ${e}/${t}`,o)}async function h_(e,t,n,r,o,i){let s=$R(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",UR(e,t),r),await Kp(s,HR,`sparse clone of ${e}/${t}`,i),await Kp(["-C",r,"sparse-checkout","set","--skip-checks","--",o],i_,`sparse-checkout set ${o}`,void 0)}function UR(e,t){return`https://github.com/${e}/${t}.git`}function $R(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function g_(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function y_(){try{if(!(await tn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:jR,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 b_(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 Kp(e,t,n,r){let o=await tn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:jR,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=b_(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var HR,i_,s_,a_,QR,c_,jR,Yp=f(()=>{"use strict";Nt();Ae();mo();Ei();HR=120*1e3,i_=30*1e3,s_=300*1e3,a_=100,QR="clone-locks",c_="clone-tmp",jR=[...po,"GIT_TERMINAL_PROMPT"]});async function qR(e,t={}){if(!Array.isArray(e))throw new Error(qo.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(qo.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(qo.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Vo.NOT_A_FUNCTION.message(l))));if(r<i.length)return R_(i,r,n,o);let s=i.map((c,l)=>WR(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function WR(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Vo.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 R_(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Vo.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await WR(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Xp=f(()=>{"use strict";st()});function KR(e,t,n){if(e<=1)return VR;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(S_/o),s=Math.max(P_,Math.min(i,VR));return n?Math.max(s,n):s}async function YR(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await qR(s,{timeout:KR(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function $i(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 qi(e){let t=new Set;return e.map((n,r)=>{let o=$i(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}var VR,S_,P_,Jp=f(()=>{"use strict";Xp();VR=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,S_=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,P_=5e3});function x_(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):""}function Zp(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Zp(o,t,n+1);return}let r=e;for(let o of em){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))XR.has(o)||i&&typeof i=="object"&&Zp(i,t,n+1)}function Hc(e){let t=[];for(let i of e)Zp(i?.data,t,0);if(t.length===0)return;let n=x_(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return C_(e,r),n}function C_(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(XR.has(s))continue;let a=i[s];typeof a=="string"?!em.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function w_(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 T_(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function Qc(e){let t=w_(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(E_.has(i))continue;let s=n[i];T_(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var em,XR,E_,jc=f(()=>{"use strict";em=["path","uri"],XR=new Set(["next","location"]);E_=new Set([...em,"owner","repo","name","id"])});function tm(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 k_(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=tm(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function O_(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=tm(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 nm(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=tm(e,s,i),c=a<o,l=k_(e,s,i),u=O_(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
|
|
30
30
|
`:`# Response page ${l}/${u}.
|
|
31
|
-
`}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function rm(e,t){return t?{...e,responsePagination:t}:e}var JR=f(()=>{"use strict"});async function fe(e,t,n,r){let o=n.concurrency??
|
|
32
|
-
`).length-1}))),r&&p&&d.url&&(y.url=d.url,p=!1),m.matches.push(y),h=!0}h||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Wc(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}var dS=f(()=>{"use strict";ce();Vc()});function pS(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function mS(e){return e.map(t=>{let{owner:n,repo:r}=qc(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}}})}var fS=f(()=>{"use strict";Vc()});function Kc(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}var cm=f(()=>{"use strict"});function hS(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Kc),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:$c(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function U_(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=>!cr(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 $_(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:U_(e,t??[])}}function gS(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=$_(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...Wc(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}var yS=f(()=>{"use strict";ce();cm();xc();Vc()});function bS(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 RS(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.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}:{}}}var SS=f(()=>{"use strict"});function lm(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??_n.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function PS(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([m],[p])=>m==="."?-1:p==="."?1:m.localeCompare(p)).map(([m,p])=>({dir:m,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[m,p]of Object.entries(c))if(n[m]){let h=new Set(n[m].files);for(let[g,y]of Object.entries(p))if(h.has(g)){let b=m==="."?g:`${m}/${g}`;l[b]=y}}}let u=Object.values(n).reduce((m,p)=>(m.totalFiles+=p.files.length,m.totalFolders+=p.folders.length,m),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var xS=f(()=>{"use strict";io()});var pr=f(()=>{"use strict";dS();fS();yS();SS();xS()});function Yc(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function q_(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:Yc(t.status),retryAfterSeconds:Yc(t.retryAfter),rateLimitRemaining:Yc(t.rateLimitRemaining),rateLimitReset:Yc(t.rateLimitReset)}}return{message:"Provider error"}}function Xc(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=q_(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 Jc(e,t,n){let r=Fn(e,[...t]);return{structuredContent:vt(ur(e)??{}),text:r,isError:n}}var Zc=f(()=>{"use strict";so()});function el(e){return typeof e=="object"&&e!==null}function yt(e){return typeof e=="string"&&e.length>0?e:void 0}function rt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function CS(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function At(e,t){return rt(e[t])??0}function W_(e){if(el(e))return{nonFile:At(e,"nonFile"),missingDownloadUrl:At(e,"missingDownloadUrl"),oversized:At(e,"oversized"),binary:At(e,"binary"),fileLimit:At(e,"fileLimit"),fetchFailed:At(e,"fetchFailed"),totalSizeLimit:At(e,"totalSizeLimit"),pathTraversal:At(e,"pathTraversal")}}function V_(e){if(el(e))return{maxDirectoryFiles:At(e,"maxDirectoryFiles"),maxTotalSize:At(e,"maxTotalSize"),maxFileSize:At(e,"maxFileSize")}}function Y_(e){if(!el(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 K_){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function X_(e,t){return Ic("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 J_(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 wS(e,t){let n=Y_(e.pagination),r={...X_(n,t),cloneForSemantics:J_(t)};return{path:yt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:yt(e.localPath),repoRoot:yt(e.repoRoot),...rt(e.fileSize)!==void 0?{fileSize:rt(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:rt(e.totalLines),sourceChars:rt(e.sourceChars),sourceBytes:rt(e.sourceBytes),resolvedBranch:yt(e.resolvedBranch),pagination:n,next:r,...e.isPartial===!0?{isPartial:!0}:{},startLine:rt(e.startLine),endLine:rt(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:yt(e.lastModified),lastModifiedBy:yt(e.lastModifiedBy),warnings:CS(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:yt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function TS(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(el).map(c=>({path:yt(c.path)??"",size:rt(c.size)??0,type:yt(c.type)??"file"})),o=W_(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:yt(e.localPath)??"",repoRoot:yt(e.repoRoot),fileCount:rt(e.fileCount)??r.length,totalSize:rt(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:rt(e.directoryEntryCount),eligibleFileCount:rt(e.eligibleFileCount),savedFileCount:rt(e.savedFileCount),skipped:o,limits:V_(e.limits),warnings:CS(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:yt(e.resolvedBranch)}}var K_,ES=f(()=>{"use strict";qe();K_=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});function Z_(e,t){return`${e}/${t}`}function eF(e,t,n){let r=Z_(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 tF(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=eF(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(TS(c,o)),a.directories=u;return}let l=a.files??[];l.push(wS(c,o)),a.files=l}),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 nF(e,t){return Xc(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function kS(){return({queries:e,results:t})=>{let n=new Map,r=$i(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=tF(t,n),i=nF(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Jc(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}var um=f(()=>{"use strict";Zc();Xe();ES()});async function OS(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{let s=pt(dr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?rF(a,n,c):oF(a,n,c)}catch(s){return Ve(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:kS()},e)}async function rF(e,t,n){if(!zc(n,"fetchDirectoryToDisk"))return Ve(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",v.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return N("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Ye(e.owner,e.repo,t),o=await Bd(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={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)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return Ee(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??Q(o)})}async function oF(e,t,n){let r=await nn(e,()=>n.provider.getFileContent(bS(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await iF(e,t):void 0,i={...RS(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 Ee(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function iF(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ye(e.owner,e.repo,t);return rp(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var dm=f(()=>{"use strict";me();Xe();Me();Uc();op();Ae();le();pr();rn();um()});function Vi(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function vS(e,t){let n=Vi(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function AS(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 sF(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function aF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cF(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${aF(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function lF(e,t){return{...e,matches:t}}function pm(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?sF(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:cF(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:lF(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)}var tl=f(()=>{"use strict"});function _S(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 LS(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 FS(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:LS(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:LS(r.get(i)),...s?{pagination:s}:{}}}})}function IS(e,t,n){let r=Vi(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),l=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!l)continue;let u=e.length===1?"getLines":`getLines:${i.id}`;o[u]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:l},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"heuristic"}}return Object.keys(o).length>0?o:void 0}var MS=f(()=>{"use strict";tl()});function mm(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Vi(e);t.forEach((C,k)=>{if(C.status==="error")return;let E=AS(C);E.repoState&&s.push({id:C.id,state:E.repoState,query:a.get(C.id)}),E.incompleteResults&&(i=!0),E.results.reduce((G,M)=>G+M.matches.length,0)===0&&o.push({id:C.id,...E.nonExistentScope?{nonExistentScope:!0}:{},...E.incompleteResults?{incompleteResults:!0}:{}});let w=E.results;n.push({id:C.id,groups:w}),E.pagination&&r.set(C.id,E.pagination)});let c=Array.from(new Set(e.flatMap(C=>{let k=C.keywords;return Array.isArray(k)?k.filter(E=>typeof E=="string"):[]}))),l=pm(_S(n),c),u=Xc(t),d=e.some(C=>C.concise===!0),m=FS(e,l,r),p=IS(m,e,c);if(d)for(let C of m)C.data.files=C.data.files.map(k=>`${k.owner}/${k.repo}:${k.path}`);let h={results:m,...p?{next:p}:{}};o.length>0&&(h.emptyQueries=o.map(({id:C,nonExistentScope:k,incompleteResults:E})=>({id:C,...k?{nonExistentScope:k}:{},...E?{incompleteResults:E}:{}}))),u.length>0&&(h.errors=u);let g=[],y=(C,k,E="warning")=>{h.warnings=[...h.warnings??[],k],g.push({level:E,code:C,message:k})};i&&y("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&&vS(o,e)&&y("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 b=8,S=o.filter(({id:C,nonExistentScope:k,incompleteResults:E})=>{if(k||E)return!1;let _=a.get(C)?.keywords;return Array.isArray(_)&&_.length>b});S.length>0&&y("ghQueryPossiblyTooComplex",`Quer${S.length>1?"ies":"y"} ${S.map(C=>C.id).join(", ")} used more than ${b} 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:C,state:k,query:E}of s)if(k.kind==="renamed"){let[_,w]=k.fullName.split("/");y("ghRepoRenamed",`Query ${C}: the repository was RENAMED to ${k.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let G=E?.keywords;h.next={...h.next??{},[`retryRenamed:${C}`]:{tool:"ghSearchCode",query:{owner:_,repo:w,...Array.isArray(G)?{keywords:G}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else k.kind==="archived"?y("ghRepoArchived",`Query ${C}: 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.`):y("ghRepoNotFound",`Query ${C}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`,"error");return g.length>0&&(h.diagnostics=g),Jc(h,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],l.length===0&&u.length>0)}}var DS=f(()=>{"use strict";Zc();tl();MS()});var fm=f(()=>{"use strict";tl();DS()});function uF(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function dF(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 pF(e,t,n){try{let r=await oe(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 NS(e){let{queries:t}=e,n=gt(e.authInfo);return fe(t,async(r,o)=>{try{let i=dF(r);if(i)return N(i.error,r);if(!uF(r))return N("At least one search term or scope filter is required.",r);let s=n(),a=await nn(r,()=>s.provider.searchCode(lS(r)));if(a.ok===!1)return a.result;let c=uS(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let l=await pF(String(r.owner),String(r.repo),e.authInfo);l&&(c.repoState=l)}return Ee(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Ve(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:mm()},e)}var hm=f(()=>{"use strict";me();Xe();Ae();Me();pr();rn();fm()});import{z as j}from"zod";import{GitHubCodeSearchQuerySchema as GS}from"@octocodeai/octocode-core/schemas";var HS,Ki,Yi,mF,i2,gm=f(()=>{"use strict";ce();nt();mt();dt();qe();HS={limit:z(1,100).optional(),page:Pe.default(1),match:j.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/ghHistoryResearch, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},Ki=be(GS,HS),Yi=ge(Ce(GS,HS)),mF=ut.extend({totalMatchesKind:j.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:j.boolean().optional(),uniqueFileCount:j.number().optional()}),i2=j.object({base:j.string().optional(),shared:j.record(j.string(),j.union([j.string(),j.number(),j.boolean()])).optional(),responsePagination:We.responsePagination,results:j.array(j.object({id:j.string(),data:j.object({files:j.array(j.union([j.string(),j.object({owner:j.string(),repo:j.string(),path:j.string(),queryId:j.string().optional(),matches:j.array(j.object({value:j.string().optional(),pathOnly:j.boolean().optional(),matchIndices:j.array(j.object({start:j.number(),end:j.number(),lineOffset:j.number()})).optional(),url:j.string().optional()}))})])),pagination:mF.optional()})})),emptyQueries:j.array(j.object({id:j.string(),nonExistentScope:j.literal(!0).optional(),incompleteResults:j.literal(!0).optional()})).optional(),warnings:j.array(j.string()).optional(),diagnostics:j.array(lo).optional(),next:j.record(j.string(),xe).optional(),errors:j.array(j.object({id:j.string(),error:j.string()})).optional()})});function fF(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 hF(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 gF(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function QS(e){let{content:t,reviewMode:n}=e,r=fF(t,n),o=hF(t,n),i=gF(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 a2(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}var ym=f(()=>{"use strict"});function Xi(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function fo(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Ji(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 mr(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 nl(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function bm(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function yF(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Zi(e,t,n){return yF({...bm(e,t),...n})}function Rm(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Zi(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function rl(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Zi(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function ho(e){return typeof e=="object"&&e!==null}function ol(e){if(ho(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function il(e){if(ho(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}var es=f(()=>{"use strict";ce()});function bF(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 jS(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=bF(r,n.comments),i=Xi(t),s=i?o.filter(l=>fo(l.body,i)):o,{items:a,pagination:c}=Ji(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=mr(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:nl(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function BS(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Xi(t);return{reviews:(o?r.filter(s=>fo(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=mr(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 zS(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Ji(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}}var US=f(()=>{"use strict";ce();es()});function sl(e){return String(e.path??e.filename??"")}function RF(e,t){return{path:sl(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function SF(e){return e.split(`
|
|
31
|
+
`}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function rm(e,t){return t?{...e,responsePagination:t}:e}var JR=f(()=>{"use strict"});async function fe(e,t,n,r){let o=n.concurrency??v_,{results:i,errors:s}=await YR(e,t,o,n.minQueryTimeoutMs);return A_(n,i,s,e,r)}function A_(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),l=qi(r);t.forEach(y=>{let b=y.result.status;c[y.queryIndex]={id:l[y.queryIndex]??$i(y.originalQuery,y.queryIndex),...b!==void 0?{status:b}:{},data:L_(y.result)}}),n.forEach(y=>{let b=r[y.queryIndex];b&&(c[y.queryIndex]={id:l[y.queryIndex]??$i(b,y.queryIndex),status:"error",data:{error:y.error}})});let u=c.filter(y=>y!==void 0);if(e.finalize){let y=e.finalize({queries:r,results:u,config:e}),b=nm(y.text,o),S=rm(y.structuredContent,b.pagination);return ZR(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:S,isError:y.isError??(u.length>0&&u.every(k=>k.status==="error"))}}let d={results:u};if(Array.isArray(d.results)){let y=Hc(d.results);y&&(d.base=y);let b=Qc(d.results);b&&(d.shared=b)}let m=Fn(d,a),p=nm(m,o),h=rm(vt(ur(d)??{}),p.pagination);return ZR(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:h,isError:u.length>0&&u.every(y=>y.status==="error")}}function ZR(e,t,n,r){let o=t.reduce((i,s)=>i+(ue(s.result)??Q(s.result)),0)+n.reduce((i,s)=>i+Q(s),0);try{$a(e,o,r)}catch{}}function L_(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}var v_,eS=f(()=>{"use strict";Nt();so();le();jc();JR();Jp();v_=3});var Xe=f(()=>{"use strict";Jp();eS()});function Bc(e){return e.data!==void 0&&!e.error}function __(e){return e.error!==void 0}var om=f(()=>{"use strict"});import{maskSensitiveData as tS}from"@octocodeai/octocode-engine/mask";function F_(){return md().provider??pd()}function I_(e){let t=md(),n=t.provider??pd(),{baseUrl:r,token:o}=t;try{let i=Up(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=tS(s);throw new im(n,`Failed to initialize ${n} provider: ${a}`)}}function gt(e){let t;return()=>t??=I_(e)}function zc(e,t){return e.capabilities[t]}async function nn(e,t){let n=await t();return Bc(n)?{ok:!0,response:n}:{ok:!1,result:Dc(n,e)}}async function nS(e,t){let n=t??F_(),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:tS(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Bc(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var im,rn=f(()=>{"use strict";Ac();om();$r();Me();im=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});async function rS(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>ht({toolName:v.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!zc(s,"cloneRepo"))return Ve(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",v.GITHUB_CLONE_REPO);let a;try{a=await BR(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return N(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=ui(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={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"}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return Ee(o,d,!0,v.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:v.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","location","error"]},e)}var sm=f(()=>{"use strict";Nt();me();Xe();Me();Dn();rn();Yp()});import{z as oS}from"zod";function M_(e,t){return e?.description&&!t.description?t.describe(e.description):t}function iS(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=M_(e.shape[r],o);return n}function D_(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function sS(e,t){if(!t?.length)return e;let n=new Set(t);return oS.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function be(e,t={},n={}){let r=sS(e,n.omit),o=D_(r,iS(r,t));return n.strict?o.strict():o}function Ce(e,t={},n={}){let r=sS(e,n.omit),o=oS.object({...r.shape,...iS(r,t)});return n.strict?o.strict():o}var mt=f(()=>{"use strict"});import{CloneRepoQuerySchema as N_}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as G_}from"@octocodeai/octocode-core/schemas/outputs";var fo,Wi,NV,am=f(()=>{"use strict";nt();mt();dt();fo=be(N_),Wi=ge(fo),NV=G_.extend(We)});import{z as O}from"zod";import{FileContentQuerySchema as aS}from"@octocodeai/octocode-core/schemas";var H_,Q_,j_,B_,z_,cS,U_,dr,Vi,qV,Uc=f(()=>{"use strict";ce();nt();mt();dt();qe();H_=O.enum(["none","standard","symbols"]).optional().default("standard"),Q_=O.union([lo.extend({nextPage:O.number().optional()}),ut.extend({charOffset:O.number().optional(),charLength:O.number().optional(),totalChars:O.number().optional(),nextCharOffset:O.number().optional()})]),j_=O.record(O.string(),xe),B_=O.object({path:O.string(),content:O.string(),localPath:O.string().optional(),repoRoot:O.string().optional(),contentView:O.enum(["none","standard","symbols"]).optional(),totalLines:O.number().optional(),sourceChars:O.number().optional(),sourceBytes:O.number().optional(),resolvedBranch:O.string().optional(),modified:O.string().optional(),fileSize:O.number().optional(),pagination:Q_.optional(),next:j_.optional(),isPartial:O.boolean().optional(),startLine:O.number().optional(),endLine:O.number().optional(),matchRanges:O.array(O.object({start:O.number(),end:O.number()})).optional(),lastModified:O.string().optional(),lastModifiedBy:O.string().optional(),warnings:O.array(O.string()).optional(),matchNotFound:O.boolean().optional(),searchedFor:O.string().optional(),cached:O.boolean().optional()}),z_=O.object({path:O.string(),localPath:O.string(),repoRoot:O.string().optional(),fileCount:O.number(),totalSize:O.number(),complete:O.boolean().optional(),directoryEntryCount:O.number().optional(),eligibleFileCount:O.number().optional(),savedFileCount:O.number().optional(),skipped:O.object({nonFile:O.number(),missingDownloadUrl:O.number(),oversized:O.number(),binary:O.number(),fileLimit:O.number(),fetchFailed:O.number(),totalSizeLimit:O.number(),pathTraversal:O.number()}).optional(),limits:O.object({maxDirectoryFiles:O.number(),maxTotalSize:O.number(),maxFileSize:O.number()}).optional(),warnings:O.array(O.string()).optional(),files:O.array(O.object({path:O.string(),size:O.number(),type:O.string()})).optional(),cached:O.boolean().optional(),resolvedBranch:O.string().optional()}),cS={startLine:co,endLine:co,contextLines:ao,charOffset:z(0,1e8).optional(),charLength:z(1,5e4).optional(),minify:H_},U_=Ce(aS,cS),dr=be(aS,cS),Vi=ge(U_),qV=O.object({base:O.string().optional(),shared:O.record(O.string(),O.union([O.string(),O.number(),O.boolean()])).optional(),responsePagination:We.responsePagination,results:O.array(O.object({id:O.string(),data:O.object({owner:O.string(),repo:O.string(),files:O.array(B_).optional(),directories:O.array(z_).optional()}).optional()})),errors:O.array(O.object({id:O.string(),owner:O.string().optional(),repo:O.string().optional(),path:O.string().optional(),error:O.string()})).optional()})});function $c(e,t){return e&&t?`${e}/${t}`:void 0}function qc(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Wc(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}:{}}}var Vc=f(()=>{"use strict"});function $_(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 lS(e){return{keywords:e.keywords??[],projectId:$c(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function uS(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=qc(a),u=`${c}/${l}`,d=s,m=o.get(u);if(m||(m={id:u,owner:c,repo:l,matches:[]},o.set(u,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let p=!0,h=!1;for(let g of s.matches){if(!g.context)continue;let y={path:s.path,value:$_(g.context)};g.positions?.length>0&&(y.matchIndices=g.positions.map(([b,S])=>({start:b,end:S,lineOffset:(g.context??"").substring(0,b).split(`
|
|
32
|
+
`).length-1}))),r&&p&&d.url&&(y.url=d.url,p=!1),m.matches.push(y),h=!0}h||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Wc(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}var dS=f(()=>{"use strict";ce();Vc()});function pS(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function mS(e){return e.map(t=>{let{owner:n,repo:r}=qc(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}}})}var fS=f(()=>{"use strict";Vc()});function Kc(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}var cm=f(()=>{"use strict"});function hS(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Kc),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:$c(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function q_(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=>!cr(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 W_(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:q_(e,t??[])}}function gS(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=W_(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...Wc(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}var yS=f(()=>{"use strict";ce();cm();Cc();Vc()});function bS(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 RS(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.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}:{}}}var SS=f(()=>{"use strict"});function lm(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??_n.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function PS(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([m],[p])=>m==="."?-1:p==="."?1:m.localeCompare(p)).map(([m,p])=>({dir:m,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[m,p]of Object.entries(c))if(n[m]){let h=new Set(n[m].files);for(let[g,y]of Object.entries(p))if(h.has(g)){let b=m==="."?g:`${m}/${g}`;l[b]=y}}}let u=Object.values(n).reduce((m,p)=>(m.totalFiles+=p.files.length,m.totalFolders+=p.folders.length,m),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var xS=f(()=>{"use strict";io()});var pr=f(()=>{"use strict";dS();fS();yS();SS();xS()});function Yc(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function V_(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:Yc(t.status),retryAfterSeconds:Yc(t.retryAfter),rateLimitRemaining:Yc(t.rateLimitRemaining),rateLimitReset:Yc(t.rateLimitReset)}}return{message:"Provider error"}}function Xc(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=V_(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 Jc(e,t,n){let r=Fn(e,[...t]);return{structuredContent:vt(ur(e)??{}),text:r,isError:n}}var Zc=f(()=>{"use strict";so()});function el(e){return typeof e=="object"&&e!==null}function yt(e){return typeof e=="string"&&e.length>0?e:void 0}function rt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function CS(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function At(e,t){return rt(e[t])??0}function K_(e){if(el(e))return{nonFile:At(e,"nonFile"),missingDownloadUrl:At(e,"missingDownloadUrl"),oversized:At(e,"oversized"),binary:At(e,"binary"),fileLimit:At(e,"fileLimit"),fetchFailed:At(e,"fetchFailed"),totalSizeLimit:At(e,"totalSizeLimit"),pathTraversal:At(e,"pathTraversal")}}function Y_(e){if(el(e))return{maxDirectoryFiles:At(e,"maxDirectoryFiles"),maxTotalSize:At(e,"maxTotalSize"),maxFileSize:At(e,"maxFileSize")}}function J_(e){if(!el(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 X_){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Z_(e,t){return Ic("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 eF(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 wS(e,t){let n=J_(e.pagination),r={...Z_(n,t),cloneForSemantics:eF(t)};return{path:yt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:yt(e.localPath),repoRoot:yt(e.repoRoot),...rt(e.fileSize)!==void 0?{fileSize:rt(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:rt(e.totalLines),sourceChars:rt(e.sourceChars),sourceBytes:rt(e.sourceBytes),resolvedBranch:yt(e.resolvedBranch),pagination:n,next:r,...e.isPartial===!0?{isPartial:!0}:{},startLine:rt(e.startLine),endLine:rt(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:yt(e.lastModified),lastModifiedBy:yt(e.lastModifiedBy),warnings:CS(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:yt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function TS(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(el).map(c=>({path:yt(c.path)??"",size:rt(c.size)??0,type:yt(c.type)??"file"})),o=K_(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:yt(e.localPath)??"",repoRoot:yt(e.repoRoot),fileCount:rt(e.fileCount)??r.length,totalSize:rt(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:rt(e.directoryEntryCount),eligibleFileCount:rt(e.eligibleFileCount),savedFileCount:rt(e.savedFileCount),skipped:o,limits:Y_(e.limits),warnings:CS(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:yt(e.resolvedBranch)}}var X_,ES=f(()=>{"use strict";qe();X_=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});function tF(e,t){return`${e}/${t}`}function nF(e,t,n){let r=tF(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 rF(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=nF(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(TS(c,o)),a.directories=u;return}let l=a.files??[];l.push(wS(c,o)),a.files=l}),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 oF(e,t){return Xc(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function kS(){return({queries:e,results:t})=>{let n=new Map,r=qi(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=rF(t,n),i=oF(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Jc(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}var um=f(()=>{"use strict";Zc();Xe();ES()});async function OS(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{let s=pt(dr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?iF(a,n,c):sF(a,n,c)}catch(s){return Ve(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:kS()},e)}async function iF(e,t,n){if(!zc(n,"fetchDirectoryToDisk"))return Ve(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",v.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return N("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Ye(e.owner,e.repo,t),o=await Bd(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={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)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return Ee(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??Q(o)})}async function sF(e,t,n){let r=await nn(e,()=>n.provider.getFileContent(bS(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await aF(e,t):void 0,i={...RS(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 Ee(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function aF(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ye(e.owner,e.repo,t);return rp(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var dm=f(()=>{"use strict";me();Xe();Me();Uc();op();Ae();le();pr();rn();um()});function Ki(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function vS(e,t){let n=Ki(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function AS(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 cF(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function lF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uF(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${lF(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function dF(e,t){return{...e,matches:t}}function pm(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?cF(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:uF(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:dF(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)}var tl=f(()=>{"use strict"});function _S(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 LS(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 FS(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:LS(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:LS(r.get(i)),...s?{pagination:s}:{}}}})}function IS(e,t,n){let r=Ki(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),l=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!l)continue;let u=e.length===1?"getLines":`getLines:${i.id}`;o[u]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:l},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"heuristic"}}return Object.keys(o).length>0?o:void 0}var MS=f(()=>{"use strict";tl()});function mm(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Ki(e);t.forEach((C,k)=>{if(C.status==="error")return;let E=AS(C);E.repoState&&s.push({id:C.id,state:E.repoState,query:a.get(C.id)}),E.incompleteResults&&(i=!0),E.results.reduce((G,M)=>G+M.matches.length,0)===0&&o.push({id:C.id,...E.nonExistentScope?{nonExistentScope:!0}:{},...E.incompleteResults?{incompleteResults:!0}:{}});let w=E.results;n.push({id:C.id,groups:w}),E.pagination&&r.set(C.id,E.pagination)});let c=Array.from(new Set(e.flatMap(C=>{let k=C.keywords;return Array.isArray(k)?k.filter(E=>typeof E=="string"):[]}))),l=pm(_S(n),c),u=Xc(t),d=e.some(C=>C.concise===!0),m=FS(e,l,r),p=IS(m,e,c);if(d)for(let C of m)C.data.files=C.data.files.map(k=>`${k.owner}/${k.repo}:${k.path}`);let h={results:m,...p?{next:p}:{}};o.length>0&&(h.emptyQueries=o.map(({id:C,nonExistentScope:k,incompleteResults:E})=>({id:C,...k?{nonExistentScope:k}:{},...E?{incompleteResults:E}:{}}))),u.length>0&&(h.errors=u);let g=[],y=(C,k,E="warning")=>{h.warnings=[...h.warnings??[],k],g.push({level:E,code:C,message:k})};i&&y("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&&vS(o,e)&&y("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 b=8,S=o.filter(({id:C,nonExistentScope:k,incompleteResults:E})=>{if(k||E)return!1;let _=a.get(C)?.keywords;return Array.isArray(_)&&_.length>b});S.length>0&&y("ghQueryPossiblyTooComplex",`Quer${S.length>1?"ies":"y"} ${S.map(C=>C.id).join(", ")} used more than ${b} 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:C,state:k,query:E}of s)if(k.kind==="renamed"){let[_,w]=k.fullName.split("/");y("ghRepoRenamed",`Query ${C}: the repository was RENAMED to ${k.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let G=E?.keywords;h.next={...h.next??{},[`retryRenamed:${C}`]:{tool:"ghSearchCode",query:{owner:_,repo:w,...Array.isArray(G)?{keywords:G}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else k.kind==="archived"?y("ghRepoArchived",`Query ${C}: 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.`):y("ghRepoNotFound",`Query ${C}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`,"error");return g.length>0&&(h.diagnostics=g),Jc(h,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],l.length===0&&u.length>0)}}var DS=f(()=>{"use strict";Zc();tl();MS()});var fm=f(()=>{"use strict";tl();DS()});function pF(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function mF(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 fF(e,t,n){try{let r=await oe(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 NS(e){let{queries:t}=e,n=gt(e.authInfo);return fe(t,async(r,o)=>{try{let i=mF(r);if(i)return N(i.error,r);if(!pF(r))return N("At least one search term or scope filter is required.",r);let s=n(),a=await nn(r,()=>s.provider.searchCode(lS(r)));if(a.ok===!1)return a.result;let c=uS(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let l=await fF(String(r.owner),String(r.repo),e.authInfo);l&&(c.repoState=l)}return Ee(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Ve(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:mm()},e)}var hm=f(()=>{"use strict";me();Xe();Ae();Me();pr();rn();fm()});import{z as j}from"zod";import{GitHubCodeSearchQuerySchema as GS}from"@octocodeai/octocode-core/schemas";var HS,Yi,Xi,hF,s2,gm=f(()=>{"use strict";ce();nt();mt();dt();qe();HS={limit:z(1,100).optional(),page:Pe.default(1),match:j.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/ghHistoryResearch, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},Yi=be(GS,HS),Xi=ge(Ce(GS,HS)),hF=ut.extend({totalMatchesKind:j.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:j.boolean().optional(),uniqueFileCount:j.number().optional()}),s2=j.object({base:j.string().optional(),shared:j.record(j.string(),j.union([j.string(),j.number(),j.boolean()])).optional(),responsePagination:We.responsePagination,results:j.array(j.object({id:j.string(),data:j.object({files:j.array(j.union([j.string(),j.object({owner:j.string(),repo:j.string(),path:j.string(),queryId:j.string().optional(),matches:j.array(j.object({value:j.string().optional(),pathOnly:j.boolean().optional(),matchIndices:j.array(j.object({start:j.number(),end:j.number(),lineOffset:j.number()})).optional(),url:j.string().optional()}))})])),pagination:hF.optional()})})),emptyQueries:j.array(j.object({id:j.string(),nonExistentScope:j.literal(!0).optional(),incompleteResults:j.literal(!0).optional()})).optional(),warnings:j.array(j.string()).optional(),diagnostics:j.array(uo).optional(),next:j.record(j.string(),xe).optional(),errors:j.array(j.object({id:j.string(),error:j.string()})).optional()})});function gF(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 yF(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 bF(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function QS(e){let{content:t,reviewMode:n}=e,r=gF(t,n),o=yF(t,n),i=bF(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 c2(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}var ym=f(()=>{"use strict"});function Ji(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function ho(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Zi(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 mr(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 nl(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function bm(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function RF(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function es(e,t,n){return RF({...bm(e,t),...n})}function Rm(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return es(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function rl(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return es(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function go(e){return typeof e=="object"&&e!==null}function ol(e){if(go(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function il(e){if(go(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}var ts=f(()=>{"use strict";ce()});function SF(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 jS(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=SF(r,n.comments),i=Ji(t),s=i?o.filter(l=>ho(l.body,i)):o,{items:a,pagination:c}=Zi(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=mr(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:nl(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function BS(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Ji(t);return{reviews:(o?r.filter(s=>ho(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=mr(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 zS(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Zi(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}}var US=f(()=>{"use strict";ce();ts()});function sl(e){return String(e.path??e.filename??"")}function PF(e,t){return{path:sl(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function xF(e){return e.split(`
|
|
33
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 $S(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(sl(p))):o,a=
|
|
34
|
+
`)}function $S(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(sl(p))):o,a=Ji(t),c=a?s.filter(p=>ho(sl(p),a)||ho(p.patch,a)):s,{items:l,pagination:u}=Zi(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=l.map(p=>{let h=PF(p,!1);if(!d||typeof p.patch!="string")return h;let g=r&&!a?xF(p.patch):p.patch,y=mr(g,t.charOffset??0,t.charLength??12e3);return{...h,patch:y?.content??"",diff:Fi(y?.content),...y?{patchPagination:y.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(sl).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}var qS=f(()=>{"use strict";ce();Ii();ts()});function fr(e,t){return{...e,content:t}}function CF(e,t){return{...e,...t}}function WS(e,t,n,r){let o=bm(e,t);return{target:o,...n.body?{}:{getBody:fr(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:fr(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:fr(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:fr(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:fr(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:fr(o,{reviews:!0})},...n.commits?{}:{getCommits:fr(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:CF(o,{reviewMode:"full"})}}}var VS=f(()=>{"use strict";ts()});function wF(e){return e.replace(/\n{3,}/g,`
|
|
35
35
|
|
|
36
|
-
`)}function CF(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function wF(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!ho(n))continue;let r=il(n.patchPagination);if(r?.hasMore)return r}}function TF(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!ho(n))continue;let r=il(n.bodyPagination);if(r?.hasMore)return r}}function EF(e,t,n,r){let o={},i=il(e.bodyPagination),s=ol(e.filePagination),a=ol(e.commentPagination),c=ol(e.commitPagination),l=wF(e),u=TF(e),d=CF(n);i&&(o.body={...i,nextQuery:Rm(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:rl(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:rl(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:Zi(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:rl(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Rm(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return ho(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Zi(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function kF(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function KS(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?xF(s):s,c=n.body?mr(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,p=$S(e,t,n,r),h=Array.isArray(p.changedFiles)?p.changedFiles.find(S=>S.path)?.path:void 0,y={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:nl(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:WS(t,i,n,h)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...p,...jS(e,t,n),...BS(e,t,n),...zS(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},b=EF(y,t,n,i);return kF(y),b&&(y.contentPagination=b),y}var Sm=f(()=>{"use strict";US();qS();VS();es()});async function YS(e,t,n){let r=await Ge(t),o=Te("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,auth:r},n);return He(o,()=>OF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function OF(e,t){try{let n=await oe(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}:{},url:c.html_url})),a=oo(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 re(n)}}var XS=f(()=>{"use strict";Ae();tt();Gi();lt()});async function JS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for releases mode.",e);let o=r.perPage!==void 0&&r.perPage!==Pm?r.perPage:r.limit!==void 0&&r.limit!==30?r.limit:r.perPage??Pm,i=await YS({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:Number(o)||Pm},n);if(Et(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=i.data.releases.length>0||i.data.latest!==void 0,a=i.data.pagination?.nextPage,c={...i.data,...a!==void 0?{next:{nextPage:{tool:"ghHistoryResearch",query:{type:"releases",owner:r.owner,repo:r.repo,page:a,perPage:o},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return Ee(e,c,s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var Pm,ZS=f(()=>{"use strict";me();Me();XS();lr();ce();Pm=30});function jt(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function xm(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Kc),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function eP(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 al(e){return e.pull_request!=null}function vF(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function cl(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:vF(e.labels),created_at:e.created_at??"",updated_at:e.updated_at??"",...e.closed_at?{closed_at:e.closed_at}:{},url:e.html_url??""}}function go(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function Cm(e,t,n="anon"){return Te("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:xm(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,locked:e.locked,visibility:e.visibility,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}var ll=f(()=>{"use strict";cm();lt()});import{ContentSanitizer as tP}from"@octocodeai/octocode-engine/contentSanitizer";async function nP(e,t){let n=jt(e.owner),r=jt(e.repo),o=e.issueNumber;if(!n||!r||o==null)return go("owner, repo, and issueNumber are required for issue detail mode.");let i=await oe(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(al(s.data))return go(`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,l=e.content?.comments?.includeBots===!0,u=cl(s.data),d={};if(a){let m=tP.sanitizeContent(s.data.body??"").content,p=eP(m,e.charOffset,e.charLength);u.body=p.text,p.pagination&&(d.body=p.pagination)}if(c){let m=Math.max(1,e.commentPage??1),p=Math.max(1,e.itemsPerPage??30),h=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=l?h.data:h.data.filter(b=>!cr(b.user?.login??""));u.comments=g.map(b=>({id:String(b.id),user:b.user?.login??"unknown",body:tP.sanitizeContent(b.body??"").content,created_at:b.created_at??"",updated_at:b.updated_at??"",commentType:"discussion"}));let y=oo(h.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:u.comments.length,hasMore:y,...y?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(u.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[u],total_count:1},status:200}}async function rP(e,t,n){let r=jt(t.owner)??"",o=jt(t.repo)??"",i=await oe(n),s=vd(e),a=Math.min(t.limit??30,100),c=t.page??1,l=t.sort&&t.sort!=="best-match"?t.sort:void 0,u=await i.rest.search.issuesAndPullRequests({q:s,sort:l,order:t.order||"desc",per_page:a,page:c}),d=(u.data.items??[]).filter(h=>!al(h)).map(h=>cl(h)),m=u.data.total_count??d.length,p=c*a<m&&d.length===a;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?d.map(h=>`#${h.number} ${h.title}`):d,total_count:m,effectiveQuery:s,...u.data.incomplete_results?{incomplete_results:!0}:{},pagination:{currentPage:c,perPage:a,hasMore:p,...p?{nextPage:c+1}:{},totalMatches:m,reportedTotalMatches:m,totalMatchesKind:"reported"}},status:200}}async function oP(e,t){let n=jt(e.owner),r=jt(e.repo);if(!n||!r)return go("owner and repo are required for issues mode.");let o=await oe(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),l=c.data.filter(d=>!al(d)).map(d=>cl(d)),u=oo(c.headers.link);return{data:{type:"issues",owner:n,repo:r,issues:e.concise?l.map(d=>`#${d.number} ${d.title}`):l,total_count:l.length,pagination:{currentPage:s,perPage:i,hasMore:u,...u?{nextPage:s+1}:{}}},status:200}}var iP=f(()=>{"use strict";Ae();xc();Gi();rr();ce();ll()});async function wm(e,t,n){let r=await Ge(t),o=Cm(e,n,r);return He(o,()=>AF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function AF(e,t){try{if(e.state==="merged")return go('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 nP(e,t);let n={...e,query:xm(e)};return Ad(n)?await rP(n,e,t):await oP(e,t)}catch(n){return Ht(n)?{data:{type:"issues",owner:jt(e.owner)??"",repo:jt(e.repo)??"",issues:[],total_count:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:re(n)}}var sP=f(()=>{"use strict";Ae();tt();rr();lt();ce();ll();iP()});var aP=f(()=>{"use strict";ll();sP()});async function cP(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await wm({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,involves:r.involves,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,interactions:r.interactions,locked:r.locked,visibility:r.visibility,"no-assignee":r["no-assignee"],"no-label":r["no-label"],"no-milestone":r["no-milestone"],"no-project":r["no-project"],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(Et(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});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 u=a[0];if(typeof u=="number")return u;if(typeof u=="string"){let d=u.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(u&&typeof u=="object"&&typeof u.number=="number")return u.number})(),l={};return o==null&&c!=null&&(l.readIssue={tool:"ghHistoryResearch",query:{type:"issues",owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"heuristic"}),l.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"heuristic"},Ee(e,{...i.data,next:l},s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var lP=f(()=>{"use strict";me();Me();aP();lr()});async function uP(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for commits mode.",e);let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return N("path is required when querying a specific file in commits mode.",e);let s=await pR({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,page:Number(r.page)||1,perPage:Number(r.perPage)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof r.itemsPerPage=="number"?r.itemsPerPage: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(Et(s))return N(s,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:a}=s.data,c=a.length>0,l=a.map(d=>d.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),u={...s.data,...l?{next:{prDetail:{tool:"ghHistoryResearch",query:{type:"prs",owner:r.owner,repo:r.repo,prNumber:Number(l)},why:`Open PR #${l} referenced by the first commit for review context`,confidence:"heuristic"}}}:{}};return Ee(e,u,c,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:s.rawResponseChars})}var dP=f(()=>{"use strict";me();Me();Gi();lr()});async function pP(e,t,n){let r=n(),o={...t},i=QS(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 N("At least one valid search parameter, filter, or PR number is required.",e);let c=await nn(o,()=>r.provider.searchPullRequests(hS(o)));if(c.ok===!1)return c.result;let l=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:u,resultData:d}=gS(c.response.data,{includeFileChanges:l});o.prNumber!==void 0&&delete d.pagination;let m=!s&&(!!e.content||!!e.reviewMode),p={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},h=o.minify==="standard",g=!0,y=u.map(S=>KS(S,o,m?p:i,h,g));d.pull_requests=y,!s&&o.concise===!0&&(d.pull_requests=y.map(S=>{let C=S;return`#${C.number} ${C.title}`}));let b=y.length>0;return Ee(o,d,b,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}var mP=f(()=>{"use strict";me();Me();pr();rn();ym();Sm()});import{z as Je}from"zod";import{GitHubPullRequestSearchQuerySchema as hP}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as LF}from"@octocodeai/octocode-core/schemas/outputs";var gP,_F,hr,ts,fP,A4,ul=f(()=>{"use strict";ce();nt();mt();dt();qe();gP={type:Je.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).'),perPage:z(1,100).optional().default(30),prNumber:z(1,1e9).optional(),issueNumber:z(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:z(1,100).optional().default(30),match:Je.array(Je.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:Pe.default(1),filePage:Pe.optional(),commentPage:Pe.optional(),commitPage:Pe.optional(),itemsPerPage:z(1,100).optional().default(20),charOffset:z(0,1e8).optional(),commentBodyOffset:z(0,1e8).optional(),charLength:z(1,5e4).optional()},_F=Ce(hP,gP),hr=be(hP,gP),ts=ge(_F),fP=Je.union([Je.string(),Je.object({}).passthrough()]),A4=LF.extend({results:Je.array(Je.object({id:Je.string().optional(),status:Je.string().optional(),data:Je.object({pull_requests:Je.array(fP).optional(),issues:Je.array(fP).optional(),next:Je.record(Je.string(),xe).optional()}).passthrough().optional()}).passthrough()).optional(),...We})});async function yP(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{let s=pt(hr,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?JS(o,s.data,n):a==="issues"?cP(o,s.data,n):a==="commits"?uP(o,s.data,n):pP(o,s.data,r)}catch(s){return Ve(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","total_count","error"]},e)}var Tm=f(()=>{"use strict";me();Xe();Me();rn();ZS();lP();dP();mP();ul()});function RP(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function SP(e){return!!(e.keywords&&e.keywords.length>0)}function PP(e){return!!(SP(e)||RP(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function bP(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function xP(e){let t=RP(e),n=SP(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:bP(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:bP(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}var CP=f(()=>{"use strict"});function wP(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}var Em=f(()=>{"use strict"});function EP(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 kP(e,t){return[...e].sort((n,r)=>{let o=FF(n,r,t.sort);if(o!==0)return o;let i=TP(r,t)-TP(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:km(n).localeCompare(km(r))})}function FF(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 wP(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function TP(e,t){let n=IF(t),r=km(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function IF(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function km(e){return`${e.owner}/${e.repo}`}var OP=f(()=>{"use strict";Em()});function Om(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 vm(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 Am(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 vP(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??Q(n.response.data??n.response)),0)}var Lm=f(()=>{"use strict";le()});function MF(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 nY(e){let t=e,r=[`${t.owner?`${t.owner}/`:""}${t.repo}`];if(typeof t.stars=="number"&&r.push(`${t.stars} stars`),typeof t.forksCount=="number"&&t.forksCount>0&&r.push(`${t.forksCount} forks`),typeof t.openIssuesCount=="number"&&t.openIssuesCount>0&&r.push(`${t.openIssuesCount} issues`),t.language&&r.push(t.language),t.license&&r.push(t.license),t.pushedAt&&r.push(t.pushedAt.slice(0,10)),t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"&&r.push(`@${t.defaultBranch}`),t.visibility&&t.visibility!=="public"&&r.push(t.visibility),Array.isArray(t.topics)&&t.topics.length>0&&r.push(`#${t.topics.slice(0,4).join(",")}`),t.description&&t.description!=="No description"){let o=t.description.replace(/\s+/g," ").trim();r.push(o.length>100?`${o.slice(0,99)}...`:o)}return r.join(" | ")}function DF(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:"heuristic"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"heuristic"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(MF),...o?{next:o}:{}}}}async function AP(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{if(!PP(o))return N("At least one repository search term or filter is required.",o);let s=r(),a=xP(o),{successes:c,failures:l}=await nS(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(pS(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?Dc(w.response,o):Ve(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=kP(EP(u.flatMap(w=>mS(w.response.data.repositories))),o),h=m!=null?p.slice(0,m):p,g=u.length===1?u[0]:void 0,b=u.length>1?Am(u,p.length):g?.response.data.pagination,S=b?Om(b):void 0,C=h.length>0,k=DF({repositories:h,pagination:S},o),E=vm(d),_=E?{...k.data,warnings:E}:k.data;return Ee(o,_,C,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:vP([...u,...d])})}catch(s){return Ve(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var _m=f(()=>{"use strict";me();Xe();Me();pr();rn();CP();OP();Lm();Lm()});import{z as ie}from"zod";import{GitHubReposSearchSingleQuerySchema as LP}from"@octocodeai/octocode-core/schemas";var _P,ns,rs,NF,GF,HF,pY,Fm=f(()=>{"use strict";ce();nt();mt();dt();qe();_P={limit:z(1,100).optional(),page:Pe.default(1),match:ie.array(ie.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.)")},ns=be(LP,_P),rs=ge(Ce(LP,_P)),NF=ie.object({owner:ie.string(),repo:ie.string(),stars:ie.number().optional(),forks:ie.number().optional(),openIssuesCount:ie.number().optional(),language:ie.string().optional(),license:ie.string().optional(),description:ie.string().optional(),homepage:ie.string().optional(),pushedAt:ie.string().optional(),createdAt:ie.string().optional(),defaultBranch:ie.string().optional(),topics:ie.array(ie.string()).optional(),visibility:ie.string().optional(),url:ie.string().optional(),updatedAt:ie.string().optional()}),GF=ut.extend({totalMatchesKind:ie.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:ie.boolean().optional()}).optional(),HF=ie.object({repositories:ie.array(ie.union([ie.string(),NF])).optional(),pagination:GF}).passthrough(),pY=ie.object({results:ie.array(ie.object({id:ie.string().optional(),status:ie.string().optional(),data:HF.optional()}).passthrough()).optional()}).extend(We)});function QF(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function jF(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&yi(o))continue;let i=r.files.filter(a=>!Vr(a)),s=r.folders.filter(a=>!yi(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function FP(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,l=c??await s.provider.resolveDefaultBranch(a),u=await nn(o,()=>s.provider.getRepoStructure(lm(o,l))),d=l,m;if(u.ok===!1&&c){let C=u.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let E=await s.provider.resolveDefaultBranch(a);if(E!==c){let _=await nn(o,()=>s.provider.getRepoStructure(lm(o,E)));_.ok!==!1&&(u=_,d=E,m=`Branch/ref '${c}' was not found. Showing '${E}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(u.ok===!1)return QF(u.result,o);let p=jF(u.response.data.structure),h=Object.keys(p).length>0,g=PS(u.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let b=g.structure?.find(C=>(C.files?.length??0)>0),S=b?b.dir==="."?b.files[0]:`${b.dir}/${b.files[0]}`:void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...o.branch?{branch:o.branch}:{}},why:"Read the first listed file",confidence:"heuristic"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...o.branch?{branch:o.branch}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},Ee(o,g,h,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return Ve(s,o,"Failed to explore repository structure",v.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:v.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var Im=f(()=>{"use strict";me();Xe();Kr();Me();pr();rn()});import{GitHubViewRepoStructureQuerySchema as IP}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as BF}from"@octocodeai/octocode-core/schemas/outputs";var MP,os,is,OY,Mm=f(()=>{"use strict";ce();ce();nt();mt();dt();MP={maxDepth:z(0,20).optional(),page:Pe.default(1),itemsPerPage:z(1,200).optional()},os=be(IP,MP),is=ge(Ce(IP,MP)),OY=BF.extend(We)});import DP from"path";import{pathValidator as zF}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as UF}from"@octocodeai/config";function bt(e,t){if(!e.path?.trim()){let s=at.pathValidationFailed("","path is required");return{isValid:!1,errorResult:N(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||UF().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=DP.isAbsolute(r)?r:DP.resolve(n,r),i=zF.validate(o);if(!i.isValid){let s=at.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:N(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function MY(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:at.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}}var Bt=f(()=>{"use strict";Yo();Mc()});var NY,zt,yo=f(()=>{"use strict";NY={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},zt={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 HY(e){return t=>{}}function NP(e,t){return n=>t}var Dm=f(()=>{"use strict"});import{open as $F,readFile as qF,stat as WF}from"fs/promises";function Nm(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Gm(e,t,n){return{...e,...Nm(t,n)}}function GP(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 HP(e,t){try{return{fileStats:await WF(t)}}catch(n){let r=at.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function QP(e,t){return t>zt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function jP(e,t,n){let r=at.fileTooLarge(e.path,n,zt.LARGE_FILE_THRESHOLD_KB);return N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function BP(e,t){let n=at.binaryFileUnsupported(e.path);return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function zP(e){let n=Buffer.alloc(8192),r;try{r=await $F(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(NP("binary sample handle close",void 0))}}async function UP(e,t){try{return{content:await qF(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?at.fileAccessFailed(e.path,r):at.fileReadFailed(e.path,r);return{errorResult:N(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function $P(e,t){return{status:"empty",errorCode:q.NO_MATCHES,totalLines:t}}var dl=f(()=>{"use strict";yo();me();Bt();Yo();bn();Dm()});function VF(e,t,n){let r=ac(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:$P(e,n)};let o=r.lines.join(`
|
|
37
|
-
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(l=m.start,u=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function
|
|
38
|
-
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function
|
|
39
|
-
`),o=Qt(t);return e.matchString?
|
|
36
|
+
`)}function TF(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function EF(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!go(n))continue;let r=il(n.patchPagination);if(r?.hasMore)return r}}function kF(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!go(n))continue;let r=il(n.bodyPagination);if(r?.hasMore)return r}}function OF(e,t,n,r){let o={},i=il(e.bodyPagination),s=ol(e.filePagination),a=ol(e.commentPagination),c=ol(e.commitPagination),l=EF(e),u=kF(e),d=TF(n);i&&(o.body={...i,nextQuery:Rm(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:rl(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:rl(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:es(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:rl(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Rm(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return go(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?es(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function vF(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function KS(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?wF(s):s,c=n.body?mr(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,p=$S(e,t,n,r),h=Array.isArray(p.changedFiles)?p.changedFiles.find(S=>S.path)?.path:void 0,y={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:nl(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:WS(t,i,n,h)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...p,...jS(e,t,n),...BS(e,t,n),...zS(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},b=OF(y,t,n,i);return vF(y),b&&(y.contentPagination=b),y}var Sm=f(()=>{"use strict";US();qS();VS();ts()});async function YS(e,t,n){let r=await Ge(t),o=Te("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,auth:r},n);return He(o,()=>AF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function AF(e,t){try{let n=await oe(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}:{},url:c.html_url})),a=oo(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 re(n)}}var XS=f(()=>{"use strict";Ae();tt();Hi();lt()});async function JS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for releases mode.",e);let o=r.perPage!==void 0&&r.perPage!==Pm?r.perPage:r.limit!==void 0&&r.limit!==30?r.limit:r.perPage??Pm,i=await YS({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:Number(o)||Pm},n);if(Et(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=i.data.releases.length>0||i.data.latest!==void 0,a=i.data.pagination?.nextPage,c={...i.data,...a!==void 0?{next:{nextPage:{tool:"ghHistoryResearch",query:{type:"releases",owner:r.owner,repo:r.repo,page:a,perPage:o},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return Ee(e,c,s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var Pm,ZS=f(()=>{"use strict";me();Me();XS();lr();ce();Pm=30});function jt(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function xm(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Kc),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function eP(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 al(e){return e.pull_request!=null}function LF(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function cl(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:LF(e.labels),created_at:e.created_at??"",updated_at:e.updated_at??"",...e.closed_at?{closed_at:e.closed_at}:{},url:e.html_url??""}}function yo(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function Cm(e,t,n="anon"){return Te("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:xm(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,locked:e.locked,visibility:e.visibility,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}var ll=f(()=>{"use strict";cm();lt()});import{ContentSanitizer as tP}from"@octocodeai/octocode-engine/contentSanitizer";async function nP(e,t){let n=jt(e.owner),r=jt(e.repo),o=e.issueNumber;if(!n||!r||o==null)return yo("owner, repo, and issueNumber are required for issue detail mode.");let i=await oe(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(al(s.data))return yo(`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,l=e.content?.comments?.includeBots===!0,u=cl(s.data),d={};if(a){let m=tP.sanitizeContent(s.data.body??"").content,p=eP(m,e.charOffset,e.charLength);u.body=p.text,p.pagination&&(d.body=p.pagination)}if(c){let m=Math.max(1,e.commentPage??1),p=Math.max(1,e.itemsPerPage??30),h=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=l?h.data:h.data.filter(b=>!cr(b.user?.login??""));u.comments=g.map(b=>({id:String(b.id),user:b.user?.login??"unknown",body:tP.sanitizeContent(b.body??"").content,created_at:b.created_at??"",updated_at:b.updated_at??"",commentType:"discussion"}));let y=oo(h.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:u.comments.length,hasMore:y,...y?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(u.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[u],total_count:1},status:200}}async function rP(e,t,n){let r=jt(t.owner)??"",o=jt(t.repo)??"",i=await oe(n),s=vd(e),a=Math.min(t.limit??30,100),c=t.page??1,l=t.sort&&t.sort!=="best-match"?t.sort:void 0,u=await i.rest.search.issuesAndPullRequests({q:s,sort:l,order:t.order||"desc",per_page:a,page:c}),d=(u.data.items??[]).filter(h=>!al(h)).map(h=>cl(h)),m=u.data.total_count??d.length,p=c*a<m&&d.length===a;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?d.map(h=>`#${h.number} ${h.title}`):d,total_count:m,effectiveQuery:s,...u.data.incomplete_results?{incomplete_results:!0}:{},pagination:{currentPage:c,perPage:a,hasMore:p,...p?{nextPage:c+1}:{},totalMatches:m,reportedTotalMatches:m,totalMatchesKind:"reported"}},status:200}}async function oP(e,t){let n=jt(e.owner),r=jt(e.repo);if(!n||!r)return yo("owner and repo are required for issues mode.");let o=await oe(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),l=c.data.filter(d=>!al(d)).map(d=>cl(d)),u=oo(c.headers.link);return{data:{type:"issues",owner:n,repo:r,issues:e.concise?l.map(d=>`#${d.number} ${d.title}`):l,total_count:l.length,pagination:{currentPage:s,perPage:i,hasMore:u,...u?{nextPage:s+1}:{}}},status:200}}var iP=f(()=>{"use strict";Ae();Cc();Hi();rr();ce();ll()});async function wm(e,t,n){let r=await Ge(t),o=Cm(e,n,r);return He(o,()=>_F(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function _F(e,t){try{if(e.state==="merged")return yo('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 nP(e,t);let n={...e,query:xm(e)};return Ad(n)?await rP(n,e,t):await oP(e,t)}catch(n){return Ht(n)?{data:{type:"issues",owner:jt(e.owner)??"",repo:jt(e.repo)??"",issues:[],total_count:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:re(n)}}var sP=f(()=>{"use strict";Ae();tt();rr();lt();ce();ll();iP()});var aP=f(()=>{"use strict";ll();sP()});async function cP(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await wm({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,involves:r.involves,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,interactions:r.interactions,locked:r.locked,visibility:r.visibility,"no-assignee":r["no-assignee"],"no-label":r["no-label"],"no-milestone":r["no-milestone"],"no-project":r["no-project"],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(Et(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});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 u=a[0];if(typeof u=="number")return u;if(typeof u=="string"){let d=u.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(u&&typeof u=="object"&&typeof u.number=="number")return u.number})(),l={};return o==null&&c!=null&&(l.readIssue={tool:"ghHistoryResearch",query:{type:"issues",owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"heuristic"}),l.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"heuristic"},Ee(e,{...i.data,next:l},s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var lP=f(()=>{"use strict";me();Me();aP();lr()});async function uP(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for commits mode.",e);let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return N("path is required when querying a specific file in commits mode.",e);let s=await pR({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,page:Number(r.page)||1,perPage:Number(r.perPage)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof r.itemsPerPage=="number"?r.itemsPerPage: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(Et(s))return N(s,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:a}=s.data,c=a.length>0,l=a.map(d=>d.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),u={...s.data,...l?{next:{prDetail:{tool:"ghHistoryResearch",query:{type:"prs",owner:r.owner,repo:r.repo,prNumber:Number(l)},why:`Open PR #${l} referenced by the first commit for review context`,confidence:"heuristic"}}}:{}};return Ee(e,u,c,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:s.rawResponseChars})}var dP=f(()=>{"use strict";me();Me();Hi();lr()});async function pP(e,t,n){let r=n(),o={...t},i=QS(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 N("At least one valid search parameter, filter, or PR number is required.",e);let c=await nn(o,()=>r.provider.searchPullRequests(hS(o)));if(c.ok===!1)return c.result;let l=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:u,resultData:d}=gS(c.response.data,{includeFileChanges:l});o.prNumber!==void 0&&delete d.pagination;let m=!s&&(!!e.content||!!e.reviewMode),p={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},h=o.minify==="standard",g=!0,y=u.map(S=>KS(S,o,m?p:i,h,g));d.pull_requests=y,!s&&o.concise===!0&&(d.pull_requests=y.map(S=>{let C=S;return`#${C.number} ${C.title}`}));let b=y.length>0;return Ee(o,d,b,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}var mP=f(()=>{"use strict";me();Me();pr();rn();ym();Sm()});import{z as Je}from"zod";import{GitHubPullRequestSearchQuerySchema as hP}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as FF}from"@octocodeai/octocode-core/schemas/outputs";var gP,IF,hr,ns,fP,L4,ul=f(()=>{"use strict";ce();nt();mt();dt();qe();gP={type:Je.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).'),perPage:z(1,100).optional().default(30),prNumber:z(1,1e9).optional(),issueNumber:z(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:z(1,100).optional().default(30),match:Je.array(Je.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:Pe.default(1),filePage:Pe.optional(),commentPage:Pe.optional(),commitPage:Pe.optional(),itemsPerPage:z(1,100).optional().default(20),charOffset:z(0,1e8).optional(),commentBodyOffset:z(0,1e8).optional(),charLength:z(1,5e4).optional()},IF=Ce(hP,gP),hr=be(hP,gP),ns=ge(IF),fP=Je.union([Je.string(),Je.object({}).passthrough()]),L4=FF.extend({results:Je.array(Je.object({id:Je.string().optional(),status:Je.string().optional(),data:Je.object({pull_requests:Je.array(fP).optional(),issues:Je.array(fP).optional(),next:Je.record(Je.string(),xe).optional()}).passthrough().optional()}).passthrough()).optional(),...We})});async function yP(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{let s=pt(hr,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?JS(o,s.data,n):a==="issues"?cP(o,s.data,n):a==="commits"?uP(o,s.data,n):pP(o,s.data,r)}catch(s){return Ve(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","total_count","error"]},e)}var Tm=f(()=>{"use strict";me();Xe();Me();rn();ZS();lP();dP();mP();ul()});function RP(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function SP(e){return!!(e.keywords&&e.keywords.length>0)}function PP(e){return!!(SP(e)||RP(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function bP(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function xP(e){let t=RP(e),n=SP(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:bP(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:bP(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}var CP=f(()=>{"use strict"});function wP(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}var Em=f(()=>{"use strict"});function EP(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 kP(e,t){return[...e].sort((n,r)=>{let o=MF(n,r,t.sort);if(o!==0)return o;let i=TP(r,t)-TP(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:km(n).localeCompare(km(r))})}function MF(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 wP(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function TP(e,t){let n=DF(t),r=km(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function DF(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function km(e){return`${e.owner}/${e.repo}`}var OP=f(()=>{"use strict";Em()});function Om(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 vm(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 Am(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 vP(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??Q(n.response.data??n.response)),0)}var Lm=f(()=>{"use strict";le()});function NF(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 rY(e){let t=e,r=[`${t.owner?`${t.owner}/`:""}${t.repo}`];if(typeof t.stars=="number"&&r.push(`${t.stars} stars`),typeof t.forksCount=="number"&&t.forksCount>0&&r.push(`${t.forksCount} forks`),typeof t.openIssuesCount=="number"&&t.openIssuesCount>0&&r.push(`${t.openIssuesCount} issues`),t.language&&r.push(t.language),t.license&&r.push(t.license),t.pushedAt&&r.push(t.pushedAt.slice(0,10)),t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"&&r.push(`@${t.defaultBranch}`),t.visibility&&t.visibility!=="public"&&r.push(t.visibility),Array.isArray(t.topics)&&t.topics.length>0&&r.push(`#${t.topics.slice(0,4).join(",")}`),t.description&&t.description!=="No description"){let o=t.description.replace(/\s+/g," ").trim();r.push(o.length>100?`${o.slice(0,99)}...`:o)}return r.join(" | ")}function GF(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:"heuristic"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"heuristic"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(NF),...o?{next:o}:{}}}}async function AP(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{if(!PP(o))return N("At least one repository search term or filter is required.",o);let s=r(),a=xP(o),{successes:c,failures:l}=await nS(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(pS(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?Dc(w.response,o):Ve(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=kP(EP(u.flatMap(w=>mS(w.response.data.repositories))),o),h=m!=null?p.slice(0,m):p,g=u.length===1?u[0]:void 0,b=u.length>1?Am(u,p.length):g?.response.data.pagination,S=b?Om(b):void 0,C=h.length>0,k=GF({repositories:h,pagination:S},o),E=vm(d),_=E?{...k.data,warnings:E}:k.data;return Ee(o,_,C,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:vP([...u,...d])})}catch(s){return Ve(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var _m=f(()=>{"use strict";me();Xe();Me();pr();rn();CP();OP();Lm();Lm()});import{z as ie}from"zod";import{GitHubReposSearchSingleQuerySchema as LP}from"@octocodeai/octocode-core/schemas";var _P,rs,os,HF,QF,jF,mY,Fm=f(()=>{"use strict";ce();nt();mt();dt();qe();_P={limit:z(1,100).optional(),page:Pe.default(1),match:ie.array(ie.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.)")},rs=be(LP,_P),os=ge(Ce(LP,_P)),HF=ie.object({owner:ie.string(),repo:ie.string(),stars:ie.number().optional(),forks:ie.number().optional(),openIssuesCount:ie.number().optional(),language:ie.string().optional(),license:ie.string().optional(),description:ie.string().optional(),homepage:ie.string().optional(),pushedAt:ie.string().optional(),createdAt:ie.string().optional(),defaultBranch:ie.string().optional(),topics:ie.array(ie.string()).optional(),visibility:ie.string().optional(),url:ie.string().optional(),updatedAt:ie.string().optional()}),QF=ut.extend({totalMatchesKind:ie.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:ie.boolean().optional()}).optional(),jF=ie.object({repositories:ie.array(ie.union([ie.string(),HF])).optional(),pagination:QF}).passthrough(),mY=ie.object({results:ie.array(ie.object({id:ie.string().optional(),status:ie.string().optional(),data:jF.optional()}).passthrough()).optional()}).extend(We)});function BF(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function zF(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&bi(o))continue;let i=r.files.filter(a=>!Vr(a)),s=r.folders.filter(a=>!bi(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function FP(e){let{queries:t,authInfo:n}=e,r=gt(n);return fe(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,l=c??await s.provider.resolveDefaultBranch(a),u=await nn(o,()=>s.provider.getRepoStructure(lm(o,l))),d=l,m;if(u.ok===!1&&c){let C=u.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let E=await s.provider.resolveDefaultBranch(a);if(E!==c){let _=await nn(o,()=>s.provider.getRepoStructure(lm(o,E)));_.ok!==!1&&(u=_,d=E,m=`Branch/ref '${c}' was not found. Showing '${E}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(u.ok===!1)return BF(u.result,o);let p=zF(u.response.data.structure),h=Object.keys(p).length>0,g=PS(u.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let b=g.structure?.find(C=>(C.files?.length??0)>0),S=b?b.dir==="."?b.files[0]:`${b.dir}/${b.files[0]}`:void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...o.branch?{branch:o.branch}:{}},why:"Read the first listed file",confidence:"heuristic"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...o.branch?{branch:o.branch}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},Ee(o,g,h,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return Ve(s,o,"Failed to explore repository structure",v.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:v.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var Im=f(()=>{"use strict";me();Xe();Kr();Me();pr();rn()});import{GitHubViewRepoStructureQuerySchema as IP}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as UF}from"@octocodeai/octocode-core/schemas/outputs";var MP,is,ss,vY,Mm=f(()=>{"use strict";ce();ce();nt();mt();dt();MP={maxDepth:z(0,20).optional(),page:Pe.default(1),itemsPerPage:z(1,200).optional()},is=be(IP,MP),ss=ge(Ce(IP,MP)),vY=UF.extend(We)});import DP from"path";import{pathValidator as NP}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as GP}from"@octocodeai/config";function $F(e=GP().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&NP.addAllowedRoot(t)}function bt(e,t){if(!e.path?.trim()){let s=at.pathValidationFailed("","path is required");return{isValid:!1,errorResult:N(s,e,{toolName:t})}}$F();let n=process.env.WORKSPACE_ROOT?.trim()||GP().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=DP.isAbsolute(r)?r:DP.resolve(n,r),i=NP.validate(o);if(!i.isValid){let s=at.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:N(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function DY(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:at.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}}var Bt=f(()=>{"use strict";Xo();Mc()});var GY,zt,bo=f(()=>{"use strict";GY={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},zt={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 QY(e){return t=>{}}function HP(e,t){return n=>t}var Dm=f(()=>{"use strict"});import{open as qF,readFile as WF,stat as VF}from"fs/promises";function Nm(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Gm(e,t,n){return{...e,...Nm(t,n)}}function QP(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 jP(e,t){try{return{fileStats:await VF(t)}}catch(n){let r=at.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function BP(e,t){return t>zt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function zP(e,t,n){let r=at.fileTooLarge(e.path,n,zt.LARGE_FILE_THRESHOLD_KB);return N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function UP(e,t){let n=at.binaryFileUnsupported(e.path);return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function $P(e){let n=Buffer.alloc(8192),r;try{r=await qF(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(HP("binary sample handle close",void 0))}}async function qP(e,t){try{return{content:await WF(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?at.fileAccessFailed(e.path,r):at.fileReadFailed(e.path,r);return{errorResult:N(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function WP(e,t){return{status:"empty",errorCode:q.NO_MATCHES,totalLines:t}}var dl=f(()=>{"use strict";bo();me();Bt();Xo();bn();Dm()});function KF(e,t,n){let r=cc(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:WP(e,n)};let o=r.lines.join(`
|
|
37
|
+
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(l=m.start,u=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function YF(e){return e.startLine!==void 0&&e.endLine!==void 0}function XF(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:q.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:q.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
|
|
38
|
+
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function VP(e,t,n){let r=t.split(`
|
|
39
|
+
`),o=Qt(t);return e.matchString?KF(e,r,o):YF(e)?XF(e,r,o):{resultContent:t,isPartial:!1}}var KP=f(()=>{"use strict";lc();sr();bn();dl()});async function YP(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",d=s;if(s!==void 0){let g=await hc(e,l,s,r);u=g.chunkMode,d=g.length}let m=mc(e,l,d,s!==void 0?{pageSize:s}:void 0),p;if(m.hasMore&&u==="char-limit"&&Ai(m.paginatedContent)){let g=m.charOffset+m.charLength;p=await Li(e,g,r)}let h=Ic("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:u,nextBlockChar:p,next:h,showPagination:s!==void 0||i>0||a}}async function XP(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=await YP(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,contentView:s,...d&&{isPartial:d},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...ap(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}async function Hm(e,t,n,r,o,i,s){let a=await YP(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...Nm(r,o),...a.showPagination&&{pagination:{...ap(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function JP(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}var ZP=f(()=>{"use strict";Le();fc();gc();qe();dl()});import{ContentSanitizer as JF}from"@octocodeai/octocode-engine/contentSanitizer";async function pl(e){let t=Ln();try{let n=bt(e,v.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=QP(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await jP(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await $P(o))return V(UP(e,o),c);if(BP(e,l))return V(zP(e,o,l),c);let{content:u,errorResult:d}=await qP(e,o);if(d||u===void 0)return d;let m=JF.sanitizeContent(u,i),p=m.content,h=p.length,g=Buffer.byteLength(p,"utf-8"),y=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,b=e.minify,S=b==="standard"||b==="symbols",C=S?"standard":"none",k;if(b==="symbols"){let M=D.extractSignatures(p,i);if(M===null){let A=uc(p,i);if(A!==null)return V(await Hm(e,A,Qt(p),h,g,y,t),h);k=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(M!==null){let A=Qt(p),W=D.applyContentViewMinification(M,i);return V(await Hm(e,W,A,h,g,y,t),h)}}let E=Qt(p),_=VP(e,p,t),w=M=>{let A=[...k?[k]:[],...y?[y]:[]];if(A.length===0)return M;let W=M.warnings??[];return{...M,warnings:[...W,...A]}};if(_.earlyResult){let M=_.earlyResult.content,A=S&&typeof M=="string"?{..._.earlyResult,content:D.applyContentViewMinification(M,i)}:_.earlyResult;return V(Gm(w(Qm(JP(A,C),e,E)),h,g),h)}let G=await XP(e,_,s,E,t,S,C);return V(Gm(w(Qm(G,e,E)),h,g),h)}catch(n){return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT})}}function Qm(e,t,n){return e}var as=f(()=>{"use strict";Le();sr();vi();me();Bt();le();dc();dl();KP();ZP()});import{z as se}from"zod";import{FetchContentQuerySchema as ex}from"@octocodeai/octocode-core/schemas";var ZF,tx,eI,gr,cs,tI,nI,EX,ml=f(()=>{"use strict";ce();nt();mt();dt();qe();ZF=se.enum(["none","standard","symbols"]).optional().default("standard"),tx={startLine:co,endLine:co,contextLines:ao.default(5),charOffset:z(0,1e8).optional(),charLength:z(1,5e4).optional(),minify:ZF},eI=Ce(ex,tx),gr=be(ex,tx),cs=ge(eI,{maxQueries:5}),tI=se.object({start:se.number(),end:se.number()}),nI=se.object({path:se.string().optional(),content:se.string().optional(),contentView:se.enum(["none","standard","symbols"]).optional(),totalLines:se.number().optional(),sourceChars:se.number().optional(),sourceBytes:se.number().optional(),startLine:se.number().optional(),endLine:se.number().optional(),isPartial:se.boolean().optional(),matchRanges:se.array(tI).optional(),pagination:se.union([lo.extend({nextBlockChar:se.number().optional()}),ut]).optional(),next:se.record(se.string(),xe).optional(),modified:se.string().optional(),lastModified:se.string().optional(),lastModifiedBy:se.string().optional(),warnings:se.array(se.string()).optional(),matchNotFound:se.boolean().optional(),searchedFor:se.string().optional()}),EX=se.object({results:se.array(se.object({id:se.string(),status:se.enum(["empty","error"]).optional(),data:nI}))}).extend(Mn)});async function nx(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=pt(gr,n);return r.ok===!1?r.error:await pl(r.data)}}),{toolName:v.LOCAL_FETCH_CONTENT,finalize:rI()},e)}function rI(){return({results:e})=>{let t={results:oI(e)},n=Hc(t.results);n&&(t.base=n);let r=Qc(t.results);return r&&(t.shared=r),{structuredContent:vt(t),text:iI(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function oI(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function iI(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=Fn({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Fn({shared:e.shared},["shared"]).trimEnd()),t.join(`
|
|
40
40
|
`).trimEnd()+`
|
|
41
|
-
`}var jm=f(()=>{"use strict";me();Xe();so();jc();ss();ml();Me();Dn();ss()});import{z as de}from"zod";import{FindFilesQuerySchema as iI}from"@octocodeai/octocode-core/schemas";function sI(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 tx,nx,aI,yr,cs,cI,lI,UX,fl=f(()=>{"use strict";ce();nt();mt();dt();qe();tx={maxDepth:z(0,100).optional(),minDepth:z(0,100).optional(),limit:z(1,1e4).optional(),page:Pe.default(1),itemsPerPage:z(1,50).optional(),excludeDir:de.array(de.string()).optional().describe('Directory names to prune from the walk (e.g. ["node_modules","dist","coverage"]). NOTHING is excluded by default \u2014 results include build output and vendor dirs unless you pass this explicitly.')},nx=de.object(Object.fromEntries(Object.entries(iI.shape).filter(([e])=>e!=="regexType")));aI=Ce(nx,tx),yr=be(nx,tx).superRefine(sI),cs=ge(aI,{maxQueries:5}),cI=de.object({name:de.string().optional(),path:de.string().optional(),type:de.enum(["file","dir","directory","link","symlink"]).optional(),size:de.union([de.number(),de.string()]).optional(),sizeFormatted:de.string().optional(),modified:de.string().optional(),accessed:de.string().optional(),created:de.string().optional(),permissions:de.string().optional()}),lI=de.object({path:de.string().optional(),files:de.array(cI).optional(),summary:de.string().optional(),pagination:In.optional(),next:de.record(de.string(),xe).optional(),warnings:de.array(de.string()).optional()}),UX=de.object({results:de.array(de.object({id:de.string(),status:de.enum(["empty","error"]).optional(),data:lI}))}).extend(Mn)});function bo(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 ls(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var us=f(()=>{"use strict"});function Bm(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+ls(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${bo(r)})`}function zm(e,t){let n=e.length,r=t.itemsPerPage||zt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function uI(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function ds(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`]}var hl=f(()=>{"use strict";yo();us()});function pI(e,t){let n=t??dI,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function br(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=bt(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:pI(i.path,i.excludeDir)},{warnings:a,query:c}=yI(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,m=u.wasCapped,p=u.entries.map(Y=>mI(Y,r)),h=e.sortBy||"modified";fI(p,h,r);let g=p.slice(0,l),y=hI(g,t,n),b=y.length,S=e.itemsPerPage||20,C=e.page||1,k=Math.max(1,Math.ceil(b/S)),E=(C-1)*S,_=Math.min(E+S,b),G=y.slice(E,_),M=[...u.warnings,...ds(u)],A=[...a,...M],W=C<k,H={...b===0?{status:"empty"}:{},path:i.path,files:G,pagination:{currentPage:C,totalPages:k,filesPerPage:S,totalFiles:b,hasMore:W,...W?{nextPage:C+1}:{},...m||d>b?{totalFilesFound:d}:{}},...W?{next:{nextPage:Fc(v.LOCAL_FIND_FILES,{...i,page:C+1},"Continue to the next page of matched files.")}}:{},...A.length>0&&{warnings:A}};return V(rx(H,e,{totalFiles:b}),u.entries.reduce((Y,I)=>Y+I.path.length,0))}catch(o){return N(o,e,{toolName:v.LOCAL_FIND_FILES})}}function mI(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 rx(e,t,n){return e}function fI(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 hI(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=bo(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function yI(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!gI.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var dI,gI,Ro=f(()=>{"use strict";Bt();us();Le();me();ce();le();qe();hl();dI=[];gI=/^\d+[hdwm]$/});async function ox(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=pt(yr,n);return r.ok===!1?r.error:await br(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var Um=f(()=>{"use strict";fl();me();Xe();Ro();Me();Dn();Ro()});import{z as F}from"zod";import{RipgrepQuerySchema as ix}from"@octocodeai/octocode-core/schemas";var bI,RI,sx,SI,PI,xI,on,ps,CI,wI,TI,S5,ms=f(()=>{"use strict";ce();nt();mt();dt();qe();bI=["paginated","discovery","detailed","structural"],RI=["semanticRanking"],sx={mode:F.enum(bI).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 ghHistoryResearch\'s `patches.mode` \u2014 different concepts sharing this name.)'),keywords:F.string().optional().describe("The search pattern (text or regex). Set fixedString:true for a literal match, or perlRegex:true for advanced regex features (lookaheads, backreferences). (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)"),filesOnly:F.boolean().optional().describe("Returns matching file paths without line content. Mutually exclusive with filesWithoutMatch. (Unlike localViewStructure's `filesOnly`, which filters a directory listing to file entries only \u2014 a different concept sharing this name.)"),pattern:F.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:F.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."),contextLines:ao,matchContentLength:z(1,1e5).optional().default(500),maxMatchesPerFile:z(1,1e5).optional(),maxFiles:z(1,1e5).optional(),matchPage:Pe.optional(),itemsPerPage:z(1,1e3).optional(),page:Pe.default(1),unique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},SI={...sx,semanticRanking:F.never().optional()},PI=Ce(ix,SI),xI=be(ix,sx,{strict:!0,omit:RI}),on=xI.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),ps=ge(PI,{maxQueries:5}),CI=F.object({line:F.number(),endLine:F.number().optional(),value:F.string().optional(),column:F.number().optional(),endColumn:F.number().optional(),count:F.number().optional(),kind:F.string().optional(),scoreHint:F.number().optional(),metavars:F.record(F.string(),F.array(F.string())).optional(),metavarRanges:F.record(F.string(),F.array(F.object({text:F.string(),line:F.number(),column:F.number(),endLine:F.number(),endColumn:F.number()}))).optional()}),wI=F.object({path:F.string(),matches:F.array(CI).optional(),totalOccurrences:F.number().optional(),totalMatchedLines:F.number().optional(),totalMatchRows:F.number().optional(),returnedMatchRows:F.number().optional(),ranking:F.object({score:F.number(),profile:F.string().optional(),pathRole:F.string().optional(),reasons:F.array(F.string()).optional()}).optional(),matchPagination:In.optional(),pagination:In.optional(),next:F.record(F.string(),xe).optional()}),TI=F.object({files:F.array(wI).optional(),summary:F.string().optional(),searchEngine:F.string().optional(),stats:F.object({totalOccurrences:F.number().optional(),matchedLines:F.number().optional(),filesMatched:F.number().optional(),filesSearched:F.number().optional(),bytesSearched:F.number().optional(),searchTime:F.string().optional()}).passthrough().optional(),pagination:In.optional(),next:F.record(F.string(),xe).optional(),warnings:F.array(F.string()).optional()}),S5=F.object({results:F.array(F.object({id:F.string(),status:F.enum(["empty","error"]).optional(),data:TI}))}).extend(Mn)});function gs(e){return gl.exec(e)?.[1]?.toLowerCase()??""}function FI(e){let t=gs(e);if(!t)return!1;for(let n of _I)if(fs[n].extensions.includes(t))return!0;return!1}function Km(e,t,n){if(n&&n!=="auto")return fs[n];let r=gs(e),o=(t??"").toLowerCase();for(let i of $m){let s=fs[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of $m){let s=fs[i];if(i!=="generic"&&s.extensions.includes(r))return s}return fs.generic}function yl(e){return EI.test(e)?"generated":OI.test(e)?"fixture":kI.test(e)?"test":AI.test(e)?"config":vI.test(e)?"docs":!hs.test(e)&&(LI.test(e)||FI(e))?"source":"unknown"}function Ym(e){if(!e)return!1;if(hs.test(e))return!0;let t=yl(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var $m,pe,qm,Wm,ax,fs,Vm,hs,EI,kI,OI,vI,AI,LI,_I,gl,bl=f(()=>{"use strict";$m=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],pe={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},qm=2e3,Wm=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,ax={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+['"]/]},fs={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...ax},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...ax},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/]}},Vm=/^\s*#{1,6}\s/,hs=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,EI=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,kI=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,OI=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,vI=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,AI=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,LI=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,_I=new Set(["typescript","javascript","rust","python","go","java","scala"]),gl=/\.([a-z0-9]+)$/i});function Xm(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(cx),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??qm,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(cx);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=nf(i,n),l=i.map(d=>{try{return{file:d,s:rf(d,n,c)}}catch{return{file:d,s:II()}}});l.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function II(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function cx(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function ys(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Rl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jm(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function Zm(e,t,n){if(e.indexOf(`
|
|
41
|
+
`}var jm=f(()=>{"use strict";me();Xe();so();jc();as();ml();Me();Dn();as()});import{z as de}from"zod";import{FindFilesQuerySchema as sI}from"@octocodeai/octocode-core/schemas";function aI(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 rx,ox,cI,yr,ls,lI,uI,$X,fl=f(()=>{"use strict";ce();nt();mt();dt();qe();rx={maxDepth:z(0,100).optional(),minDepth:z(0,100).optional(),limit:z(1,1e4).optional(),page:Pe.default(1),itemsPerPage:z(1,50).optional(),excludeDir:de.array(de.string()).optional().describe('Directory names to prune from the walk (e.g. ["node_modules","dist","coverage"]). NOTHING is excluded by default \u2014 results include build output and vendor dirs unless you pass this explicitly.')},ox=de.object(Object.fromEntries(Object.entries(sI.shape).filter(([e])=>e!=="regexType")));cI=Ce(ox,rx),yr=be(ox,rx).superRefine(aI),ls=ge(cI,{maxQueries:5}),lI=de.object({name:de.string().optional(),path:de.string().optional(),type:de.enum(["file","dir","directory","link","symlink"]).optional(),size:de.union([de.number(),de.string()]).optional(),sizeFormatted:de.string().optional(),modified:de.string().optional(),accessed:de.string().optional(),created:de.string().optional(),permissions:de.string().optional()}),uI=de.object({path:de.string().optional(),files:de.array(lI).optional(),summary:de.string().optional(),pagination:In.optional(),next:de.record(de.string(),xe).optional(),warnings:de.array(de.string()).optional()}),$X=de.object({results:de.array(de.object({id:de.string(),status:de.enum(["empty","error"]).optional(),data:uI}))}).extend(Mn)});function Ro(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 us(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var ds=f(()=>{"use strict"});function Bm(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+us(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Ro(r)})`}function zm(e,t){let n=e.length,r=t.itemsPerPage||zt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function dI(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 ps(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`]}var hl=f(()=>{"use strict";bo();ds()});function mI(e,t){let n=t??pI,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function br(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=bt(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:mI(i.path,i.excludeDir)},{warnings:a,query:c}=bI(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,m=u.wasCapped,p=u.entries.map(Y=>fI(Y,r)),h=e.sortBy||"modified";hI(p,h,r);let g=p.slice(0,l),y=gI(g,t,n),b=y.length,S=e.itemsPerPage||20,C=e.page||1,k=Math.max(1,Math.ceil(b/S)),E=(C-1)*S,_=Math.min(E+S,b),G=y.slice(E,_),M=[...u.warnings,...ps(u)],A=[...a,...M],W=C<k,H={...b===0?{status:"empty"}:{},path:i.path,files:G,pagination:{currentPage:C,totalPages:k,filesPerPage:S,totalFiles:b,hasMore:W,...W?{nextPage:C+1}:{},...m||d>b?{totalFilesFound:d}:{}},...W?{next:{nextPage:Fc(v.LOCAL_FIND_FILES,{...i,page:C+1},"Continue to the next page of matched files.")}}:{},...A.length>0&&{warnings:A}};return V(ix(H,e,{totalFiles:b}),u.entries.reduce((Y,I)=>Y+I.path.length,0))}catch(o){return N(o,e,{toolName:v.LOCAL_FIND_FILES})}}function fI(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 ix(e,t,n){return e}function hI(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 gI(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=Ro(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function bI(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!yI.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var pI,yI,So=f(()=>{"use strict";Bt();ds();Le();me();ce();le();qe();hl();pI=[];yI=/^\d+[hdwm]$/});async function sx(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=pt(yr,n);return r.ok===!1?r.error:await br(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var Um=f(()=>{"use strict";fl();me();Xe();So();Me();Dn();So()});import{z as F}from"zod";import{RipgrepQuerySchema as ax}from"@octocodeai/octocode-core/schemas";var RI,SI,cx,PI,xI,CI,on,ms,wI,TI,EI,P5,fs=f(()=>{"use strict";ce();nt();mt();dt();qe();RI=["paginated","discovery","detailed","structural"],SI=["semanticRanking"],cx={mode:F.enum(RI).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 ghHistoryResearch\'s `patches.mode` \u2014 different concepts sharing this name.)'),keywords:F.string().optional().describe("The search pattern (text or regex). Set fixedString:true for a literal match, or perlRegex:true for advanced regex features (lookaheads, backreferences). (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)"),filesOnly:F.boolean().optional().describe("Returns matching file paths without line content. Mutually exclusive with filesWithoutMatch. (Unlike localViewStructure's `filesOnly`, which filters a directory listing to file entries only \u2014 a different concept sharing this name.)"),pattern:F.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:F.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."),contextLines:ao,matchContentLength:z(1,1e5).optional().default(500),maxMatchesPerFile:z(1,1e5).optional(),maxFiles:z(1,1e5).optional(),matchPage:Pe.optional(),itemsPerPage:z(1,1e3).optional(),page:Pe.default(1),unique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},PI={...cx,semanticRanking:F.never().optional()},xI=Ce(ax,PI),CI=be(ax,cx,{strict:!0,omit:SI}),on=CI.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),ms=ge(xI,{maxQueries:5}),wI=F.object({line:F.number(),endLine:F.number().optional(),value:F.string().optional(),column:F.number().optional(),endColumn:F.number().optional(),count:F.number().optional(),kind:F.string().optional(),scoreHint:F.number().optional(),metavars:F.record(F.string(),F.array(F.string())).optional(),metavarRanges:F.record(F.string(),F.array(F.object({text:F.string(),line:F.number(),column:F.number(),endLine:F.number(),endColumn:F.number()}))).optional()}),TI=F.object({path:F.string(),matches:F.array(wI).optional(),totalOccurrences:F.number().optional(),totalMatchedLines:F.number().optional(),totalMatchRows:F.number().optional(),returnedMatchRows:F.number().optional(),ranking:F.object({score:F.number(),profile:F.string().optional(),pathRole:F.string().optional(),reasons:F.array(F.string()).optional()}).optional(),matchPagination:In.optional(),pagination:In.optional(),next:F.record(F.string(),xe).optional()}),EI=F.object({files:F.array(TI).optional(),summary:F.string().optional(),searchEngine:F.string().optional(),stats:F.object({totalOccurrences:F.number().optional(),matchedLines:F.number().optional(),filesMatched:F.number().optional(),filesSearched:F.number().optional(),bytesSearched:F.number().optional(),searchTime:F.string().optional()}).passthrough().optional(),pagination:In.optional(),next:F.record(F.string(),xe).optional(),warnings:F.array(F.string()).optional()}),P5=F.object({results:F.array(F.object({id:F.string(),status:F.enum(["empty","error"]).optional(),data:EI}))}).extend(Mn)});function ys(e){return gl.exec(e)?.[1]?.toLowerCase()??""}function II(e){let t=ys(e);if(!t)return!1;for(let n of FI)if(hs[n].extensions.includes(t))return!0;return!1}function Km(e,t,n){if(n&&n!=="auto")return hs[n];let r=ys(e),o=(t??"").toLowerCase();for(let i of $m){let s=hs[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of $m){let s=hs[i];if(i!=="generic"&&s.extensions.includes(r))return s}return hs.generic}function yl(e){return kI.test(e)?"generated":vI.test(e)?"fixture":OI.test(e)?"test":LI.test(e)?"config":AI.test(e)?"docs":!gs.test(e)&&(_I.test(e)||II(e))?"source":"unknown"}function Ym(e){if(!e)return!1;if(gs.test(e))return!0;let t=yl(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var $m,pe,qm,Wm,lx,hs,Vm,gs,kI,OI,vI,AI,LI,_I,FI,gl,bl=f(()=>{"use strict";$m=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],pe={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},qm=2e3,Wm=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,lx={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+['"]/]},hs={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...lx},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...lx},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/]}},Vm=/^\s*#{1,6}\s/,gs=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,kI=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,OI=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,vI=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,AI=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,LI=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,_I=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,FI=new Set(["typescript","javascript","rust","python","go","java","scala"]),gl=/\.([a-z0-9]+)$/i});function Xm(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(ux),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??qm,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(ux);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=nf(i,n),l=i.map(d=>{try{return{file:d,s:rf(d,n,c)}}catch{return{file:d,s:MI()}}});l.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function MI(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function ux(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function bs(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Rl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jm(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function Zm(e,t,n){if(e.indexOf(`
|
|
42
42
|
`)<0)return e;let o=e.split(`
|
|
43
|
-
`);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 ef(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Wm.test(e))return"comment";let o=MI(e,t,r);if(o<0)return"code";let i=DI(e);return i>=0&&o>i?"comment":lx(e,o)?"string":"code"}function MI(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function DI(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 lx(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!==""}var tf=f(()=>{"use strict";bl();of()});function NI(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function GI(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 HI(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Jm(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=Zm(l,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Rl(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=pe.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=pe.exactCaseInsensitive,m.push("case-insensitive match")):u.includes(r)&&(d+=pe.substring,m.push("substring match")));let p=c.kind;if(p)d+=QI(p,m);else{let h=ef(u,r,t.id,n.caseSensitive);h!=="code"?(d+=pe.commentOrStringPenalty,m.push(h==="comment"?"comment match (weak)":"string literal (weak)")):(ys(t.declaration,u)&&(d+=pe.declarationLine,m.push("declaration line")),ys(t.export,u)&&(d+=pe.exportLine,m.push("export/public line")),ys(t.import,u)&&(d+=pe.importLine,m.push("import line")),t.id==="markdown"&&Vm.test(u)&&(d+=pe.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&jI(u,r)&&(d+=pe.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function QI(e,t){switch(e){case"declaration":return t.push("AST: declaration"),pe.declarationLine;case"export":return t.push("AST: export/public"),pe.exportLine;case"configKey":return t.push("AST: config key"),pe.configKeyLine;case"heading":return t.push("AST: heading"),pe.headingLine;case"import":return t.push("AST: import"),pe.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),pe.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function jI(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 BI(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(gl,"").includes(l))&&(s+=pe.pathSegmentToken,i.push("query token in path"))}let a=gs(e);return r.extensions.includes(a)&&t.langType&&(s+=pe.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=pe.sourceDir,i.push("source file")),s}function zI(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),pe.lowSignalPathPenalty):0}function UI(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*pe.matchCountScale,r=Math.min(n,pe.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function nf(e,t){let n=GI(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=>$I(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 $I(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Rl(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function qI(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*pe.rareQueryTokenScale,pe.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function rf(e,t,n){let r=Km(e.path,t.langType,t.profileOverride),o=yl(e.path),i=NI(t.keyword),s=[],a=0;return a+=HI(e.matches,r,t,i,s),a+=BI(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=pe.pathUnderQuery,s.push("under requested subtree")),a+=zI(o,t,s),hs.test(e.path)&&!t.explicitLowSignal&&(a+=pe.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=UI(e.matchCount??0,s),a+=qI(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var of=f(()=>{"use strict";bl();tf()});var ux=f(()=>{"use strict";bl();of();tf()});function dx(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=KI(i);s.fetch={tool:"localGetFileContent",query:sf({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?"heuristic":"exact"};let a=YI(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:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:sf({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:sf({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function KI(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 YI(e,t,n){if(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)return;if(n==="structural")return XI(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.onlyMatching){let o=af(e?.value);return o?{symbol:o}:void 0}let r=af(t.keywords);return r?{symbol:r}:void 0}function XI(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=af(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function af(e){if(typeof e!="string")return;let t=e.trim();if(VI.test(t)&&!WI.has(t))return t}function sf(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var WI,VI,cf=f(()=>{"use strict";WI=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"]),VI=/^[A-Za-z_$][A-Za-z0-9_$]*$/});async function Sl(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=Xm(e,s,JI(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),m=!!(t.countLinesPerFile||t.countMatchesPerFile),p=d||m,h=c.reduce((H,Y)=>H+(Y.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??h:h,y=t,b=Math.min(y.itemsPerPage||zt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=y.page||1,C=Math.max(1,Math.ceil(u/b)),k=(S-1)*b,E=Math.min(k+b,u),_=c.slice(k,E),w=y.maxMatchesPerFile||zt.DEFAULT_MATCHES_PER_PAGE,G=_.map(H=>{let Y=H.matches?.length??0,I=Math.ceil(Y/w),Re=Math.max(1,y.matchPage||1),Oe=(Re-1)*w,hn=Math.min(Oe+w,Y),zo=p?void 0:H.matches?.slice(Oe,hn),xa=zo?.length,Uo=l?.get(H.path);return{path:H.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:H.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:H.matchCount||1}:{totalMatchRows:Y,...xa!==void 0?{returnedMatchRows:xa}:{}},...zo!==void 0&&{matches:zo},...Uo?{ranking:{score:Uo.score,profile:Uo.profile,pathRole:Uo.pathRole,reasons:Uo.reasons}}:{},pagination:!p&&Y>w?{currentPage:Re,totalPages:I,matchesPerPage:w,totalMatches:Y,hasMore:Re<I,...Re<I?{nextMatchPage:Re+1}:{}}:void 0}}),M=G.filter(H=>H.pagination?.hasMore),A=dx(G,t,n,{isFileListMode:p,currentPage:S,totalFilePages:C,matchPage:y.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:M.length>0}),W={searchEngine:n,...o?{stats:o}:{},files:G,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<C,...S<C?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return px(W,t,{totalMatches:g,totalFiles:u})}function px(e,t,n){return e}function JI(e){let t=e.rankingProfile,n=!!(e.include?.length||Ym(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var mx=f(()=>{"use strict";yo();ux();cf()});var bs=f(()=>{"use strict";mx();cf()});function fx(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&ZI(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&e0(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function ZI(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function e0(e){return/\(\?[=!<]/.test(e)}var lf=f(()=>{"use strict";Le()});import{validateRipgrepQuery as t0}from"@octocodeai/octocode-core/schemas/runtime";function n0(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function r0(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:n0(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function o0(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function hx(e){let t=[],n=t0(e);if(!n.isValid)return N(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=on.safeParse(e);if(!r.success){let g=r.error.issues.map(y=>y.message);return N(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return N(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=bt(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=fx({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return N(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(r0(a))}catch(g){return N(g instanceof Error?g:new Error(String(g)),o,{toolName:v.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(y=>{let b={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(b.count=y.count),y.kind!==void 0&&(b.kind=y.kind),y.scoreHint!==void 0&&(b.scoreHint=y.scoreHint),b})})),m=o0(d),p={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return V({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...l]},m);!a.filesOnly&&m>zt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let h=await Sl(d,o,"rg",[...t,...l],p);return V(h,m)}var uf=f(()=>{"use strict";Bt();ms();yo();me();bs();lf();le();Le()});var gx,yx,bx=f(()=>{"use strict";gx={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"]}},yx={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 i0(e){return e.trim().replace(/^\./,"").toLowerCase()}function Rr(e){if(!e?.trim())return;let t=i0(e),n=gx[t]??yx[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function s0(e){return[...e??[]].map(t=>`**/*.${t}`)}function df(e){return[...e??[]].map(t=>`*.${t}`)}function Rs(e){let t=Rr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Pl(e){let t=Rr(e);return t?t.kind==="extension"&&t.extension?{include:s0([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function xl(e){let t=Rr(e);return t?t.kind==="extension"&&t.extension?df([t.extension]):t.kind==="language"?df(t.extensions):t.normalized?df([t.normalized]):[]:[]}function pf(e){let t=Rr(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}function Cl(e){return Rr(e)?.canonicalLanguage}var Rx=f(()=>{"use strict";bx()});var mf=f(()=>{"use strict";Rx()});import{readFile as a0,stat as c0}from"node:fs/promises";function p0(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function Px(e){return e.include?.length?e.include:pf(e.langType)}async function m0(e){try{return(await c0(e)).isFile()}catch{return!1}}async function f0(e,t){let n=await a0(e,"utf8"),r=await D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function xx(e){let t=bt(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await m0(t.sanitizedPath)?await f0(t.sanitizedPath,e):await D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...Px(e)?{include:Px(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Sx.length?{excludeDir:Sx}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??l0,maxFileBytes:u0})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return N(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:v.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(d0+p0(e.pattern)),await Sl(r,e,"structural",i,o)}var Sx,l0,u0,d0,Cx=f(()=>{"use strict";Le();Bt();me();mf();bs();Sx=[],l0=2e3,u0=1e6,d0="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 h0(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Rt(e){let t=h0(e);if(t.mode==="structural")return await xx(t);t.contextLines===void 0&&(t.contextLines=2);try{return await hx(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:q.OUTPUT_TOO_LARGE}:N(n,t,{toolName:v.LOCAL_RIPGREP})}}var Sr=f(()=>{"use strict";Bt();bn();me();uf();Cx()});async function wx(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=pt(on,n);return r.ok===!1?r.error:await Rt(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var ff=f(()=>{"use strict";ms();me();Xe();Sr();Me();Dn();bs()});import{z as ee}from"zod";import{ViewStructureQuerySchema as Tx}from"@octocodeai/octocode-core/schemas";var Ex,g0,Pr,Ss,y0,b0,F3,wl=f(()=>{"use strict";ce();nt();mt();dt();qe();Ex={maxDepth:z(0,20).optional(),limit:z(1,1e4).optional(),page:Pe.default(1),itemsPerPage:z(1,50).optional(),filesOnly:ee.boolean().optional().describe("Returns files only. Mutually exclusive with directoriesOnly. (Unlike localSearchCode's `filesOnly`, which filters search results to matching file paths \u2014 a different concept sharing this name.)")},g0=Ce(Tx,Ex),Pr=be(Tx,Ex),Ss=ge(g0,{maxQueries:5}),y0=ee.object({name:ee.string().optional(),type:ee.enum(["file","dir","directory","link","symlink"]),path:ee.string().optional(),depth:ee.number().optional(),size:ee.union([ee.number(),ee.string()]).optional(),sizeBytes:ee.number().optional(),modified:ee.string().optional(),permissions:ee.string().optional()}),b0=ee.object({path:ee.string().optional(),entries:ee.array(y0).optional(),files:ee.array(ee.string()).optional(),folders:ee.array(ee.string()).optional(),links:ee.array(ee.string()).optional(),summary:ee.union([ee.string(),ee.record(ee.string(),ee.unknown())]).optional(),pagination:In.optional(),next:ee.record(ee.string(),xe).optional(),warnings:ee.array(ee.string()).optional()}),F3=ee.object({results:ee.array(ee.object({id:ee.string(),status:ee.enum(["empty","error"]).optional(),data:b0}))}).extend(Mn)});function P0(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function kx(e,t){let n=e[t];return n===void 0?!1:R0.has(n)||n==="{"&&w0(e,t)}function x0(e,t,n){let r=n.pop()??!1,o=kx(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?Ox(e,t+1):t+1})}function C0(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Ox(e,t)})}function hf(e){if(e.length>S0)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=P0(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=x0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(kx(e,r)){let i=C0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function w0(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 Ox(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function M3(e,t){let n=hf(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}var R0,S0,gf=f(()=>{"use strict";R0=new Set(["+","*","?"]),S0=1e3});function vx(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(!hf(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function Ax(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 Lx(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}var yf=f(()=>{"use strict";gf()});async function Tl(e){try{let t=bt(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return T0(e,t.sanitizedPath,n)}catch(t){let n=at.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function T0(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=k0(e),s=r&&e.limit&&!E0(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:O0(e),limit:s})}catch(C){return L0(C,e,t)}let c=a.entries.map(C=>v0(C,n,e.details??!1)),l=vx(c,e),u=e.sortBy??"name";l=l.sort((C,k)=>{let E=0;switch(u){case"size":{let _=C.sizeBytes??(C.size?ls(C.size):0),w=k.sizeBytes??(k.size?ls(k.size):0);E=_-w;break}case"time":n&&C.modified&&k.modified?E=C.modified.localeCompare(k.modified):E=C.name.localeCompare(k.name);break;case"extension":E=(C.extension||"").localeCompare(k.extension||"");break;default:E=C.name.localeCompare(k.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:m,pagination:p}=zm(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(C=>({...Lx(C),path:C.path??`${t.replace(/\/$/,"")}/${C.name}`}))}:{path:t,...Ax(m)},y=[...a.warnings,...ds({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],b=d===0,S=Bm(l);return V(_x({...b?{status:"empty"}:{},...g,summary:S,...p.hasMore||p.totalPages>1?{pagination:p}:{},...p.hasMore?{next:{nextPage:Fc(v.LOCAL_VIEW_STRUCTURE,{...e,page:p.currentPage+1},"Continue to the next page of directory entries.")}}:{},...y.length>0&&{warnings:y}},e),a.entries.reduce((C,k)=>C+k.path.length,0))}function E0(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function k0(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function O0(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function v0(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:bo(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=A0(e.permissions)),o}function A0(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 L0(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=at.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return N(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function _x(e,t){return e}var Ps=f(()=>{"use strict";us();me();Bt();Yo();yf();hl();le();Le();qe()});async function Fx(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=pt(Pr,n);return r.ok===!1?r.error:await Tl(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var bf=f(()=>{"use strict";wl();me();Xe();Ps();Me();Dn();Ps()});var Nn,xs,Rf,Sf,Ix=f(()=>{"use strict";Nn=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","diff","research","graph","materialize"],xs=["fixes","dataflow"],Rf=["packages","repositories"],Sf={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});function Pf(e){return Array.isArray(e.queries)}function xf(e){return Array.isArray(e.queries)}function Cf(e){return Array.isArray(e.children)}var Mx=f(()=>{"use strict"});var Gn=f(()=>{"use strict";Ix();Mx()});import{z as $}from"zod";var Dx,Nx,_0,F0,xr,wf,I0,M0,Hn,Gx=f(()=>{"use strict";Dx=$.enum(["smart","sensitive","insensitive"]),Nx=$.string().max(1e4),_0=$.strictObject({id:$.string().optional(),kind:$.literal("text"),value:Nx,case:Dx.optional(),wholeWord:$.boolean().optional()}),F0=$.strictObject({id:$.string().optional(),kind:$.literal("regex"),value:Nx,dialect:$.enum(["rust","pcre2","provider"]).optional(),case:Dx.optional(),wholeWord:$.boolean().optional(),multiline:$.boolean().optional(),dotAll:$.boolean().optional()}),xr=$.lazy(()=>$.strictObject({pattern:$.string().optional(),kind:$.string().optional(),inside:xr.optional(),has:xr.optional(),not:xr.optional(),all:$.array(xr).optional(),any:$.array(xr).optional(),stopBy:$.literal("end").optional()})),wf=$.union([xr,$.string().min(1)]),I0=$.strictObject({id:$.string().optional(),kind:$.literal("structural"),lang:$.string().min(1),pattern:$.string().optional(),rule:wf.optional()}),M0=$.strictObject({id:$.string().optional(),kind:$.literal("field"),field:$.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:$.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:$.unknown().optional()}),Hn=$.lazy(()=>$.discriminatedUnion("kind",[$.strictObject({kind:$.literal("all"),id:$.string().optional(),of:$.array(Hn).min(1)}),$.strictObject({kind:$.literal("any"),id:$.string().optional(),of:$.array(Hn).min(1)}),$.strictObject({kind:$.literal("not"),id:$.string().optional(),predicate:Hn}),_0,F0,I0,M0]))});import{z as P}from"zod";var Ef,Tf,D0,Hx,Qx,jx,Bx,El,N0,mJ,zx,Ux,$x,qx,Cs,Wx,Vx,Qn,Cr=f(()=>{"use strict";Gn();Gx();Ef=P.lazy(()=>P.union([P.strictObject({kind:P.literal("local"),path:P.string().min(1)}),P.strictObject({kind:P.literal("github"),repo:P.string().min(1).optional(),owner:P.string().min(1).optional(),ref:P.string().min(1).optional()}),P.strictObject({kind:P.literal("materialized"),localPath:P.string().min(1),source:Ef.optional()}),P.strictObject({kind:P.literal("npm")})])),Tf=P.union([P.string(),P.array(P.string()).max(100)]),D0=P.strictObject({path:Tf.optional(),language:Tf.optional(),include:P.array(P.string()).max(100).optional(),exclude:P.array(P.string()).max(100).optional(),excludeDir:P.array(P.string()).max(100).optional(),hidden:P.boolean().optional(),noIgnore:P.boolean().optional(),minDepth:P.number().int().min(0).max(64).optional(),maxDepth:P.number().int().min(0).max(64).optional()}).optional(),Hx=P.strictObject({mode:P.enum(["never","auto","required"]),strategy:P.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:P.boolean().optional(),forceRefresh:P.boolean().optional()}),Qx=P.strictObject({content:P.strictObject({range:P.strictObject({startLine:P.number().int().min(1).optional(),endLine:P.number().int().min(1).optional(),contextLines:P.number().int().min(0).max(100).optional()}).optional(),match:P.strictObject({text:P.string(),regex:P.boolean().optional(),caseSensitive:P.boolean().optional()}).optional(),contentView:P.enum(["none","standard","symbols","exact","compact"]).transform(e=>e==="exact"?"none":e==="compact"?"standard":e).optional(),charOffset:P.number().int().min(0).max(1e8).optional(),charLength:P.number().int().min(1).max(5e4).optional(),fullContent:P.boolean().optional()}).optional(),tree:P.strictObject({maxDepth:P.number().int().min(0).max(64).optional(),pattern:P.string().optional(),includeSizes:P.boolean().optional(),extensions:P.array(P.string()).optional(),filesOnly:P.boolean().optional(),directoriesOnly:P.boolean().optional(),sortBy:P.enum(["name","size","time","extension"]).optional(),reverse:P.boolean().optional()}).optional()}),jx=P.strictObject({search:P.strictObject({countLinesPerFile:P.boolean().optional(),countMatchesPerFile:P.boolean().optional(),onlyMatching:P.boolean().optional(),unique:P.boolean().optional(),countUnique:P.boolean().optional(),contextLines:P.number().int().min(0).max(100).optional(),invertMatch:P.boolean().optional(),matchWindow:P.number().int().min(0).optional(),matchContentLength:P.number().int().min(1).optional(),maxMatchesPerFile:P.number().int().min(1).optional(),matchPage:P.number().int().min(1).optional(),sort:P.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:P.boolean().optional(),rankingProfile:P.string().optional(),debugRanking:P.boolean().optional()}).optional(),budget:P.strictObject({maxFiles:P.number().int().min(1).optional(),maxCandidates:P.number().int().min(1).optional(),maxBytes:P.number().int().min(1).optional(),maxMaterializedBytes:P.number().int().min(1).optional(),maxPlanNodes:P.number().int().min(1).optional(),maxBooleanExpansion:P.number().int().min(1).optional(),timeoutMs:P.number().int().min(1).optional()}).optional()}),Bx=P.enum(["discovery","paginated","detailed"]),El=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),target:P.enum(Nn),from:Ef.optional(),scope:D0,where:Hn.optional(),materialize:Hx.optional(),fetch:Qx.optional(),select:P.array(P.string()).optional(),view:Bx.optional(),controls:jx.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional()}),N0=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),queries:P.array(El).min(1).max(5),combine:P.enum(["independent","merge"]).optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),explain:P.boolean().optional()}),mJ=P.union([El,N0]),zx=[...Nn,...xs],Ux={schema:P.literal("oql").optional(),id:P.string().optional(),mainResearchGoal:P.string().optional(),researchGoal:P.string().optional(),reasoning:P.string().optional()},$x={...Ux,target:P.enum(zx).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Ef.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:Hn.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:P.union([Hx,P.enum(["never","auto","required"])]).optional(),fetch:Qx.optional(),select:P.array(P.string()).optional(),view:Bx.optional(),controls:jx.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional(),repo:P.string().optional(),owner:P.string().optional(),ref:P.string().optional(),path:Tf.optional(),text:P.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:P.string().optional(),pattern:P.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:wf.optional(),lang:P.string().optional(),and:P.array(P.unknown()).optional(),or:P.array(P.unknown()).optional(),xor:P.array(P.unknown()).optional(),noneOf:P.array(P.unknown()).optional(),oneOf:P.array(P.unknown()).optional(),invert:P.unknown().optional(),filesOnly:P.boolean().optional(),filesWithoutMatch:P.boolean().optional(),verbose:P.boolean().optional()},qx={...$x,target:P.enum(zx).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},Cs=P.object(qx).catchall(P.unknown()),Wx=P.object($x).catchall(P.unknown()),Vx=P.object({...Ux,queries:P.array(P.unknown()).min(1)}).catchall(P.unknown()),Qn=P.object({...qx,queries:P.array(P.unknown()).min(1).max(5).optional(),combine:P.enum(["independent","merge"]).optional()}).catchall(P.unknown())});function x(e,t,n={}){let r=n.severity??(H0.has(e)?"error":"warning"),o=n.blocksAnswer??(G0.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function Kx(e){return e.some(t=>t.blocksAnswer)}var G0,H0,sn,ne=f(()=>{"use strict";G0=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),H0=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);sn=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});function Z(...e){throw new sn(e)}function wr(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var So=f(()=>{"use strict";ne()});import{z as T}from"zod";function Xx(e,t){let n=Y0[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var _e,Q0,Yx,j0,B0,z0,U0,$0,q0,W0,V0,K0,Y0,Jx=f(()=>{"use strict";_e=T.number().int().min(1),Q0=T.number().int().min(0),Yx=T.enum(["symbols","files","dependencies","relations"]),j0=T.object({match:T.enum(["file","path"]).optional(),concise:T.boolean().optional(),extension:T.string().optional(),filename:T.string().optional(),page:_e.optional(),limit:_e.optional()}).passthrough(),B0=T.object({type:T.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:T.string().optional(),symbolName:T.string().optional(),symbolKind:T.string().optional(),lineHint:_e.optional(),orderHint:T.number().int().optional(),includeDeclaration:T.boolean().optional(),depth:T.number().int().min(0).max(20).optional(),groupByFile:T.boolean().optional(),workspaceRoot:T.string().optional(),format:T.enum(["structured","compact"]).optional(),page:_e.optional(),itemsPerPage:_e.optional()}).passthrough(),z0=T.object({keywords:T.array(T.string()).optional(),topicsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:T.string().optional(),owner:T.string().optional(),stars:T.union([T.string(),T.number()]).optional(),forks:T.string().optional(),goodFirstIssues:T.string().optional(),size:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),license:T.string().optional(),match:T.array(T.enum(["name","description","readme"])).optional(),visibility:T.enum(["public","private"]).optional(),archived:T.boolean().optional(),sort:T.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:T.boolean().optional(),page:_e.optional()}).passthrough(),U0=T.object({packageName:T.string().optional(),keywords:T.array(T.string()).optional(),mode:T.enum(["lean","full"]).optional(),page:_e.optional()}).passthrough(),$0=T.object({prNumber:_e.optional(),concise:T.boolean().optional(),state:T.enum(["open","closed","merged"]).optional(),author:T.string().optional(),label:T.union([T.string(),T.array(T.string())]).optional(),keywordsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:T.string().optional(),base:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),closed:T.string().optional(),"merged-at":T.string().optional(),draft:T.boolean().optional(),archived:T.boolean().optional(),sort:T.enum(["created","updated","best-match","comments","reactions"]).optional(),order:T.enum(["asc","desc"]).optional(),reviewMode:T.string().optional(),filePage:_e.optional(),commentPage:_e.optional(),commitPage:_e.optional(),charOffset:Q0.optional(),charLength:_e.optional(),minify:T.enum(["none","standard"]).optional(),limit:_e.optional(),page:_e.optional(),matchString:T.string().optional(),matchScope:T.enum(["body","title","comments","reviews","all"]).optional(),content:T.record(T.string(),T.unknown()).optional()}).passthrough(),q0=T.object({path:T.string().optional(),branch:T.string().optional(),since:T.string().optional(),until:T.string().optional(),author:T.string().optional(),includeDiff:T.boolean().optional(),limit:_e.optional(),page:_e.optional()}).passthrough(),W0=T.object({prNumber:_e.optional(),files:T.array(T.string()).optional(),baseRef:T.string().optional(),headRef:T.string().optional(),path:T.string().optional()}).passthrough(),V0=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(Yx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:_e.optional()}).passthrough(),K0=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(Yx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:_e.optional(),subject:T.string().optional(),subjectKind:T.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:T.union([T.string(),T.array(T.string())]).optional(),verdict:T.union([T.string(),T.array(T.string())]).optional(),direction:T.enum(["incoming","outgoing","both"]).optional(),proof:T.enum(["none","lsp"]).optional(),proofLimit:_e.max(25).optional(),includePackets:T.boolean().optional(),includeFacts:T.boolean().optional(),includeEdges:T.boolean().optional()}).passthrough(),Y0={semantics:B0,repositories:z0,packages:U0,pullRequests:$0,commits:q0,diff:W0,research:V0,graph:K0,code:j0}});function Zx(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&Z(x("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),X0(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Rf.includes(t)||Z(x("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function X0(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}var eC=f(()=>{"use strict";ne();Gn();So()});function tC(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&Z(x("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}var nC=f(()=>{"use strict";ne();So()});function Po(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Po(n),0):e.kind==="not"?1+Po(e.predicate):1:0}var kf=f(()=>{"use strict"});function rC(e,t){let n=eM(e);e.where&&n&&Z(x("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Of(r,"where"),vf(r,"where",new Map);let o=Hn.safeParse(r);return o.success||Z(x("invalidQuery",wr(o.error),{queryPath:"where"})),o.data}function Z0(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:J0}function eM(e){let t=n=>{let r=Po(n),o=Z0(e);return r>o&&Z(x("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(xo)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(xo)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(xo)}};if(Array.isArray(e.xor)){e.xor.length!==2&&Z(x("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=xo(e.xor[0]),r=xo(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(tM(e.oneOf.map(xo)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&Z(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&Z(x("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function xo(e){if(e&&typeof e=="object"&&"kind"in e)return e;Z(x("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function tM(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Of(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&Z(x("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Of(n,`${t}.of[${r}]`));break;case"not":e.predicate||Z(x("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Of(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&Z(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":nM(e,t);break;default:break}}function vf(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&Z(x("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>vf(r,`${t}.of[${o}]`,n)):e.kind==="not"&&vf(e.predicate,`${t}.predicate`,n)}function nM(e,t){if(e.op==="exists"){e.value!==void 0&&Z(x("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&Z(x("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&Z(x("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}var J0,oC=f(()=>{"use strict";Cr();ne();kf();So();J0=64});function iC(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return iC(e.predicate);default:return!1}}function sC(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:iC(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}var aC=f(()=>{"use strict"});function cC(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!oM(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function oM(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return rM.some(n=>t.includes(n))}var rM,lC=f(()=>{"use strict";rM=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"]});function ws(e){let t=Wx.safeParse(e);t.success||Z(x("invalidQuery",wr(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??sM(n);r===void 0&&Z(x("invalidQuery",`Could not determine \`target\`; specify one of: ${Nn.join(", ")}.`,{queryPath:"target"})),xs.includes(r)&&Z(x("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${Nn.join(", ")}.`}})),Nn.includes(r)||Z(x("unknownField",`Unknown target "${r}".`));for(let h of Object.keys(n))iM.has(h)||Z(x("unknownField",`Unknown field "${h}" is not part of OQL.`,{queryPath:h}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=Zx(n,r),a=tC(n,s),c=rC(n,r),l=sC(n,s,c,r),u=aM(n),d=cC(n,r),m={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(m.target==="code"&&!m.where&&Z(x("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.where&&Z(x("invalidQuery",`target:"${m.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.from?.kind==="github"&&!(m.from.repo&&m.from.repo.includes("/"))&&Z(x("invalidQuery",`target:"${m.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),m.target==="materialize"&&(m.where&&Z(x("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),m.from?.kind!=="github"&&m.from?.kind!=="materialized"&&Z(x("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),m.params!==void 0){let h=Xx(m.target,m.params);h&&Z(x("invalidQuery",h,{queryPath:"params"}))}let p=El.safeParse(m);return p.success||Z(x("invalidQuery",wr(p.error))),p.data}function sM(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function aM(e){return e.fetch?{...e.fetch}:void 0}var iM,kl=f(()=>{"use strict";Cr();ne();Jx();Gn();So();eC();nC();oC();aC();lC();iM=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"])});function uC(e){let t=Vx.safeParse(e);t.success||Z(x("invalidQuery",wr(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||Z(x("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&Z(x("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return ws(i)}catch(a){throw a instanceof sn?new sn(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}var dC=f(()=>{"use strict";Cr();ne();So();kl()});function pC(e){return Pf(e)?uC(e):ws(e)}var mC=f(()=>{"use strict";Gn();dC();kl();kl()});function Ts(e){let t=lM(e),n=dM(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function lM(e){return!e.executable||e.diagnostics.some(t=>cM.has(t.code))?"unsupported":e.approximate||uM(e.diagnostics)?"candidate":Kx(e.diagnostics)||fC(e)?"partial":"proof"}function uM(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function fC(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function dM(e){return!e.executable||fC(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function hC(e){return e.some(t=>!t.exact)}function Ol(e,t,n,r,o){return Ts({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var cM,Es=f(()=>{"use strict";ne();cM=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function vl(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(vl):e.kind==="not"?vl(e.predicate):[e]}function Af(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function Qe(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Co(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Lf(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var jn=f(()=>{"use strict"});import Tr from"node:path";import{statSync as pM}from"node:fs";function gC(e){let t=Tr.resolve(e);try{if(pM(t).isDirectory())return`${t}${Tr.sep}`}catch{}return`${Tr.dirname(t)}${Tr.sep}`}function yC(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function bC(e,t){let n=yC(e);if(!n)return;let r=gC(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function RC(e){let t=yC(e);if(!t)return;let n=gC(t).slice(0,-Tr.sep.length);return r=>({kind:"local",path:Tr.isAbsolute(r)?r:Tr.join(n,r)})}var _f=f(()=>{"use strict"});function SC(e,t){for(let n of t)n.proofGrade??=mM(e,n)}function mM(e,t){return t.kind==="code"?ks(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":ks(e.where,"text")||ks(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?Os(t.data)?"missing":"graph":t.recordType==="research"?Os(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"?"text":"candidate"}function ks(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>ks(n,t)):e.kind==="not"?ks(e.predicate,t):!1:!1}function Os(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!fM(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function fM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ff=f(()=>{"use strict"});function hM(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function PC(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:hM(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"none",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function xC(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function gM(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function yM(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function CC(e){let t=yM(e);return t?gM(t,"materialized"):void 0}function wC(e,t){return EC(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function TC(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(Os(r))return EC(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function EC(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!Os(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=RM(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function RM(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&bM.has(o));return r.length>0?r:void 0}var bM,kC=f(()=>{"use strict";Ff();bM=new Set(["symbols","files","dependencies","relations"])});import vs from"node:path";import{statSync as SM}from"node:fs";function OC(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=CM(e)??wM(t.query),i=PM(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"none",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function PM(e,t){if(e&&vs.isAbsolute(e))return e;if(t&&vs.isAbsolute(t)){let n=xM(t);return e?vs.resolve(n,e):t}return t??e}function xM(e){try{return SM(e).isDirectory()?e:vs.dirname(e)}catch{return vs.dirname(e)}}function CM(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function wM(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}var vC=f(()=>{"use strict"});function TM(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function EM(e){let t=TM(e),n=Qe(e.scope),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${AC(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${AC(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function AC(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function LC(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${EM(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:RC(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=kM[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function _C(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||If(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function If(e,t){return e.why===t.why&&e.confidence===t.confidence}var kM,Mf=f(()=>{"use strict";jn();_f();kC();vC();kM={code:PC,content:xC,"record:materialized":CC,"record:semantics":OC,"record:research":wC,"record:graph":TC}});import{completeMetadata as OM}from"@octocodeai/octocode-core";function As(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function PZ(e){return vM.has(e)}var X,je,Bn,vM,wo=f(()=>{"use strict";X=OM.toolNames,je=X.LSP_GET_SEMANTIC_CONTENT,Bn="oqlSearch";vM=new Set([X.LOCAL_RIPGREP,X.LOCAL_FETCH_CONTENT,X.LOCAL_FIND_FILES,X.LOCAL_VIEW_STRUCTURE,je])});function an(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Df(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 FC,Lt=f(()=>{"use strict";wo();FC=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{z as te}from"zod";import{NpmPackageQuerySchema as IC}from"@octocodeai/octocode-core/schemas";var MC,Ls,_s,LZ,Nf=f(()=>{"use strict";nt();mt();dt();qe();MC={page:Pe,mode:te.enum(["lean","full"]).optional(),keywords:te.union([te.string(),te.array(te.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},Ls=be(IC,MC),_s=ge(Ce(IC,MC,{strict:!0}),{maxQueries:5}),LZ=te.object({results:te.array(te.looseObject({id:te.string(),data:te.looseObject({packages:te.array(te.object({name:te.string(),version:te.string().optional(),description:te.string().optional(),license:te.string().optional(),downloads:te.number().optional(),repository:te.string().optional(),repositoryDirectory:te.string().optional(),repositoryId:te.string().optional(),next:te.record(te.string(),xe).optional(),warnings:te.array(te.string()).optional(),diagnostics:te.array(lo).optional()}).passthrough()).optional(),repositories:te.record(te.string(),te.object({repository:te.string(),owner:te.string(),repo:te.string(),repositoryDirectory:te.string().optional(),next:te.record(te.string(),xe)}).passthrough()).optional(),pagination:ut.optional()}).optional(),status:te.string().optional()})).optional()}).extend(We)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as GC}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as AM}from"@octocodeai/octocode-core/schemas/outputs";var LM,_M,FM,HC,IM,Eo,MM,ko,DC,DM,NM,Al,Ll,GM,HM,QC,To,QM,jM,BM,jC,zM,UM,$M,qM,WM,VM,KM,NC,YM,_l=f(()=>{"use strict";ce();nt();mt();Lt();qe();LM=z(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),_M=z(0,1e5).optional(),FM=["structured","compact"],HC={type:R.enum(FC).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:R.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:LM.optional(),orderHint:_M,depth:z(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:Pe,itemsPerPage:z(1,100).optional(),contextLines:z(0,100).optional(),format:R.enum(FM).optional().default("structured")},IM=Ce(GC,HC),Eo=be(GC,HC),MM=Eo,ko=ge(IM,{maxQueries:5}),DC=R.object({line:R.number(),character:R.number()}),DM=R.object({start:DC,end:DC}),NM=R.object({startLine:R.number(),endLine:R.number()}),Al=R.object({uri:R.string(),content:R.string().optional(),displayRange:NM.optional(),isDefinition:R.boolean().optional()}),Ll=R.string(),GM=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),HM=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),QC=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),To=R.object({category:QC,reason:R.string()}),QM=ut,jM=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),BM=R.string(),jC=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),zM=R.string(),UM=R.object({direction:R.enum(["incoming","outgoing"]),item:jC,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),$M=R.string(),qM=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),WM=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),VM=R.string(),KM=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Al,Ll]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Al,Ll]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Al,Ll]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Al,Ll])).optional(),byFile:R.array(R.union([WM,VM])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:To.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([jC,zM]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([UM,$M])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:qM,empty:To.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:DM.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([jM,BM])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:To.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:To.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:To.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:To.optional()}),R.object({kind:R.literal("empty"),category:QC,reason:R.string()})]),NC=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:GM.optional(),lsp:HM.optional(),payload:KM,pagination:QM.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional(),next:R.record(R.string(),xe).optional(),hints:R.array(R.string()).optional()}),YM=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:NC}),R.object({id:R.string().min(1),status:R.literal("error"),data:AM}),R.object({id:R.string().min(1),data:NC})]))})});var Gf=f(()=>{"use strict";am();Uc();gm();ul();Fm();Mm();Nf();ml();fl();ms();wl();_l();Cr()});import{z as BC}from"zod";function Er(e){return ZM.find(t=>t.name===e)}function Fs(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===X.PACKAGE_SEARCH?"Package":"Other"}function s6(e){return[...e].sort((t,n)=>{let r=zC.indexOf(Fs(t)),o=zC.indexOf(Fs(n));if(r!==o)return r-o;let i=UC.get(t)??Number.MAX_SAFE_INTEGER,s=UC.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function a6(e){let t=Er(e);if(!t)return"{}";try{return JSON.stringify(BC.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(BC.toJSONSchema(t.schema,{io:"input"}),null,2)}}function c6(e){return JSON.stringify(e??{},null,2)}function l6(e){let t=Fs(e),n=[...JM];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function u6(){return $C.map(e=>({...e}))}function d6(){return JSON.stringify(Object.fromEntries($C.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function p6(e,t){return t?.tools?.[e]?.description??e}var zC,UC,_t,XM,Is,JM,$C,ZM,Ms=f(()=>{"use strict";wo();Lt();Gf();zC=["GitHub","Local Code","Package","Other"],UC=new Map([X.GITHUB_SEARCH_CODE,X.GITHUB_SEARCH_REPOSITORIES,X.GITHUB_SEARCH_PULL_REQUESTS,X.GITHUB_FETCH_CONTENT,X.GITHUB_VIEW_REPO_STRUCTURE,X.GITHUB_CLONE_REPO,X.LOCAL_RIPGREP,X.LOCAL_FIND_FILES,X.LOCAL_FETCH_CONTENT,X.LOCAL_VIEW_STRUCTURE,je,X.PACKAGE_SEARCH,...As()?[Bn]:[]].map((e,t)=>[e,t])),_t=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},XM=["id","mainResearchGoal","researchGoal","reasoning"],Is=new Set([...XM]),JM=["id","researchGoal","reasoning"],$C=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],ZM=[{name:X.GITHUB_SEARCH_CODE,schema:Ki,inputSchema:Yi},{name:X.GITHUB_FETCH_CONTENT,schema:dr,inputSchema:Wi},{name:X.GITHUB_VIEW_REPO_STRUCTURE,schema:os,inputSchema:is},{name:X.GITHUB_SEARCH_REPOSITORIES,schema:ns,inputSchema:rs},{name:X.GITHUB_SEARCH_PULL_REQUESTS,schema:hr,inputSchema:ts},{name:X.PACKAGE_SEARCH,schema:Ls,inputSchema:_s},{name:X.GITHUB_CLONE_REPO,schema:mo,inputSchema:qi},{name:X.LOCAL_RIPGREP,schema:on,inputSchema:ps},{name:X.LOCAL_VIEW_STRUCTURE,schema:Pr,inputSchema:Ss},{name:X.LOCAL_FIND_FILES,schema:yr,inputSchema:cs},{name:X.LOCAL_FETCH_CONTENT,schema:gr,inputSchema:as},{name:je,schema:Eo,inputSchema:ko},...As()?[{name:Bn,schema:Cs,inputSchema:Qn}]:[]]});import{z as eD}from"zod";function Fl(e){let t=Er(e);if(!t)return[];let n=eD.toJSONSchema(t.schema,{io:"input"});if(!Oo(n))return[];let r=cn(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Is.has(i)&&!jf(r[i])):[]);return Qf(r,o)}function tD(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 Hf(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Oo(e.items)?e.items:void 0;return`array<${n?Hf(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Oo).map(Hf).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 Qf(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Is.has(o))continue;let s=Oo(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Hf(s),constraints:tD(s),description:typeof s.description=="string"?s.description:void 0}),cn(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!jf(s.properties?.[u]):!1):[]);r.push(...Qf(s.properties,l,a))}let c=s.type==="array"&&Oo(s.items)?s.items:void 0;if(c&&cn(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!jf(c.properties?.[u]):!1):[]);r.push(...Qf(c.properties,l,a))}}return r}function WC(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[qC(e,n)]}return qC(e,t)}function qC(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 cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oo(e){return cn(e)}function jf(e){return Oo(e)&&"default"in e}var Il=f(()=>{"use strict";Ms()});function VC(e){return e===Bn?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===X.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"2024-01-01T00:00:00Z",perPage:5}},{label:"releases + latest",query:{type:"releases",owner:"microsoft",repo:"TypeScript",perPage:5}},{label:"issues search",query:{type:"issues",owner:"microsoft",repo:"TypeScript",keywordsToSearch:["crash"],state:"open",concise:!0,limit:5}},{label:"issue detail",query:{type:"issues",owner:"bgauryy",repo:"octocode",issueNumber:443,content:{body:!0,comments:{discussion:!0}}}}]:e===X.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===X.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===X.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===X.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===X.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",keywords:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===X.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===X.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===X.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,filesOnly:!0,itemsPerPage:100}}]:e===je?[{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}}]:[]}var KC=f(()=>{"use strict";wo()});function YC(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function nD(e){let t=VC(e);if(t.length>0)return t.map(r=>({...r,command:YC(e,r.query)}));let n=rD(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:YC(e,n)}]}function C6(e){return nD(e)[0]?.query??{}}function rD(e){if(!Er(e))return{};let t=Fl(e),n=t.filter(i=>!i.name.includes(".")),r=oD(n),o={};for(let i of r)o[i.name]=WC(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===je&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function oD(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&&iD(i)).sort(sD),o=Math.max(XC,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=>!JC.has(i.name)).filter(i=>i.type!=="boolean").slice(0,XC)}function iD(e){return JC.has(e.name)||e.type==="boolean"?!1:aD(e)?Bf.has(e.name):!0}function sD(e,t){let n=Bf.get(e.name)??Number.MAX_SAFE_INTEGER,r=Bf.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function aD(e){return e.constraints?.includes("default ")===!0}var XC,Bf,JC,ZC=f(()=>{"use strict";Lt();Ms();KC();Il();XC=4,Bf=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]]),JC=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});function k6(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new _t("Tool input must be valid JSON.")}return cD(e,r,n)}function cD(e,t,n={}){let r=uD(e,t,n),o=Er(e);if(!o)throw new _t(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new _t("Tool input does not match the expected schema.",lD(i.error));return i.data}function lD(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function uD(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(cn(t)&&Array.isArray(t.queries))r=t.queries;else if(cn(t))r=[t];else throw new _t('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new _t("At least one query is required.");let o=cn(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>dD(e,a,yD(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function dD(e,t,n,r){let o={...n},i=Fs(e),s=r.sourceLabel??"direct tool execution",a=pD(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 pD(e,t){return`Execute ${e} via ${t}`}function mD(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 fD(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),l=mD(n,c);if(c.includes(n)||n.includes(c)){l<o&&(r=a,o=l);continue}if(n.length<3)continue;let u=Math.max(2,Math.floor(a.length/3));l<=u&&l<s&&(i=a,s=l)}return r??i}function gD(e,t){let n=hD[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n))o in t&&!(i in t)&&(r??={...t},r[i]=r[o],delete r[o]);return r??t}function yD(e,t,n,r={}){if(!cn(t))throw new _t("Tool input must be a JSON object or an array of objects.");let o=gD(e,t),i=new Set([...Fl(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Is]),s={},a=[];for(let[c,l]of Object.entries(o)){if(i.has(c)){s[c]=l;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(l=>{let u=fD(l,i);return u?`'${l}' \u2192 did you mean '${u}'?`:""}).filter(Boolean);throw new _t(`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}var hD,ew=f(()=>{"use strict";Ms();Il();hD={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"keywords"}}});var zf=f(()=>{"use strict";Ms();Il();ZC();ew()});import{existsSync as tw}from"fs";import{delimiter as bD,dirname as RD,join as nw}from"path";function rw(){return process.platform==="win32"?"npm.cmd":"npm"}function SD(){let e=RD(process.execPath);return nw(e,rw())}function PD(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function xD(){let e=(process.env.PATH??"").split(bD).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...PD()])]}function ow(){let e=SD();if(tw(e))return{command:process.execPath,argsPrefix:[e]};let t=rw();for(let n of xD()){let r=nw(n,t);if(tw(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function N6(e=1e4){let t=ow();return NR(t.command,[...t.argsPrefix,"--version"],e)}async function zn(e,t,n={}){if(!CD.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Gc(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=ow(),c=await tn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:wD});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var CD,wD,vo=f(()=>{"use strict";po();CD=["view","search","ping","config","whoami"],wD=[...uo,...DR]});async function Ns(){if(Ds)return Ds;try{let e=await zn("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 Ds=t,t}}catch{}return Ds=Ao,Ao}function TD(){Ds=null}async function ED(){try{let e=await Ns(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}var Ao,Ds,Gs=f(()=>{"use strict";vo();Ao="https://registry.npmjs.org",Ds=null});function Qs(e){try{return new URL(e).host||e}catch{return e}}function iw(e,t=Date.now()){let n=Lo.get(Qs(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Hs)throw new Uf(Qs(e),Hs-r);n.state="half-open"}}function qf(e){let t=Lo.get(Qs(e));t&&(t.failures=0,t.state="closed")}function sw(e,t=Date.now()){let n=Qs(e),r=Lo.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=$f&&(r.state="open",r.openedAt=t)),Lo.set(n,r)}function B6(){Lo.clear(),$f=5,Hs=3e4}function z6(e){typeof e.failureThreshold=="number"&&($f=e.failureThreshold),typeof e.cooldownMs=="number"&&(Hs=e.cooldownMs)}function aw(e,t=Date.now()){let n=Lo.get(Qs(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Hs:!1}var j6,Lo,$f,Hs,Uf,Ml=f(()=>{"use strict";j6=5,Lo=new Map,$f=5,Hs=3e4;Uf=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}}});import{z as L}from"zod";var Dl,kD,cw,lw,js=f(()=>{"use strict";Dl=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),kD=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),cw=L.looseObject({objects:L.array(kD),total:L.union([L.number(),L.string()]).optional()}),lw=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});function uw(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function vD(e,t,n,r){e&&En({limit_type:"primary",retry_after_seconds:uw(r),api_method:t,api_url:n,provider:e})}function AD(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(qo.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&qy(r),e.status===429&&vD(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function LD(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=uw(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Ut(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=OD,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let y=e.includes("?")?"&":"?";d=`${e}${y}version=${encodeURIComponent(nr)}`}let m={"User-Agent":`Octocode-MCP/${nr}`,...i},p=globalThis.fetch;if(!p)throw new Error(qo.FETCH_NOT_AVAILABLE.message);iw(d);let h,g=n+1;for(let y=1;y<=g;y++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(d,{method:s,headers:m,signal:c});if(!b.ok)throw AD(b,s,d,u,l);if(b.status===204)return qf(d),null;let S=await b.json();return qf(d),S}catch(b){let S=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw b;if(h=b instanceof Error?b:new Error(String(b)),y===g)break;let C=LD(y,r,o,S);await new Promise(k=>setTimeout(k,C))}}throw sw(d),new Error(qo.FETCH_FAILED_AFTER_RETRIES.message(g,h?.message||""))}var OD,Bs=f(()=>{"use strict";Wa();st();di();Ml();OD=6e4});function Un(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function Ze(e){return e===void 0?0:Q(e)}async function Nl(e){try{let t=`${_D}/${encodeURIComponent(e)}`,n=await Ut(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:Ze(n)}}catch{return{rawResponseChars:0}}}function dw(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 pw(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 FD(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Gl(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Un(e.repository):(e.repository.url&&(r=Un(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:FD(e),...o?{repositoryDirectory:o}:{},...dw(e.exports)?{exports:dw(e.exports)}:{},...pw(e.bin,e.name)?{bin:pw(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 ID(e){return typeof e.links?.repository=="string"?Un(e.links.repository):typeof e.repository=="string"?Un(e.repository):typeof e.repository?.url=="string"?Un(e.repository.url):null}function mw(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:ID(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 Wf(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function fw(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 _D,Vf=f(()=>{"use strict";Bs();le();_D="https://api.npmjs.org/downloads/point/last-week"});function Kf(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 Yf(e){try{let t=await Ns(),n=Wf(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Ut(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ze(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Ut(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ze(i)}}catch{return{rawResponseChars:0}}}async function Ql(e,t,n){let[r,o]=await Promise.all([Nl(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Yf(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 Hl(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function DD(e,t){try{let n=await zn("view",[e,"--json"],{timeout:MD});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,...Hl(c)?{}:{errorDetail:c},rawResponseChars:Ze(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=Ze(o),s=Dl.safeParse(o);return s.success?{pkg:Gl(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,...Hl(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function ND(e,t){try{let n=await Ns(),r=Wf(e),o=`${n}/${r}/latest`,i;try{i=await Ut(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Ze(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=Dl.safeParse(i);return a.success?{pkg:Gl(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,...Hl(r)?{}:{errorDetail:r},rawResponseChars:0}}}function GD(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Xf(e,t){let n=0,r;for(let o of GD(e)){let i;try{i=await Ut(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);Hl(l)||(r=l);continue}if(n+=Ze(i),!i||typeof i!="object")continue;let s=Dl.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Gl(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function jl(e,t=!1){let[n,r]=await Promise.allSettled([DD(e,t),ND(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?Ql(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function hw(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await jl(e,t);if(!r){if(o){let s=Kf(o);if(s&&n){let a=await Xf(e,t);if(a.pkg){let c=await Ql(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}}var MD,Jf=f(()=>{"use strict";vo();Bs();js();Gs();Vf();MD=3e3});async function HD(e,t,n,r=0){let o=Math.max(t+r,t),i=await zn("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:Ze(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=Ze(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((h,g)=>{let y=h?.score?.final??0;return(g?.score?.final??0)-y}).slice(r,r+t),d=await Promise.all(u.map(async h=>{if(!h||typeof h!="object")return null;let g=h;if(!g.name)return null;if(n){let y=await jl(g.name,!0);if(y.pkg)return y}return{pkg:mw(g),rawResponseChars:0}})),m=d.map(h=>h?.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function QD(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Ao}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Ut(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(h){return{error:`NPM registry search failed: ${h instanceof Error?h.message:String(h)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ze(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=cw.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 u=[...c.data.objects].sort((h,g)=>{let y=h.score?.final??0;return(g.score?.final??0)-y}).map(h=>h.package).filter(h=>typeof h.name=="string"&&h.name.length>0).slice(0,t),d=await Promise.all(u.map(async h=>{if(n){let g=await jl(h.name,!0);if(g.pkg)return g}return{pkg:{name:h.name,npmUrl:(h.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(h.name)}`,repoUrl:h.links?.repository&&typeof h.links.repository=="string"?Un(h.links.repository):null,version:h.version??"unknown",source:"registry",...h.description?{description:h.description}:{},...h.links?.homepage?{homepage:h.links.homepage}:{}},rawResponseChars:0}})),m=d.map(h=>h.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+g.rawResponseChars,0);return{packages:m,totalFound:fw(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Zf(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 Ut(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:Ze(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ze(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"?Un(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:Ze(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function eh(e,t,n,r=0){try{let o=await HD(e,t,n,r);if(!("error"in o))return o}catch{}return QD(e,t,n,r)}async function th(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}):Nl(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Yf(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)]}}var gw=f(()=>{"use strict";vo();Bs();js();Gs();Vf();Jf()});function zs(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function yw(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function nh(e,t,n,r=0){let o=Te("npm-search",{name:e,limit:t,metadata:n,from:r});return He(o,async()=>{if(aw(Ao)){if(r===0&&t===1&&zs(e)){let u=await Xf(e,n);if(u.pkg){let d=await Ql(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await Zf(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&zs(e)){let l=await hw(e,n,t===1);if("error"in l){if(!Kf(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await eh(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return th(s);let a=yw(e);if(a!==e){let l=await eh(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return th(l)}let c=await Zf(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 bw(e){try{let t=await zn("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=lw.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}}var Rw=f(()=>{"use strict";vo();lt();Ml();js();Gs();Jf();gw()});var rh=f(()=>{"use strict";Gs();Rw()});async function Sw(e){let t=zs(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return nh(e.name,n,!0,r)}var oh=f(()=>{"use strict";rh()});function jD(e){return"error"in e}function Bl(e){return"npmUrl"in e}function BD(e){return Bl(e)&&e.path?e.path:e.name}function zD(e){return Bl(e)?e.repoUrl:e.repository}function UD(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function $D(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function ih(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 Pw(e,t){let n=ih(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghHistoryResearch",query:{type:"releases",owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function qD(e){let t=BD(e),n=$D(zD(e)),r={name:t};Bl(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=UD(Bl(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=Pw(n,o);if(i&&(r.next=i),r.version&&ih(n)){let s=`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.warnings=[s],r.diagnostics=[{level:"warning",code:"npmRepoTagDivergence",message:s}]}return r}function WD(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=ih(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:Pw(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function VD(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,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function xw(e){return fe(e.queries,async t=>{try{if(!t.packageName)return N("Package name is required for package search",t);let n=await Sw({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(jD(n))return N(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(qD),i=o.length>0,s=r.length>1||n.totalFound>1,a=VD(t,n.totalFound,o.length,s),l={...WD(o),pagination:a};return Ee(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return N(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var sh=f(()=>{"use strict";oh();Xe();Me();me()});function YD(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function Cw(e,t){if(t===void 0||t==="progressIdle")return e;let n=YD(e);if(!n||!KD.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]}}var KD,ww=f(()=>{"use strict";KD=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as XD,stat as JD}from"node:fs/promises";import{SymbolResolver as ZD,SymbolResolutionError as eN}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as zl}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function ah(e,t){let n=e.uri,r=bt({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await JD(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:zl.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:zl.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:o,absolutePath:o,content:await XD(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:zl.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Tw(e,t){let n=await ah(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 ZD({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:tN(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof eN)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:zl.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 tN(e){return{start:e,end:{line:e.line,character:e.character}}}var Ul=f(()=>{"use strict";Bt()});function lh(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 uh(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:lh(e.type,t),reason:t}}}function St(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:lh(e,n),reason:n}}}function Pt(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}:{}}}}var $n,$l,ch,ql=f(()=>{"use strict";Lt();$n=40,$l=40,ch=10});function Us(e,t,n,r,o){let i=o.length>0,s=o.map(Df),{pageItems:a,pagination:c}=Pt(s,e.page??1,e.itemsPerPage??$l);return{type:e.type,uri:t.uri,resolvedSymbol:an(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 dh(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?Ew(r):void 0,i=o??r.map(Df),{pageItems:s,pagination:a}=Pt(i,e.page??1,e.itemsPerPage??$l),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function ph(e,t,n){let r=kw(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function Ew(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 kw(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=>Ow(r)).join(`
|
|
44
|
-
`).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
|
|
45
|
-
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function rN(e,t){return Promise.all(e.map(async n=>({...n,from:await Lw(n.from,t,n.fromRanges)})))}async function oN(e,t){return Promise.all(e.map(async n=>({...n,to:await Lw(n.to,t)})))}async function mh(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Aw};try{let i=await e.getIncomingCalls(t),s=o>0?await rN(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=$s(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),mh(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function fh(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Aw};try{let i=await e.getOutgoingCalls(t),s=o>0?await oN(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=$s(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),fh(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var Aw,hh=f(()=>{"use strict";sr();Aw={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function Fw(e){return V(e,Q(e))}function Iw(e,t){return e.format!=="compact"||!Dw(t)?t:sN(t)}function Mw(e){if(!Dw(e))return e;let n=e.payload.locations?.[0],r=n?.displayRange?.startLine;if(!n?.uri||typeof r!="number")return e;let o=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri;return{...e,next:{readSite:{tool:"localGetFileContent",query:{path:o,startLine:Math.max(1,r-3),endLine:(n.displayRange?.endLine??r)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}function Dw(e){return kr(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&kr(e.payload)}function sN(e){return{...e,format:"compact",payload:aN(e.payload)}}function aN(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(_w)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(lN)}:{locations:(e.locations??[]).map(_w)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Nw(e.root)}:{},direction:e.direction,calls:e.calls.map(uN),...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(cN)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function cN(e){if(!kr(e))return String(e);let t=ot(e,"line"),n=ot(e,"character"),r=ot(e,"endLine"),o=ln(e,"kind"),i=ln(e,"name"),s=ot(e,"childCount"),a=ln(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function _w(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Hw(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function lN(e){if(!kr(e))return String(e);let t=ln(e,"uri"),n=ot(e,"firstLine"),r=ot(e,"firstCharacter"),o=ot(e,"count"),i=Gw(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 uN(e){if(!kr(e))return String(e);let t=ln(e,"direction"),n=Nw(e.item),r=Gw(e,"ranges").map(dN).join(","),o=ot(e,"rangeCount"),i=ot(e,"rangeSampleCount"),s=ln(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Hw(s,180)}`:""].filter(Boolean).join(" ")}function Nw(e){if(!kr(e))return String(e);let t=ln(e,"name"),n=ln(e,"kind"),r=ln(e,"uri"),o=ot(e,"line"),i=ot(e,"endLine"),s=ot(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function dN(e){return kr(e)?`${ot(e,"line")}:${ot(e,"character")}`:String(e)}function kr(e){return typeof e=="object"&&e!==null}function ln(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function ot(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Gw(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Hw(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 Qw(e,t){let n=Bw(e.fromRanges);return{direction:"incoming",item:Wl(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...zw(e.from,t)}}function jw(e,t){let n=Bw(e.fromRanges);return{direction:"outgoing",item:Wl(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...zw(e.to,t)}}function Wl(e){return{name:e.name,kind:_o(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 Bw(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>=iN))break}return n}function zw(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function _o(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"}}var iN,qs=f(()=>{"use strict";le();iN=8});async function gh(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return St(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await mh(n,o,i,new Set([$s(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await fh(n,o,i,new Set([$s(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),m=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],p=m.map(S=>S.direction==="incoming"?Qw(S,e.contextLines??0):jw(S,e.contextLines??0)),{pageItems:h,pagination:g}=Pt(p,e.page??1,e.itemsPerPage??ch),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Wl(o),direction:y,calls:h,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function yh(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return St(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}=Pt(s,e.page??1,e.itemsPerPage??$n);return{type:e.type,uri:t.uri,resolvedSymbol:an(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 Uw=f(()=>{"use strict";hh();Lt();qs();ql()});var Ws=f(()=>{"use strict";ql();vw();Uw()});import Vs from"node:path";import{readFile as pN}from"node:fs/promises";import{resolveImportAliasDefinitions as mN}from"@octocodeai/octocode-engine/lsp/resolver";async function Ww(e,t,n){if(typeof e.openDocument=="function")try{let r=Vs.extname(t.uri).slice(1),o=$w.includes(r)?$w:[r],i=await Rt({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:fN,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=Vs.isAbsolute(a)?a:Vs.join(n,a);if(Vs.resolve(c)!==Vs.resolve(t.uri))try{let l=await pN(c,"utf-8");if(l.length>hN)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function Vw(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?Us(e,t,"definition","definitionProvider",await mN({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):St(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?Us(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):St(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?Us(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):St(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?dh(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):St(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?ph(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):St(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?gh(e,t,n):St(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?yh(e,t,n):St(e.type,t,"typeHierarchyProvider unsupported",!0)}}var qw,fN,hN,$w,Kw=f(()=>{"use strict";Sr();Ws();qw=new Set(["references","callers","callees","callHierarchy","implementation"]),fN=12,hN=512*1024,$w=["ts","tsx","mts","cts","js","jsx","mjs","cjs"]});import Rh from"node:path";import{fileURLToPath as gN}from"node:url";import{unavailableHintFor as yN}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as bN}from"@octocodeai/octocode-engine/lsp/config";function Yw(e){return bh||(bh=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),bh.has(Rh.extname(e).toLowerCase())}function Ft(e,t){let n=bN(e),r=yN(n,void 0);throw new ze(q.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function Xw(e,t){let n=e.startsWith("file://")?gN(e):e;return Rh.isAbsolute(n)?n:Rh.resolve(t,n)}function Sh(){return[...D.getSupportedJsTsExtensions(),...RN]}function Jw(){return Sh().map(e=>`**/*.${e}`)}async function Zw(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:Jw(),excludeDir:[...SN],maxSnippetChars:1})).files[0]?.path}catch{return}}async function Ph(e,t){if(e.uri)return Xw(e.uri,t);let n=await Zw(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Sh(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function xh(e){return e instanceof Error?e.message:String(e)}function Ch(e,t){if(!Yw(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var bh,RN,SN,Vl=f(()=>{"use strict";Vo();bn();Le();RN=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];SN=[".git","node_modules","dist","out","coverage","target"]});import{acquirePooledClient as PN,isLanguageServerAvailable as xN}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as CN}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Eh(e){let t=await ah(e,je);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await CN(t.value.uri),r=await xN(t.value.uri,n),o=r?await PN(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Ch(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let y=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(y)?y:[],a="lsp"}else{let y=Ub(t.value.content,t.value.uri);y&&(s=y,a="markdown")}let l=a!==void 0;!l&&!r&&Ft(t.value.uri,"documentSymbols");let u=eT(s),d=nT(s),{pageItems:m,pagination:p}=Pt(u,e.page??1,e.itemsPerPage??$n),h=rT(u,y=>y.kind),g=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:u.length,returnedSymbols:m.length,topLevelSymbols:d,kinds:h},payload:{kind:"documentSymbols",symbols:m,...g?{empty:g}:{}},pagination:p}}function eT(e){let t=[];for(let n of e)kh(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function kh(e,t,n){if(!e||typeof e!="object")return;let r=e,o=tT(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:_o(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)&&wN.has(_o(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)kh(s,t,i)}}function tT(e){if(wh(e.range))return e.range;let t=e.location;return t&&wh(t.range)?t.range:void 0}function wh(e){if(!e||typeof e!="object")return!1;let t=e;return Th(t.start)&&Th(t.end)}function Th(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function nT(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function rT(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}var wN,oT=f(()=>{"use strict";uc();Lt();Ul();Ws();qs();Vl();wN=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});import iT from"node:path";import{acquirePooledClient as sT,isLanguageServerAvailable as aT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as TN}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Oh(e){let t=e.symbolName??"",n=iT.resolve(e.workspaceRoot??process.cwd()),r=await Ph(e,n);await aT(r,n)||Ft(r,"workspaceSymbol");let i=await sT(n,r);if(i||Ft(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{iT.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${xh(u)}`}}}let a=cT(s),{pageItems:c,pagination:l}=Pt(a,e.page??1,e.itemsPerPage??$n);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function cT(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:_o(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function vh(e){let t=e.uri??"",n=e.workspaceRoot??(t?await TN(t):process.cwd());await aT(t,n)||Ft(t,"diagnostic");let o=await sT(n,t);if(o||Ft(t,"diagnostic"),!o.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 i=await o.getDiagnostics(t),s=lT(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Pt(s,e.page??1,e.itemsPerPage??$n);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function lT(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>uT(r))}return[]}function uT(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}var dT=f(()=>{"use strict";Ws();qs();Vl()});var pT=f(()=>{"use strict";Vl();oT();dT()});import{acquirePooledClient as EN,isLanguageServerAvailable as kN}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as ON}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Ah(e){return fe(e.queries||[],async t=>ht({toolName:je,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await vN(t);return Fw(Mw(Iw(t,n)))}}),{toolName:je,minQueryTimeoutMs:3e4},e)}async function vN(e){if(e.type==="documentSymbols")return Eh(e);if(e.type==="workspaceSymbol")return Oh(e);if(e.type==="diagnostic")return vh(e);let t=await Tw(e,je);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return uh(e,a)}let n=e.workspaceRoot??await ON(t.value.uri);await kN(t.value.uri,n)||Ft(t.value.uri,e.type);let o=await EN(n,t.value.uri);o||Ft(t.value.uri,e.type),qw.has(e.type)&&await Ww(o,t.value,n);let i=o.getReadiness?.(),s=await Vw(e,t.value,o);return Cw(s,i)}var Kl=f(()=>{"use strict";Xe();Dn();Lt();ww();Ul();Kw();Ws();pT();qs()});var Lh,_h=f(()=>{"use strict";me();Lh={hasTool(e){return Yd(e)},getDescription(e){return Vd[e]??""},getToolName(e){return v[e]??String(e)}}});function AN(e,t){return t.getToolName(e)}function It(e,t,n){let r=AN(t,e);return{...n,name:r,description:Fh(r,e)}}function LN(e=Lh){let t=It(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ki,inputSchema:Yi,executionFn:NS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=It(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:dr,inputSchema:Wi,executionFn:OS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=It(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:os,inputSchema:is,executionFn:FP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=It(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ns,inputSchema:rs,executionFn:AP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=It(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:hr,inputSchema:ts,executionFn:yP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=It(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ls,inputSchema:_s,executionFn:xw,security:"remote",requiresServerRuntime:!0}}),a=It(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:mo,inputSchema:qi,executionFn:rS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=It(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:on,inputSchema:ps,executionFn:wx,security:"basic"}}),l=It(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Pr,inputSchema:Ss,executionFn:Fx,security:"basic"}}),u=It(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:yr,inputSchema:cs,executionFn:ox,security:"basic"}}),d=It(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:gr,inputSchema:as,executionFn:ex,security:"basic"}}),m={name:je,description:Fh(je,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Eo,inputSchema:ko,executionFn:Ah,security:"basic",requiresServerRuntime:!0}},p={name:Bn,description:Fh(Bn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:Cs,inputSchema:Qn,executionFn:fT,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},h=[t,n,r,o,i,s,a,c,l,u,d,m,...As()?[p]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,OQL_SEARCH:p,ALL_TOOLS:h}}var Fh,it,f9,h9,g9,y9,b9,R9,S9,P9,x9,C9,w9,T9,E9,mT,Ih=f(()=>{"use strict";Gf();sm();dm();hm();Tm();_m();Im();sh();jm();Um();ff();bf();Kl();Mh();Lt();wo();_h();Fh=(e,t=Lh)=>t.getDescription(e);it=LN(),f9=it.GITHUB_SEARCH_CODE,h9=it.GITHUB_FETCH_CONTENT,g9=it.GITHUB_VIEW_REPO_STRUCTURE,y9=it.GITHUB_SEARCH_REPOSITORIES,b9=it.GITHUB_SEARCH_PULL_REQUESTS,R9=it.PACKAGE_SEARCH,S9=it.GITHUB_CLONE_REPO,P9=it.LOCAL_RIPGREP,x9=it.LOCAL_VIEW_STRUCTURE,C9=it.LOCAL_FIND_FILES,w9=it.LOCAL_FETCH_CONTENT,T9=it.LSP_GET_SEMANTIC_CONTENT,E9=it.OQL_SEARCH,mT=it.ALL_TOOLS});import{ContentSanitizer as _N}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as FN}from"@octocodeai/config";function Nh(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:vt(t.structuredContent)}}catch{}return MN(t)?DN(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}=_N.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function MN(e){return FN()==="mcp"&&process.env[IN]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function DN(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:NN(e.structuredContent)},...t]}}function NN(e){let t=["structuredContent available"];if(Dh(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=GN(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Dh(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function GN(e){let t=0,n=0;for(let r of e)Dh(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Dh(e){return typeof e=="object"&&e!==null}function Gh(e,t){let n=QN(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
46
|
-
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:
|
|
47
|
-
`)}var ST=f(()=>{"use strict"});function PT(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function xT(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return PT(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),PT(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=RT(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function pn(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return xT(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=xT(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var Xs=f(()=>{"use strict";ST()});var Zl=f(()=>{"use strict";mf()});function CT(e,t,n){let r=e.where,o=r?vl(r):[],i=r&&oG.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>x("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function iG(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function Js(e,t={}){if(!e.where)return{ok:!1,diagnostics:[x("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=iG(e.where);if(n){let m=wT(e,t);if(m.length>0)return{ok:!1,diagnostics:m};let{owner:p,repo:h}=Af(e.from),g=e.params??{},y=typeof g.extension=="string"||typeof n.extension=="string"?{}:Rs(Co(e.scope)),b=Lf(e),S=Qe(e.scope);return CT(e,{...p?{owner:p}:{},...h?{repo:h}:{},...y,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...b?{limit:b}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=pn(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[x("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=wT(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[x("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Af(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Rs(Co(e.scope)),u=Lf(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return CT(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...Qe(e.scope)?{path:Qe(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function wT(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var oG,$h=f(()=>{"use strict";Xs();ne();Zl();jn();oG=new Set(["text","regex","structural","field"])});function qh(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function Or(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function Wh(e){return e.structuredContent?.results?.[0]?.status}function TT(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function Vh(...e){return e.map(TT).filter(Boolean).join("/")}function ET(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function Kh(e){return TT(e).split("/").filter(Boolean).length}function sG(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function aG(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function cG(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lG(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(cG).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function kT(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(sG).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!lG(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(aG(o.path)))}function Yh(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function OT(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function vT(e){return typeof e=="string"?[]:e.matches??[]}function De(e){return e.from??{kind:"github"}}function AT(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}var Xh=f(()=>{"use strict"});function uG(e,t){return e>0?[]:[x("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function Mo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function dG(e){if(Wh(e)==="error"){let r=Or(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:Mo(o.status),retryAfterSeconds:Mo(o.retryAfter),rateLimitRemaining:Mo(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:Mo(n.status),retryAfterSeconds:Mo(n.retryAfterSeconds),rateLimitRemaining:Mo(n.rateLimitRemaining)}}function pG(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return x("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?x("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):x("invalidQuery",e.message,{backend:t})}function mG(e,t){let n=dG(e);return n?[pG(n,t)]:Wh(e)==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function Zs(e,t,n){let r=mG(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...uG(t,n)]}var LT=f(()=>{"use strict";ne();Xh()});async function _T(e){let t=Js(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await ke("ghSearchCode",t.query),r=Or(n),o=new Set,i=[];for(let a of r?.files??[]){let c=Yh(a);o.has(c)||(o.add(c),i.push({kind:"file",source:De(e),path:c,entryType:"file"}))}let s=dn(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...Zs(n,i.length,"ghSearchCode"),...i.length>0?[x("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:De(e)}]}}async function FT(e){let t=Js(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await ke("ghSearchCode",t.query),r=Or(n),o=[];for(let s of r?.files??[]){let a=Yh(s),c=OT(s),l=vT(s);if(l.length===0){o.push({kind:"code",source:De(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:De(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=zh(dn(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...Zs(n,o.length,"ghSearchCode"),...o.length>0?[x("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:De(e)}]}}async function IT(e){let{owner:t,repo:n}=qh(De(e)),r=e.fetch?.content,o=r?.contentView??"standard",i=AT(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Qe(e.scope)??"",type:"file",minify:o,...De(e).kind==="github"&&De(e).ref?{branch:De(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await ke("ghGetFileContent",s),c=Or(a),l=o,u=c?.pagination,d=c?.results??c?.files??[],m=d.map(h=>{let g=h.pagination??u,y=typeof g?.charOffset=="number",b={...h.startLine!==void 0?{startLine:h.startLine}:{},...h.endLine!==void 0?{endLine:h.endLine}:{},...y?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:De(e),path:h.path,content:h.content,contentView:l,...Object.keys(b).length?{range:b}:{}}}),p=u??d.find(h=>h.pagination)?.pagination;return{results:m,...p?.hasMore!==void 0?{pagination:{hasMore:!!p.hasMore,...p.currentPage!==void 0?{currentPage:p.currentPage}:{},...p.totalPages!==void 0?{totalPages:p.totalPages}:{},...p.charLength!==void 0?{itemsPerPage:p.charLength}:{},...p.totalChars!==void 0?{totalItems:p.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...Zs(a,m.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:De(e)}]}}async function MT(e){let{owner:t,repo:n}=qh(De(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Qe(e.scope)??"",...De(e).kind==="github"&&De(e).ref?{branch:De(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await ke("ghViewRepoStructure",r),i=Or(o),s=[],a=Qe(e.scope);for(let u of ET(i?.structure)){let d=u.dir??".";for(let m of u.folders??[]){let p=Vh(a,d,m);s.push({kind:"tree",source:De(e),path:p,entryType:"directory",depth:Kh(p)})}for(let m of u.files??[]){let p=Vh(a,d,m);s.push({kind:"tree",source:De(e),path:p,entryType:"file",depth:Kh(p)})}}let c=kT(s,e),l=dn(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...Zs(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:De(e)}]}}var DT=f(()=>{"use strict";un();Jl();Wn();ne();$h();jn();LT();Xh()});async function NT(e){switch(e.target){case"content":return IT(e);case"structure":return MT(e);case"files":return _T(e);default:return FT(e)}}var GT=f(()=>{"use strict";DT()});function Do(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Jh=f(()=>{"use strict"});function vr(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function QT(e){return fG.test(e)}function jT(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function Ar(e,t,n){if(n){e.langType=n;return}let r=Pl(Co(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=jT(e.include,r.include))}function hG(e){return xl(Co(e))}function HT(e){let t=Do(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function No(e){return!!(e?.include?.length||e?.exclude?.length)}function ea(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(HT).filter(i=>!!i);n.length>0&&!e.names&&(e.names=jT(e.names,n));let r=(t?.include??[]).filter(i=>!HT(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=hG(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function BT(e,t){if(No(t.scope)){tu(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function tu(e){e.limit=eu,e.itemsPerPage=eu}function zT(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function nu(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}var eu,fG,Lr=f(()=>{"use strict";ce();Zl();jn();Jh();eu=1e4;fG=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});function UT(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?Zh(e.predicate):!1}function gG(e){return e.kind==="text"||e.kind==="regex"}function ru(e){return e?.kind==="not"&&gG(e.predicate)}function Zh(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}function eg(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?eg(e.predicate):!1}function ou(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(x("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(ta(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(ta(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(ta(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(x("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(ta(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(ta(i));break}r&&n.push(x("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function ta(e){return x("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function $t(e,t){let n=[];e.status==="error"?n.push(x("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(x(yG(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function yG(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function qt(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var Go=f(()=>{"use strict";ne()});import tg from"node:path";async function qT(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Tl(r);return{...gT(o,t),diagnostics:$t(o,"localViewStructure"),provenance:[qt("localViewStructure",t,void 0)]}}async function WT(e,t,n){let r=e.fetch?.content,o=r?.contentView??"standard",i=bG(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await pl(s);return{...yT(a,t,n,o),diagnostics:$t(a,"localGetFileContent"),provenance:[qt("localGetFileContent",t,void 0)]}}function bG(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function na(e,t,n){if(!No(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>RG(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function RG(e,t,n){let r=Do(SG(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>$T(r,i))?!1:!(n?.exclude??[]).some(i=>$T(r,i))}function SG(e,t){let n=tg.relative(t,e);return!n||n.startsWith("..")||tg.isAbsolute(n)?e:n}function $T(e,t){let n=Do(t),r=Do(e),o=PG(n);return o.test(r)?!0:n.includes("/")?!1:o.test(tg.posix.basename(r))}function PG(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=xG(r)}return new RegExp(`${t}$`)}function xG(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}var iu=f(()=>{"use strict";Ps();ss();Wn();Lr();Go();Jh()});function su(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}function ra(e){let t=new Map;for(let n of e)t.set(n.path,su(t.get(n.path),n));return t}function VT(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,su(o,i))}return n}function KT(e,t){return new Set([...e].filter(n=>t.has(n)))}var oa=f(()=>{"use strict"});async function ng(e,t,n,r){let o={path:n,entryType:"f"};ea(o,e.scope),No(e.scope)&&(tu(o),o.page=1);let i=await br(o),s=na(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),ra(Ys({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function YT(e,t,n,r,o,i){let s={path:r,details:!0};ea(s,e.scope),ou(t,s,i),No(e.scope)&&(tu(s),s.page=1);let a=await br(s),c=na(a,e,r);return o.push({backend:"localFindFiles",source:e.from}),ra(Ys(c,n).results)}var XT=f(()=>{"use strict";Ro();Wn();Lr();Go();iu();oa()});async function JT(e,t,n,r,o,i){let s=pn(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:eu,...vr(e.scope)};Ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await Rt(c);return o.push({backend:"localSearchCode",source:e.from}),ra((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}async function ZT(e,t,n,r){let o=await Rt(tE(e,n,r.predicate)),i=$t(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[qt("localSearchCode",t,r)]}}async function eE(e,t,n,r){let o=await Rt(tE(e,n,r.predicate));return{...Io(o,t),diagnostics:$t(o,"localSearchCode"),provenance:[qt("localSearchCode",t,r)]}}function tE(e,t,n){let o=pn(n).match,i={path:t,filesWithoutMatch:!0,...vr(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...nu(e)};return Ar(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}var au=f(()=>{"use strict";Sr();Xs();Wn();ne();Lr();Go();oa()});async function nE(e,t,n,r){let o=[],i=[],a=[...(await cu(e,r,t,n,o,i)).values()].sort(CG(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(x("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function CG(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function cu(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>cu(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:VT(a,c));case"any":{let s=await Promise.all(t.of.map(c=>cu(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,su(a.get(l),u));return a}case"not":{let s=await ng(e,n,r,o),a=await cu(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return rE(e,t,n,r,o,i)}}async function rE(e,t,n,r,o,i){return t.kind==="field"?YT(e,t,n,r,o,i):JT(e,t,n,r,o,i)}async function oE(e,t,n){return new Set((await ng(e,e.from,t,n)).keys())}async function iE(e,t,n,r,o){return new Set((await rE(e,t,e.from,n,r,o)).keys())}var rg=f(()=>{"use strict";ne();XT();au();oa()});async function sE(e,t,n,r){let o=[],i=[],s=await lu(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(x("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function lu(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>lu(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:KT(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>lu(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await oE(e,r,o),a=await lu(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await iE(e,t,r,o,i),rows:[]};default:{let s=await wG(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function wG(e,t,n,r,o,i){let s=pn(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...vr(e.scope)};Ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await Rt(c);return o.push({backend:"localSearchCode",source:n}),Io(l,n).results}var aE=f(()=>{"use strict";Sr();Xs();Wn();ne();Lr();rg();oa()});async function uu(e,t,n){let r=e.where;if(UT(r))return sE(e,t,n,r);if(e.view==="discovery"&&ru(r))return eE(e,t,n,r);let o=pn(r);if(o.unsupported)return{results:[],diagnostics:[x(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...vr(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...nu(e)};Ar(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await Rt(s),c=Io(a,t),l=$t(a,"localSearchCode"),u=TG(a);if(u.length>0){let d=u.reduce((p,h)=>p+(h.total??0),0),m=u.reduce((p,h)=>p+h.shown,0);l.push(x("matchTruncated",`${u.length} file(s) have more matches (showed ${m} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(x("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&QT(i.keywords)&&l.push(x("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[qt("localSearchCode",t,r)]}}function TG(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}var og=f(()=>{"use strict";Sr();Xs();Wn();ne();Lr();Go();aE();au()});async function cE(e,t,n){let r=e.where;if(ru(r))return ZT(e,t,n,r);if(r&&Zh(r))return nE(e,t,n,r);if(r&&eg(r)){let l=await uu({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};ea(o,e.scope),BT(o,e),zT(o,e);let i=[];r&&ou(r,o,i);let s=await br(o),a=na(s,e,n);return{...Ys(a,t),diagnostics:[...i,...$t(a,"localFindFiles")],provenance:[qt("localFindFiles",t,r)]}}var lE=f(()=>{"use strict";Ro();Wn();Lr();Go();og();rg();au();iu()});import EG from"node:fs";import kG from"node:path";function OG(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}async function ia(e){let t=e.from,n=OG(e),r=Qe(e.scope),o=r?kG.join(n,r):n;if(!EG.existsSync(o))return{results:[],diagnostics:[x("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return cE(e,t,o);case"structure":return qT(e,t,o);case"content":return WT(e,t,o);default:return uu(e,t,o)}}var ig=f(()=>{"use strict";ne();og();lE();iu();jn()});import uE from"node:path";function dE(e){return[...new Set(e)]}function mE(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function fE(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!uE.isAbsolute(r.localPath)?uE.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function hE(e){if(e.from?.kind!=="github")return ia(e);let t=e.from,{owner:n,repo:r}=mE(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Qe(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await ke("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=fE(s);if(u==="error"||!a)return{results:[],diagnostics:[x("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},m={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:dE([...d.excludeDir??[],".git"]),exclude:dE([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},p=await ia(m);return{...p,diagnostics:[...p.diagnostics,...c?[x("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...p.provenance]}}async function gE(e){if(e.from?.kind==="materialized"){let p=e.from.localPath;return{results:[pE(p,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[x("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=mE(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:Qe(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await ke("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=fE(a);if(d==="error"||!c)return{results:[],diagnostics:[x("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let m=!i;return{results:[pE(c,t,t.ref,m,l)],diagnostics:l?[x("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function pE(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var yE=f(()=>{"use strict";un();ig();ne();jn()});import sg from"node:path";function du(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{byVerdict:t,facts:n,edges:r}}function sa(e){let t=e.root,n=[...e.symbols.map(a=>vG(t,a)),...e.files.map(a=>FG(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>IG(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let{byVerdict:o,facts:i,edges:s}=du(n);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function vG(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=AG(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:t.retentionSource==="ast"?"imports":"references",source:t.retentionSource==="ast"?"ast":"ripgrep",confidence:t.retentionSource==="ast"?"exact":"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:LG(r),next:_G(e,t)}}function AG(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function LG(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via AST import/call retention (or lexical fallback); likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable retainers found in analyze (AST import/call scan, then lexical fallback). Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only retained from unreachable code (AST or lexical scan). Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function _G(e,t){let n=sg.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"none"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function FG(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:sg.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:sg.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function IG(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var bE=f(()=>{"use strict"});var pu=f(()=>{"use strict";bE()});function RE(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function ag(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:RE(e.relation),verdicts:RE(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function MG(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function _r(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function aa(e,t){if(!MG(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>_r(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>_r(i.relation,t)),o=e.why.some(i=>_r(i.claim,t));return n||r||o}function mu(e,t){e.set(t.id,t)}function SE(e,t,n){_r(t.claim,n)&&e.set(t.id,t)}function ca(e,t,n,r){_r(n.relation,r)&&(mu(e,n.from),mu(e,n.to),t.set(n.id,n))}function PE(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}var fu=f(()=>{"use strict"});import xE from"node:path";function la(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function wE(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=NG(a.relation);if(!_r(c,i))continue;let l=CE(a.from,e,a.line),u=CE(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||ca(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function NG(e){let t=e.trim();return DG.has(t)?t:"references"}function CE(e,t,n){let r=GG(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function GG(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:xE.isAbsolute(o)?xE.relative(t,o):o,name:i}}var DG,cg=f(()=>{"use strict";fu();DG=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});function Fr(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??HG),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function TE(e,t,n,r,o,i){let s=t.filter(g=>aa(g,r)),a=Fr(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,m=new Map,p={},h={};for(let g of s)p[g.verdict]=(p[g.verdict]??0)+1,h[g.proofStatus]=(h[g.proofStatus]??0)+1;for(let g of c){if(mu(l,g.subject),r.includeFacts)for(let y of g.why)SE(d,y,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let y of g.retainedBy)ca(l,u,y,r);if(r.direction!=="incoming")for(let y of g.retains??[])ca(l,u,y,r)}for(let y of g.missingProof)m.set(PE(y),y)}return r.includeEdges&&wE(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:m.size,byVerdict:p,proofStatus:h},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...m.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function EE(e){let{byVerdict:t,facts:n,edges:r}=du(e);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}var HG,ua=f(()=>{"use strict";pu();fu();cg();fu();cg();HG=25});function hu(e){if(!e)return[];for(let t of kE){let n=e[t];if(Array.isArray(n))return n}return[e]}function OE(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function vE(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))QG.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function lg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ho(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function jG(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??Ho(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:Ho(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??Ho(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??Ho(t);case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:Ho(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return Ho(t)}function Vn(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=jG(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}var kE,QG,da=f(()=>{"use strict";kE=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],QG=new Set([...kE,"pagination","contentPagination","next"])});import{statSync as BG}from"node:fs";import gu from"node:path";function yu(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function AE(e,t){if(!t||gu.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?gu.join(n.base,t):t}function pa(e){try{let t=gu.isAbsolute(e)?e:gu.resolve(e);return BG(t).isDirectory()}catch{return!1}}function Kn(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function xt(e){return e.params??{}}function ma(e,t){let n={...xt(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}var Yn=f(()=>{"use strict"});function bu(e){return e==="plan"||e==="prove"?e:"analyze"}function zG(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;LE.includes(o)&&t.add(o)}return t.size>0?t:void 0}function _E(e,t){let n=zG(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of LE){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:m,pagination:p}=Fr(e,u.length);o[l]=u.slice(d,m),o[`${l}Page`]=p,s=p.itemsPerPage,a=Math.max(a,p.totalPages??1),p.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function FE(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function ug(e,t){let{status:n,data:r}=qn(e);return n==="error"?[x("invalidQuery",yu(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function Ir(e,t,n,r){let{data:o,status:i}=qn(e),s=ug(e,n),a=i==="error"?[]:hu(o);a.length===0&&!s.some(m=>m.code==="zeroMatches"||m.severity==="error")&&s.push(x("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=dn(c,l),d=t==="package"?OE(o):void 0;return{results:Vn(a,t,r,vE(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function dg(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function IE(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:dg(n,t)}}var LE,Mr=f(()=>{"use strict";ne();un();Jl();ua();da();Yn();LE=["manifests","files","dependencies","symbols","graphFacts"]});function UG(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}async function ME(e){let{owner:t}=Kn(e.from),n=ma(e,"limit"),r=typeof n.language=="string"?n.language:UG(e),o=Cl(r);o&&(n.language=o);let i=await ke("ghSearchRepos",{...t?{owner:t}:{},...n}),s=Ir(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&$G(n)&&s.diagnostics.push(x("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function $G(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function DE(e){let t=await ke("npmSearch",{...ma(e)});return Ir(t,"package","npmSearch",e.from??{kind:"npm"})}var NE=f(()=>{"use strict";un();ne();Zl();Mr();Yn()});async function pg(e){let{owner:t,repo:n}=Kn(e.from),r=e.target==="commits",o=r?void 0:WG(e),i=r?qG(e):void 0,s=ma(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await ke("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=Ir(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?HE(c,o):i?GE(c,i):c}function qG(e){let t=xt(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function GE(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),m=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,m)+(m<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function WG(e){let t=xt(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function VG(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
|
|
48
|
-
`)}function
|
|
49
|
-
`)[0]||p.error?.message||`exit ${p.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=mg(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[x("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function
|
|
43
|
+
`);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 ef(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Wm.test(e))return"comment";let o=DI(e,t,r);if(o<0)return"code";let i=NI(e);return i>=0&&o>i?"comment":dx(e,o)?"string":"code"}function DI(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function NI(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 dx(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!==""}var tf=f(()=>{"use strict";bl();of()});function GI(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function HI(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 QI(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Jm(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=Zm(l,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Rl(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=pe.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=pe.exactCaseInsensitive,m.push("case-insensitive match")):u.includes(r)&&(d+=pe.substring,m.push("substring match")));let p=c.kind;if(p)d+=jI(p,m);else{let h=ef(u,r,t.id,n.caseSensitive);h!=="code"?(d+=pe.commentOrStringPenalty,m.push(h==="comment"?"comment match (weak)":"string literal (weak)")):(bs(t.declaration,u)&&(d+=pe.declarationLine,m.push("declaration line")),bs(t.export,u)&&(d+=pe.exportLine,m.push("export/public line")),bs(t.import,u)&&(d+=pe.importLine,m.push("import line")),t.id==="markdown"&&Vm.test(u)&&(d+=pe.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&BI(u,r)&&(d+=pe.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function jI(e,t){switch(e){case"declaration":return t.push("AST: declaration"),pe.declarationLine;case"export":return t.push("AST: export/public"),pe.exportLine;case"configKey":return t.push("AST: config key"),pe.configKeyLine;case"heading":return t.push("AST: heading"),pe.headingLine;case"import":return t.push("AST: import"),pe.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),pe.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function BI(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 zI(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(gl,"").includes(l))&&(s+=pe.pathSegmentToken,i.push("query token in path"))}let a=ys(e);return r.extensions.includes(a)&&t.langType&&(s+=pe.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=pe.sourceDir,i.push("source file")),s}function UI(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),pe.lowSignalPathPenalty):0}function $I(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*pe.matchCountScale,r=Math.min(n,pe.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function nf(e,t){let n=HI(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=>qI(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 qI(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Rl(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function WI(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*pe.rareQueryTokenScale,pe.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function rf(e,t,n){let r=Km(e.path,t.langType,t.profileOverride),o=yl(e.path),i=GI(t.keyword),s=[],a=0;return a+=QI(e.matches,r,t,i,s),a+=zI(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=pe.pathUnderQuery,s.push("under requested subtree")),a+=UI(o,t,s),gs.test(e.path)&&!t.explicitLowSignal&&(a+=pe.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=$I(e.matchCount??0,s),a+=WI(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var of=f(()=>{"use strict";bl();tf()});var px=f(()=>{"use strict";bl();of();tf()});function mx(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=YI(i);s.fetch={tool:"localGetFileContent",query:sf({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?"heuristic":"exact"};let a=XI(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:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:sf({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:sf({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function YI(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 XI(e,t,n){if(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)return;if(n==="structural")return JI(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.onlyMatching){let o=af(e?.value);return o?{symbol:o}:void 0}let r=af(t.keywords);return r?{symbol:r}:void 0}function JI(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=af(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function af(e){if(typeof e!="string")return;let t=e.trim();if(KI.test(t)&&!VI.has(t))return t}function sf(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var VI,KI,cf=f(()=>{"use strict";VI=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"]),KI=/^[A-Za-z_$][A-Za-z0-9_$]*$/});async function Sl(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=Xm(e,s,ZI(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),m=!!(t.countLinesPerFile||t.countMatchesPerFile),p=d||m,h=c.reduce((H,Y)=>H+(Y.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??h:h,y=t,b=Math.min(y.itemsPerPage||zt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=y.page||1,C=Math.max(1,Math.ceil(u/b)),k=(S-1)*b,E=Math.min(k+b,u),_=c.slice(k,E),w=y.maxMatchesPerFile||zt.DEFAULT_MATCHES_PER_PAGE,G=_.map(H=>{let Y=H.matches?.length??0,I=Math.ceil(Y/w),Re=Math.max(1,y.matchPage||1),Oe=(Re-1)*w,hn=Math.min(Oe+w,Y),Uo=p?void 0:H.matches?.slice(Oe,hn),Ca=Uo?.length,$o=l?.get(H.path);return{path:H.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:H.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:H.matchCount||1}:{totalMatchRows:Y,...Ca!==void 0?{returnedMatchRows:Ca}:{}},...Uo!==void 0&&{matches:Uo},...$o?{ranking:{score:$o.score,profile:$o.profile,pathRole:$o.pathRole,reasons:$o.reasons}}:{},pagination:!p&&Y>w?{currentPage:Re,totalPages:I,matchesPerPage:w,totalMatches:Y,hasMore:Re<I,...Re<I?{nextMatchPage:Re+1}:{}}:void 0}}),M=G.filter(H=>H.pagination?.hasMore),A=mx(G,t,n,{isFileListMode:p,currentPage:S,totalFilePages:C,matchPage:y.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:M.length>0}),W={searchEngine:n,...o?{stats:o}:{},files:G,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<C,...S<C?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return fx(W,t,{totalMatches:g,totalFiles:u})}function fx(e,t,n){return e}function ZI(e){let t=e.rankingProfile,n=!!(e.include?.length||Ym(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var hx=f(()=>{"use strict";bo();px();cf()});var Rs=f(()=>{"use strict";hx();cf()});function gx(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&e0(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&t0(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function e0(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function t0(e){return/\(\?[=!<]/.test(e)}var lf=f(()=>{"use strict";Le()});import{validateRipgrepQuery as n0}from"@octocodeai/octocode-core/schemas/runtime";function r0(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function o0(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:r0(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function i0(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function yx(e){let t=[],n=n0(e);if(!n.isValid)return N(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=on.safeParse(e);if(!r.success){let g=r.error.issues.map(y=>y.message);return N(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return N(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=bt(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=gx({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return N(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(o0(a))}catch(g){return N(g instanceof Error?g:new Error(String(g)),o,{toolName:v.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(y=>{let b={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(b.count=y.count),y.kind!==void 0&&(b.kind=y.kind),y.scoreHint!==void 0&&(b.scoreHint=y.scoreHint),b})})),m=i0(d),p={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return V({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...l]},m);!a.filesOnly&&m>zt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let h=await Sl(d,o,"rg",[...t,...l],p);return V(h,m)}var uf=f(()=>{"use strict";Bt();fs();bo();me();Rs();lf();le();Le()});var bx,Rx,Sx=f(()=>{"use strict";bx={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"]}},Rx={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 s0(e){return e.trim().replace(/^\./,"").toLowerCase()}function Rr(e){if(!e?.trim())return;let t=s0(e),n=bx[t]??Rx[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function a0(e){return[...e??[]].map(t=>`**/*.${t}`)}function df(e){return[...e??[]].map(t=>`*.${t}`)}function Ss(e){let t=Rr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Pl(e){let t=Rr(e);return t?t.kind==="extension"&&t.extension?{include:a0([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function xl(e){let t=Rr(e);return t?t.kind==="extension"&&t.extension?df([t.extension]):t.kind==="language"?df(t.extensions):t.normalized?df([t.normalized]):[]:[]}function pf(e){let t=Rr(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}function Cl(e){return Rr(e)?.canonicalLanguage}var Px=f(()=>{"use strict";Sx()});var mf=f(()=>{"use strict";Px()});import{readFile as c0,stat as l0}from"node:fs/promises";function m0(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function Cx(e){return e.include?.length?e.include:pf(e.langType)}async function f0(e){try{return(await l0(e)).isFile()}catch{return!1}}async function h0(e,t){let n=await c0(e,"utf8"),r=await D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function wx(e){let t=bt(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await f0(t.sanitizedPath)?await h0(t.sanitizedPath,e):await D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...Cx(e)?{include:Cx(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:xx.length?{excludeDir:xx}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??u0,maxFileBytes:d0})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return N(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:v.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(p0+m0(e.pattern)),await Sl(r,e,"structural",i,o)}var xx,u0,d0,p0,Tx=f(()=>{"use strict";Le();Bt();me();mf();Rs();xx=[],u0=2e3,d0=1e6,p0="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 g0(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Rt(e){let t=g0(e);if(t.mode==="structural")return await wx(t);t.contextLines===void 0&&(t.contextLines=2);try{return await yx(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:q.OUTPUT_TOO_LARGE}:N(n,t,{toolName:v.LOCAL_RIPGREP})}}var Sr=f(()=>{"use strict";Bt();bn();me();uf();Tx()});async function Ex(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=pt(on,n);return r.ok===!1?r.error:await Rt(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var ff=f(()=>{"use strict";fs();me();Xe();Sr();Me();Dn();Rs()});import{z as ee}from"zod";import{ViewStructureQuerySchema as kx}from"@octocodeai/octocode-core/schemas";var Ox,y0,Pr,Ps,b0,R0,I3,wl=f(()=>{"use strict";ce();nt();mt();dt();qe();Ox={maxDepth:z(0,20).optional(),limit:z(1,1e4).optional(),page:Pe.default(1),itemsPerPage:z(1,50).optional(),filesOnly:ee.boolean().optional().describe("Returns files only. Mutually exclusive with directoriesOnly. (Unlike localSearchCode's `filesOnly`, which filters search results to matching file paths \u2014 a different concept sharing this name.)")},y0=Ce(kx,Ox),Pr=be(kx,Ox),Ps=ge(y0,{maxQueries:5}),b0=ee.object({name:ee.string().optional(),type:ee.enum(["file","dir","directory","link","symlink"]),path:ee.string().optional(),depth:ee.number().optional(),size:ee.union([ee.number(),ee.string()]).optional(),sizeBytes:ee.number().optional(),modified:ee.string().optional(),permissions:ee.string().optional()}),R0=ee.object({path:ee.string().optional(),entries:ee.array(b0).optional(),files:ee.array(ee.string()).optional(),folders:ee.array(ee.string()).optional(),links:ee.array(ee.string()).optional(),summary:ee.union([ee.string(),ee.record(ee.string(),ee.unknown())]).optional(),pagination:In.optional(),next:ee.record(ee.string(),xe).optional(),warnings:ee.array(ee.string()).optional()}),I3=ee.object({results:ee.array(ee.object({id:ee.string(),status:ee.enum(["empty","error"]).optional(),data:R0}))}).extend(Mn)});function x0(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function vx(e,t){let n=e[t];return n===void 0?!1:S0.has(n)||n==="{"&&T0(e,t)}function C0(e,t,n){let r=n.pop()??!1,o=vx(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?Ax(e,t+1):t+1})}function w0(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Ax(e,t)})}function hf(e){if(e.length>P0)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=x0(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=C0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(vx(e,r)){let i=w0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function T0(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 Ax(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function D3(e,t){let n=hf(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}var S0,P0,gf=f(()=>{"use strict";S0=new Set(["+","*","?"]),P0=1e3});function Lx(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(!hf(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function _x(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 Fx(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}var yf=f(()=>{"use strict";gf()});async function Tl(e){try{let t=bt(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return E0(e,t.sanitizedPath,n)}catch(t){let n=at.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function E0(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=O0(e),s=r&&e.limit&&!k0(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:v0(e),limit:s})}catch(C){return _0(C,e,t)}let c=a.entries.map(C=>A0(C,n,e.details??!1)),l=Lx(c,e),u=e.sortBy??"name";l=l.sort((C,k)=>{let E=0;switch(u){case"size":{let _=C.sizeBytes??(C.size?us(C.size):0),w=k.sizeBytes??(k.size?us(k.size):0);E=_-w;break}case"time":n&&C.modified&&k.modified?E=C.modified.localeCompare(k.modified):E=C.name.localeCompare(k.name);break;case"extension":E=(C.extension||"").localeCompare(k.extension||"");break;default:E=C.name.localeCompare(k.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:m,pagination:p}=zm(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(C=>({...Fx(C),path:C.path??`${t.replace(/\/$/,"")}/${C.name}`}))}:{path:t,..._x(m)},y=[...a.warnings,...ps({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],b=d===0,S=Bm(l);return V(Ix({...b?{status:"empty"}:{},...g,summary:S,...p.hasMore||p.totalPages>1?{pagination:p}:{},...p.hasMore?{next:{nextPage:Fc(v.LOCAL_VIEW_STRUCTURE,{...e,page:p.currentPage+1},"Continue to the next page of directory entries.")}}:{},...y.length>0&&{warnings:y}},e),a.entries.reduce((C,k)=>C+k.path.length,0))}function k0(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function O0(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function v0(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function A0(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:Ro(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=L0(e.permissions)),o}function L0(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 _0(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=at.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return N(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function Ix(e,t){return e}var xs=f(()=>{"use strict";ds();me();Bt();Xo();yf();hl();le();Le();qe()});async function Mx(e){let{queries:t}=e;return fe(t||[],async n=>ht({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=pt(Pr,n);return r.ok===!1?r.error:await Tl(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var bf=f(()=>{"use strict";wl();me();Xe();xs();Me();Dn();xs()});var Nn,Cs,Rf,Sf,Dx=f(()=>{"use strict";Nn=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","diff","research","graph","materialize"],Cs=["fixes","dataflow"],Rf=["packages","repositories"],Sf={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});function Pf(e){return Array.isArray(e.queries)}function xf(e){return Array.isArray(e.queries)}function Cf(e){return Array.isArray(e.children)}var Nx=f(()=>{"use strict"});var Gn=f(()=>{"use strict";Dx();Nx()});import{z as $}from"zod";var Gx,Hx,F0,I0,xr,wf,M0,D0,Hn,Qx=f(()=>{"use strict";Gx=$.enum(["smart","sensitive","insensitive"]),Hx=$.string().max(1e4),F0=$.strictObject({id:$.string().optional(),kind:$.literal("text"),value:Hx,case:Gx.optional(),wholeWord:$.boolean().optional()}),I0=$.strictObject({id:$.string().optional(),kind:$.literal("regex"),value:Hx,dialect:$.enum(["rust","pcre2","provider"]).optional(),case:Gx.optional(),wholeWord:$.boolean().optional(),multiline:$.boolean().optional(),dotAll:$.boolean().optional()}),xr=$.lazy(()=>$.strictObject({pattern:$.string().optional(),kind:$.string().optional(),inside:xr.optional(),has:xr.optional(),not:xr.optional(),all:$.array(xr).optional(),any:$.array(xr).optional(),stopBy:$.literal("end").optional()})),wf=$.union([xr,$.string().min(1)]),M0=$.strictObject({id:$.string().optional(),kind:$.literal("structural"),lang:$.string().min(1),pattern:$.string().optional(),rule:wf.optional()}),D0=$.strictObject({id:$.string().optional(),kind:$.literal("field"),field:$.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:$.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:$.unknown().optional()}),Hn=$.lazy(()=>$.discriminatedUnion("kind",[$.strictObject({kind:$.literal("all"),id:$.string().optional(),of:$.array(Hn).min(1)}),$.strictObject({kind:$.literal("any"),id:$.string().optional(),of:$.array(Hn).min(1)}),$.strictObject({kind:$.literal("not"),id:$.string().optional(),predicate:Hn}),F0,I0,M0,D0]))});import{z as P}from"zod";var Ef,Tf,N0,jx,Bx,zx,Ux,El,G0,fJ,$x,qx,Wx,Vx,ws,Kx,Yx,Qn,Cr=f(()=>{"use strict";Gn();Qx();Ef=P.lazy(()=>P.union([P.strictObject({kind:P.literal("local"),path:P.string().min(1)}),P.strictObject({kind:P.literal("github"),repo:P.string().min(1).optional(),owner:P.string().min(1).optional(),ref:P.string().min(1).optional()}),P.strictObject({kind:P.literal("materialized"),localPath:P.string().min(1),source:Ef.optional()}),P.strictObject({kind:P.literal("npm")})])),Tf=P.union([P.string(),P.array(P.string()).max(100)]),N0=P.strictObject({path:Tf.optional(),language:Tf.optional(),include:P.array(P.string()).max(100).optional(),exclude:P.array(P.string()).max(100).optional(),excludeDir:P.array(P.string()).max(100).optional(),hidden:P.boolean().optional(),noIgnore:P.boolean().optional(),minDepth:P.number().int().min(0).max(64).optional(),maxDepth:P.number().int().min(0).max(64).optional()}).optional(),jx=P.strictObject({mode:P.enum(["never","auto","required"]),strategy:P.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:P.boolean().optional(),forceRefresh:P.boolean().optional()}),Bx=P.strictObject({content:P.strictObject({range:P.strictObject({startLine:P.number().int().min(1).optional(),endLine:P.number().int().min(1).optional(),contextLines:P.number().int().min(0).max(100).optional()}).optional(),match:P.strictObject({text:P.string(),regex:P.boolean().optional(),caseSensitive:P.boolean().optional()}).optional(),contentView:P.enum(["none","standard","symbols","exact","compact"]).transform(e=>e==="exact"?"none":e==="compact"?"standard":e).optional(),charOffset:P.number().int().min(0).max(1e8).optional(),charLength:P.number().int().min(1).max(5e4).optional(),fullContent:P.boolean().optional()}).optional(),tree:P.strictObject({maxDepth:P.number().int().min(0).max(64).optional(),pattern:P.string().optional(),includeSizes:P.boolean().optional(),extensions:P.array(P.string()).optional(),filesOnly:P.boolean().optional(),directoriesOnly:P.boolean().optional(),sortBy:P.enum(["name","size","time","extension"]).optional(),reverse:P.boolean().optional()}).optional()}),zx=P.strictObject({search:P.strictObject({countLinesPerFile:P.boolean().optional(),countMatchesPerFile:P.boolean().optional(),onlyMatching:P.boolean().optional(),unique:P.boolean().optional(),countUnique:P.boolean().optional(),contextLines:P.number().int().min(0).max(100).optional(),invertMatch:P.boolean().optional(),matchWindow:P.number().int().min(0).optional(),matchContentLength:P.number().int().min(1).optional(),maxMatchesPerFile:P.number().int().min(1).optional(),matchPage:P.number().int().min(1).optional(),sort:P.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:P.boolean().optional(),rankingProfile:P.string().optional(),debugRanking:P.boolean().optional()}).optional(),budget:P.strictObject({maxFiles:P.number().int().min(1).optional(),maxCandidates:P.number().int().min(1).optional(),maxBytes:P.number().int().min(1).optional(),maxMaterializedBytes:P.number().int().min(1).optional(),maxPlanNodes:P.number().int().min(1).optional(),maxBooleanExpansion:P.number().int().min(1).optional(),timeoutMs:P.number().int().min(1).optional()}).optional()}),Ux=P.enum(["discovery","paginated","detailed"]),El=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),target:P.enum(Nn),from:Ef.optional(),scope:N0,where:Hn.optional(),materialize:jx.optional(),fetch:Bx.optional(),select:P.array(P.string()).optional(),view:Ux.optional(),controls:zx.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional()}),G0=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),queries:P.array(El).min(1).max(5),combine:P.enum(["independent","merge"]).optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),explain:P.boolean().optional()}),fJ=P.union([El,G0]),$x=[...Nn,...Cs],qx={schema:P.literal("oql").optional(),id:P.string().optional(),mainResearchGoal:P.string().optional(),researchGoal:P.string().optional(),reasoning:P.string().optional()},Wx={...qx,target:P.enum($x).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Ef.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:Hn.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:P.union([jx,P.enum(["never","auto","required"])]).optional(),fetch:Bx.optional(),select:P.array(P.string()).optional(),view:Ux.optional(),controls:zx.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional(),repo:P.string().optional(),owner:P.string().optional(),ref:P.string().optional(),path:Tf.optional(),text:P.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:P.string().optional(),pattern:P.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:wf.optional(),lang:P.string().optional(),and:P.array(P.unknown()).optional(),or:P.array(P.unknown()).optional(),xor:P.array(P.unknown()).optional(),noneOf:P.array(P.unknown()).optional(),oneOf:P.array(P.unknown()).optional(),invert:P.unknown().optional(),filesOnly:P.boolean().optional(),filesWithoutMatch:P.boolean().optional(),verbose:P.boolean().optional()},Vx={...Wx,target:P.enum($x).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},ws=P.object(Vx).catchall(P.unknown()),Kx=P.object(Wx).catchall(P.unknown()),Yx=P.object({...qx,queries:P.array(P.unknown()).min(1)}).catchall(P.unknown()),Qn=P.object({...Vx,queries:P.array(P.unknown()).min(1).max(5).optional(),combine:P.enum(["independent","merge"]).optional()}).catchall(P.unknown())});function x(e,t,n={}){let r=n.severity??(Q0.has(e)?"error":"warning"),o=n.blocksAnswer??(H0.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function Xx(e){return e.some(t=>t.blocksAnswer)}var H0,Q0,sn,ne=f(()=>{"use strict";H0=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),Q0=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);sn=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});function Z(...e){throw new sn(e)}function wr(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var Po=f(()=>{"use strict";ne()});import{z as T}from"zod";function Zx(e,t){let n=X0[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var _e,j0,Jx,B0,z0,U0,$0,q0,W0,V0,K0,Y0,X0,eC=f(()=>{"use strict";_e=T.number().int().min(1),j0=T.number().int().min(0),Jx=T.enum(["symbols","files","dependencies","relations"]),B0=T.object({match:T.enum(["file","path"]).optional(),concise:T.boolean().optional(),extension:T.string().optional(),filename:T.string().optional(),page:_e.optional(),limit:_e.optional()}).passthrough(),z0=T.object({type:T.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:T.string().optional(),symbolName:T.string().optional(),symbolKind:T.string().optional(),lineHint:_e.optional(),orderHint:T.number().int().optional(),includeDeclaration:T.boolean().optional(),depth:T.number().int().min(0).max(20).optional(),groupByFile:T.boolean().optional(),workspaceRoot:T.string().optional(),format:T.enum(["structured","compact"]).optional(),page:_e.optional(),itemsPerPage:_e.optional()}).passthrough(),U0=T.object({keywords:T.array(T.string()).optional(),topicsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:T.string().optional(),owner:T.string().optional(),stars:T.union([T.string(),T.number()]).optional(),forks:T.string().optional(),goodFirstIssues:T.string().optional(),size:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),license:T.string().optional(),match:T.array(T.enum(["name","description","readme"])).optional(),visibility:T.enum(["public","private"]).optional(),archived:T.boolean().optional(),sort:T.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:T.boolean().optional(),page:_e.optional()}).passthrough(),$0=T.object({packageName:T.string().optional(),keywords:T.array(T.string()).optional(),mode:T.enum(["lean","full"]).optional(),page:_e.optional()}).passthrough(),q0=T.object({prNumber:_e.optional(),concise:T.boolean().optional(),state:T.enum(["open","closed","merged"]).optional(),author:T.string().optional(),label:T.union([T.string(),T.array(T.string())]).optional(),keywordsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:T.string().optional(),base:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),closed:T.string().optional(),"merged-at":T.string().optional(),draft:T.boolean().optional(),archived:T.boolean().optional(),sort:T.enum(["created","updated","best-match","comments","reactions"]).optional(),order:T.enum(["asc","desc"]).optional(),reviewMode:T.string().optional(),filePage:_e.optional(),commentPage:_e.optional(),commitPage:_e.optional(),charOffset:j0.optional(),charLength:_e.optional(),minify:T.enum(["none","standard"]).optional(),limit:_e.optional(),page:_e.optional(),matchString:T.string().optional(),matchScope:T.enum(["body","title","comments","reviews","all"]).optional(),content:T.record(T.string(),T.unknown()).optional()}).passthrough(),W0=T.object({path:T.string().optional(),branch:T.string().optional(),since:T.string().optional(),until:T.string().optional(),author:T.string().optional(),includeDiff:T.boolean().optional(),limit:_e.optional(),page:_e.optional()}).passthrough(),V0=T.object({prNumber:_e.optional(),files:T.array(T.string()).optional(),baseRef:T.string().optional(),headRef:T.string().optional(),path:T.string().optional()}).passthrough(),K0=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(Jx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:_e.optional()}).passthrough(),Y0=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(Jx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:_e.optional(),subject:T.string().optional(),subjectKind:T.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:T.union([T.string(),T.array(T.string())]).optional(),verdict:T.union([T.string(),T.array(T.string())]).optional(),direction:T.enum(["incoming","outgoing","both"]).optional(),proof:T.enum(["none","lsp"]).optional(),proofLimit:_e.max(25).optional(),includePackets:T.boolean().optional(),includeFacts:T.boolean().optional(),includeEdges:T.boolean().optional()}).passthrough(),X0={semantics:z0,repositories:U0,packages:$0,pullRequests:q0,commits:W0,diff:V0,research:K0,graph:Y0,code:B0}});function tC(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&Z(x("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),J0(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Rf.includes(t)||Z(x("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function J0(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}var nC=f(()=>{"use strict";ne();Gn();Po()});function rC(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&Z(x("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}var oC=f(()=>{"use strict";ne();Po()});function xo(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+xo(n),0):e.kind==="not"?1+xo(e.predicate):1:0}var kf=f(()=>{"use strict"});function iC(e,t){let n=tM(e);e.where&&n&&Z(x("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Of(r,"where"),vf(r,"where",new Map);let o=Hn.safeParse(r);return o.success||Z(x("invalidQuery",wr(o.error),{queryPath:"where"})),o.data}function eM(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:Z0}function tM(e){let t=n=>{let r=xo(n),o=eM(e);return r>o&&Z(x("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(Co)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(Co)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(Co)}};if(Array.isArray(e.xor)){e.xor.length!==2&&Z(x("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=Co(e.xor[0]),r=Co(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(nM(e.oneOf.map(Co)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&Z(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&Z(x("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function Co(e){if(e&&typeof e=="object"&&"kind"in e)return e;Z(x("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function nM(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Of(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&Z(x("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Of(n,`${t}.of[${r}]`));break;case"not":e.predicate||Z(x("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Of(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&Z(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":rM(e,t);break;default:break}}function vf(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&Z(x("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>vf(r,`${t}.of[${o}]`,n)):e.kind==="not"&&vf(e.predicate,`${t}.predicate`,n)}function rM(e,t){if(e.op==="exists"){e.value!==void 0&&Z(x("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&Z(x("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&Z(x("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}var Z0,sC=f(()=>{"use strict";Cr();ne();kf();Po();Z0=64});function aC(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return aC(e.predicate);default:return!1}}function cC(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:aC(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}var lC=f(()=>{"use strict"});function uC(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!iM(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function iM(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return oM.some(n=>t.includes(n))}var oM,dC=f(()=>{"use strict";oM=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"]});function Ts(e){let t=Kx.safeParse(e);t.success||Z(x("invalidQuery",wr(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??aM(n);r===void 0&&Z(x("invalidQuery",`Could not determine \`target\`; specify one of: ${Nn.join(", ")}.`,{queryPath:"target"})),Cs.includes(r)&&Z(x("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${Nn.join(", ")}.`}})),Nn.includes(r)||Z(x("unknownField",`Unknown target "${r}".`));for(let h of Object.keys(n))sM.has(h)||Z(x("unknownField",`Unknown field "${h}" is not part of OQL.`,{queryPath:h}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=tC(n,r),a=rC(n,s),c=iC(n,r),l=cC(n,s,c,r),u=cM(n),d=uC(n,r),m={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(m.target==="code"&&!m.where&&Z(x("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.where&&Z(x("invalidQuery",`target:"${m.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.from?.kind==="github"&&!(m.from.repo&&m.from.repo.includes("/"))&&Z(x("invalidQuery",`target:"${m.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),m.target==="materialize"&&(m.where&&Z(x("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),m.from?.kind!=="github"&&m.from?.kind!=="materialized"&&Z(x("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),m.params!==void 0){let h=Zx(m.target,m.params);h&&Z(x("invalidQuery",h,{queryPath:"params"}))}let p=El.safeParse(m);return p.success||Z(x("invalidQuery",wr(p.error))),p.data}function aM(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function cM(e){return e.fetch?{...e.fetch}:void 0}var sM,kl=f(()=>{"use strict";Cr();ne();eC();Gn();Po();nC();oC();sC();lC();dC();sM=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"])});function pC(e){let t=Yx.safeParse(e);t.success||Z(x("invalidQuery",wr(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||Z(x("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&Z(x("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return Ts(i)}catch(a){throw a instanceof sn?new sn(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}var mC=f(()=>{"use strict";Cr();ne();Po();kl()});function fC(e){return Pf(e)?pC(e):Ts(e)}var hC=f(()=>{"use strict";Gn();mC();kl();kl()});function Es(e){let t=uM(e),n=pM(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function uM(e){return!e.executable||e.diagnostics.some(t=>lM.has(t.code))?"unsupported":e.approximate||dM(e.diagnostics)?"candidate":Xx(e.diagnostics)||gC(e)?"partial":"proof"}function dM(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function gC(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function pM(e){return!e.executable||gC(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function yC(e){return e.some(t=>!t.exact)}function Ol(e,t,n,r,o){return Es({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var lM,ks=f(()=>{"use strict";ne();lM=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function vl(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(vl):e.kind==="not"?vl(e.predicate):[e]}function Af(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function Qe(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function wo(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Lf(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var jn=f(()=>{"use strict"});import Tr from"node:path";import{statSync as mM}from"node:fs";function bC(e){let t=Tr.resolve(e);try{if(mM(t).isDirectory())return`${t}${Tr.sep}`}catch{}return`${Tr.dirname(t)}${Tr.sep}`}function RC(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function SC(e,t){let n=RC(e);if(!n)return;let r=bC(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function PC(e){let t=RC(e);if(!t)return;let n=bC(t).slice(0,-Tr.sep.length);return r=>({kind:"local",path:Tr.isAbsolute(r)?r:Tr.join(n,r)})}var _f=f(()=>{"use strict"});function xC(e,t){for(let n of t)n.proofGrade??=fM(e,n)}function fM(e,t){return t.kind==="code"?Os(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Os(e.where,"text")||Os(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?vs(t.data)?"missing":"graph":t.recordType==="research"?vs(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"?"text":"candidate"}function Os(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Os(n,t)):e.kind==="not"?Os(e.predicate,t):!1:!1}function vs(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!hM(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function hM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ff=f(()=>{"use strict"});function gM(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function CC(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:gM(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"none",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function wC(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function yM(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function bM(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function TC(e){let t=bM(e);return t?yM(t,"materialized"):void 0}function EC(e,t){return OC(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function kC(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(vs(r))return OC(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function OC(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!vs(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=SM(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function SM(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&RM.has(o));return r.length>0?r:void 0}var RM,vC=f(()=>{"use strict";Ff();RM=new Set(["symbols","files","dependencies","relations"])});import As from"node:path";import{statSync as PM}from"node:fs";function AC(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=wM(e)??TM(t.query),i=xM(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"none",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function xM(e,t){if(e&&As.isAbsolute(e))return e;if(t&&As.isAbsolute(t)){let n=CM(t);return e?As.resolve(n,e):t}return t??e}function CM(e){try{return PM(e).isDirectory()?e:As.dirname(e)}catch{return As.dirname(e)}}function wM(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function TM(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}var LC=f(()=>{"use strict"});function EM(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function kM(e){let t=EM(e),n=Qe(e.scope),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${_C(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${_C(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function _C(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function FC(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${kM(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:PC(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=OM[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function IC(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||If(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function If(e,t){return e.why===t.why&&e.confidence===t.confidence}var OM,Mf=f(()=>{"use strict";jn();_f();vC();LC();OM={code:CC,content:wC,"record:materialized":TC,"record:semantics":AC,"record:research":EC,"record:graph":kC}});import{completeMetadata as vM}from"@octocodeai/octocode-core";function Ls(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function xZ(e){return AM.has(e)}var X,je,Bn,AM,To=f(()=>{"use strict";X=vM.toolNames,je=X.LSP_GET_SEMANTIC_CONTENT,Bn="oqlSearch";AM=new Set([X.LOCAL_RIPGREP,X.LOCAL_FETCH_CONTENT,X.LOCAL_FIND_FILES,X.LOCAL_VIEW_STRUCTURE,je])});function an(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Df(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 MC,Lt=f(()=>{"use strict";To();MC=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{z as te}from"zod";import{NpmPackageQuerySchema as DC}from"@octocodeai/octocode-core/schemas";var NC,_s,Fs,_Z,Nf=f(()=>{"use strict";nt();mt();dt();qe();NC={page:Pe,mode:te.enum(["lean","full"]).optional(),keywords:te.union([te.string(),te.array(te.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},_s=be(DC,NC),Fs=ge(Ce(DC,NC,{strict:!0}),{maxQueries:5}),_Z=te.object({results:te.array(te.looseObject({id:te.string(),data:te.looseObject({packages:te.array(te.object({name:te.string(),version:te.string().optional(),description:te.string().optional(),license:te.string().optional(),downloads:te.number().optional(),repository:te.string().optional(),repositoryDirectory:te.string().optional(),repositoryId:te.string().optional(),next:te.record(te.string(),xe).optional(),warnings:te.array(te.string()).optional(),diagnostics:te.array(uo).optional()}).passthrough()).optional(),repositories:te.record(te.string(),te.object({repository:te.string(),owner:te.string(),repo:te.string(),repositoryDirectory:te.string().optional(),next:te.record(te.string(),xe)}).passthrough()).optional(),pagination:ut.optional()}).optional(),status:te.string().optional()})).optional()}).extend(We)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as QC}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as LM}from"@octocodeai/octocode-core/schemas/outputs";var _M,FM,IM,jC,MM,ko,DM,Oo,GC,NM,GM,Al,Ll,HM,QM,BC,Eo,jM,BM,zM,zC,UM,$M,qM,WM,VM,KM,YM,HC,XM,_l=f(()=>{"use strict";ce();nt();mt();Lt();qe();_M=z(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),FM=z(0,1e5).optional(),IM=["structured","compact"],jC={type:R.enum(MC).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:R.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:_M.optional(),orderHint:FM,depth:z(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:Pe,itemsPerPage:z(1,100).optional(),contextLines:z(0,100).optional(),format:R.enum(IM).optional().default("structured")},MM=Ce(QC,jC),ko=be(QC,jC),DM=ko,Oo=ge(MM,{maxQueries:5}),GC=R.object({line:R.number(),character:R.number()}),NM=R.object({start:GC,end:GC}),GM=R.object({startLine:R.number(),endLine:R.number()}),Al=R.object({uri:R.string(),content:R.string().optional(),displayRange:GM.optional(),isDefinition:R.boolean().optional()}),Ll=R.string(),HM=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),QM=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),BC=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Eo=R.object({category:BC,reason:R.string()}),jM=ut,BM=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),zM=R.string(),zC=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),UM=R.string(),$M=R.object({direction:R.enum(["incoming","outgoing"]),item:zC,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),qM=R.string(),WM=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),VM=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),KM=R.string(),YM=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Al,Ll]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Al,Ll]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Al,Ll]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Al,Ll])).optional(),byFile:R.array(R.union([VM,KM])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:Eo.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([zC,UM]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([$M,qM])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:WM,empty:Eo.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:NM.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([BM,zM])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:Eo.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:Eo.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:Eo.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:Eo.optional()}),R.object({kind:R.literal("empty"),category:BC,reason:R.string()})]),HC=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:HM.optional(),lsp:QM.optional(),payload:YM,pagination:jM.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional(),next:R.record(R.string(),xe).optional(),hints:R.array(R.string()).optional()}),XM=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),responsePagination:lo.optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:HC}),R.object({id:R.string().min(1),status:R.literal("error"),data:LM}),R.object({id:R.string().min(1),data:HC})]))})});var Gf=f(()=>{"use strict";am();Uc();gm();ul();Fm();Mm();Nf();ml();fl();fs();wl();_l();Cr()});import{z as UC}from"zod";function Er(e){return eD.find(t=>t.name===e)}function Is(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===X.PACKAGE_SEARCH?"Package":"Other"}function a6(e){return[...e].sort((t,n)=>{let r=$C.indexOf(Is(t)),o=$C.indexOf(Is(n));if(r!==o)return r-o;let i=qC.get(t)??Number.MAX_SAFE_INTEGER,s=qC.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function c6(e){let t=Er(e);if(!t)return"{}";try{return JSON.stringify(UC.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(UC.toJSONSchema(t.schema,{io:"input"}),null,2)}}function l6(e){return JSON.stringify(e??{},null,2)}function u6(e){let t=Is(e),n=[...ZM];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function d6(){return WC.map(e=>({...e}))}function p6(){return JSON.stringify(Object.fromEntries(WC.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function m6(e,t){return t?.tools?.[e]?.description??e}var $C,qC,_t,JM,Ms,ZM,WC,eD,Ds=f(()=>{"use strict";To();Lt();Gf();$C=["GitHub","Local Code","Package","Other"],qC=new Map([X.GITHUB_SEARCH_CODE,X.GITHUB_SEARCH_REPOSITORIES,X.GITHUB_SEARCH_PULL_REQUESTS,X.GITHUB_FETCH_CONTENT,X.GITHUB_VIEW_REPO_STRUCTURE,X.GITHUB_CLONE_REPO,X.LOCAL_RIPGREP,X.LOCAL_FIND_FILES,X.LOCAL_FETCH_CONTENT,X.LOCAL_VIEW_STRUCTURE,je,X.PACKAGE_SEARCH,...Ls()?[Bn]:[]].map((e,t)=>[e,t])),_t=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},JM=["id","mainResearchGoal","researchGoal","reasoning"],Ms=new Set([...JM]),ZM=["id","researchGoal","reasoning"],WC=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],eD=[{name:X.GITHUB_SEARCH_CODE,schema:Yi,inputSchema:Xi},{name:X.GITHUB_FETCH_CONTENT,schema:dr,inputSchema:Vi},{name:X.GITHUB_VIEW_REPO_STRUCTURE,schema:is,inputSchema:ss},{name:X.GITHUB_SEARCH_REPOSITORIES,schema:rs,inputSchema:os},{name:X.GITHUB_SEARCH_PULL_REQUESTS,schema:hr,inputSchema:ns},{name:X.PACKAGE_SEARCH,schema:_s,inputSchema:Fs},{name:X.GITHUB_CLONE_REPO,schema:fo,inputSchema:Wi},{name:X.LOCAL_RIPGREP,schema:on,inputSchema:ms},{name:X.LOCAL_VIEW_STRUCTURE,schema:Pr,inputSchema:Ps},{name:X.LOCAL_FIND_FILES,schema:yr,inputSchema:ls},{name:X.LOCAL_FETCH_CONTENT,schema:gr,inputSchema:cs},{name:je,schema:ko,inputSchema:Oo},...Ls()?[{name:Bn,schema:ws,inputSchema:Qn}]:[]]});import{z as tD}from"zod";function Fl(e){let t=Er(e);if(!t)return[];let n=tD.toJSONSchema(t.schema,{io:"input"});if(!vo(n))return[];let r=cn(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Ms.has(i)&&!jf(r[i])):[]);return Qf(r,o)}function nD(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 Hf(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=vo(e.items)?e.items:void 0;return`array<${n?Hf(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(vo).map(Hf).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 Qf(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Ms.has(o))continue;let s=vo(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Hf(s),constraints:nD(s),description:typeof s.description=="string"?s.description:void 0}),cn(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!jf(s.properties?.[u]):!1):[]);r.push(...Qf(s.properties,l,a))}let c=s.type==="array"&&vo(s.items)?s.items:void 0;if(c&&cn(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!jf(c.properties?.[u]):!1):[]);r.push(...Qf(c.properties,l,a))}}return r}function KC(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[VC(e,n)]}return VC(e,t)}function VC(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 cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vo(e){return cn(e)}function jf(e){return vo(e)&&"default"in e}var Il=f(()=>{"use strict";Ds()});function YC(e){return e===Bn?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===X.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"2024-01-01T00:00:00Z",perPage:5}},{label:"releases + latest",query:{type:"releases",owner:"microsoft",repo:"TypeScript",perPage:5}},{label:"issues search",query:{type:"issues",owner:"microsoft",repo:"TypeScript",keywordsToSearch:["crash"],state:"open",concise:!0,limit:5}},{label:"issue detail",query:{type:"issues",owner:"bgauryy",repo:"octocode",issueNumber:443,content:{body:!0,comments:{discussion:!0}}}}]:e===X.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===X.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===X.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===X.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===X.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",keywords:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===X.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===X.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===X.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,filesOnly:!0,itemsPerPage:100}}]:e===je?[{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}}]:[]}var XC=f(()=>{"use strict";To()});function JC(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function rD(e){let t=YC(e);if(t.length>0)return t.map(r=>({...r,command:JC(e,r.query)}));let n=oD(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:JC(e,n)}]}function w6(e){return rD(e)[0]?.query??{}}function oD(e){if(!Er(e))return{};let t=Fl(e),n=t.filter(i=>!i.name.includes(".")),r=iD(n),o={};for(let i of r)o[i.name]=KC(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===je&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function iD(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&&sD(i)).sort(aD),o=Math.max(ZC,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=>!ew.has(i.name)).filter(i=>i.type!=="boolean").slice(0,ZC)}function sD(e){return ew.has(e.name)||e.type==="boolean"?!1:cD(e)?Bf.has(e.name):!0}function aD(e,t){let n=Bf.get(e.name)??Number.MAX_SAFE_INTEGER,r=Bf.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function cD(e){return e.constraints?.includes("default ")===!0}var ZC,Bf,ew,tw=f(()=>{"use strict";Lt();Ds();XC();Il();ZC=4,Bf=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]]),ew=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});function O6(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new _t("Tool input must be valid JSON.")}return lD(e,r,n)}function lD(e,t,n={}){let r=dD(e,t,n),o=Er(e);if(!o)throw new _t(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new _t("Tool input does not match the expected schema.",uD(i.error));return i.data}function uD(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function dD(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(cn(t)&&Array.isArray(t.queries))r=t.queries;else if(cn(t))r=[t];else throw new _t('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new _t("At least one query is required.");let o=cn(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>pD(e,a,bD(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function pD(e,t,n,r){let o={...n},i=Is(e),s=r.sourceLabel??"direct tool execution",a=mD(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 mD(e,t){return`Execute ${e} via ${t}`}function fD(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 hD(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),l=fD(n,c);if(c.includes(n)||n.includes(c)){l<o&&(r=a,o=l);continue}if(n.length<3)continue;let u=Math.max(2,Math.floor(a.length/3));l<=u&&l<s&&(i=a,s=l)}return r??i}function yD(e,t){let n=gD[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n))o in t&&!(i in t)&&(r??={...t},r[i]=r[o],delete r[o]);return r??t}function bD(e,t,n,r={}){if(!cn(t))throw new _t("Tool input must be a JSON object or an array of objects.");let o=yD(e,t),i=new Set([...Fl(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Ms]),s={},a=[];for(let[c,l]of Object.entries(o)){if(i.has(c)){s[c]=l;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(l=>{let u=hD(l,i);return u?`'${l}' \u2192 did you mean '${u}'?`:""}).filter(Boolean);throw new _t(`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}var gD,nw=f(()=>{"use strict";Ds();Il();gD={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"keywords"}}});var zf=f(()=>{"use strict";Ds();Il();tw();nw()});import{existsSync as rw}from"fs";import{delimiter as RD,dirname as SD,join as ow}from"path";function iw(){return process.platform==="win32"?"npm.cmd":"npm"}function PD(){let e=SD(process.execPath);return ow(e,iw())}function xD(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function CD(){let e=(process.env.PATH??"").split(RD).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...xD()])]}function sw(){let e=PD();if(rw(e))return{command:process.execPath,argsPrefix:[e]};let t=iw();for(let n of CD()){let r=ow(n,t);if(rw(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function G6(e=1e4){let t=sw();return NR(t.command,[...t.argsPrefix,"--version"],e)}async function zn(e,t,n={}){if(!wD.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Gc(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=sw(),c=await tn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:TD});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var wD,TD,Ao=f(()=>{"use strict";mo();wD=["view","search","ping","config","whoami"],TD=[...po,...DR]});async function Gs(){if(Ns)return Ns;try{let e=await zn("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 Ns=t,t}}catch{}return Ns=Lo,Lo}function ED(){Ns=null}async function kD(){try{let e=await Gs(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}var Lo,Ns,Hs=f(()=>{"use strict";Ao();Lo="https://registry.npmjs.org",Ns=null});function js(e){try{return new URL(e).host||e}catch{return e}}function aw(e,t=Date.now()){let n=_o.get(js(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Qs)throw new Uf(js(e),Qs-r);n.state="half-open"}}function qf(e){let t=_o.get(js(e));t&&(t.failures=0,t.state="closed")}function cw(e,t=Date.now()){let n=js(e),r=_o.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=$f&&(r.state="open",r.openedAt=t)),_o.set(n,r)}function z6(){_o.clear(),$f=5,Qs=3e4}function U6(e){typeof e.failureThreshold=="number"&&($f=e.failureThreshold),typeof e.cooldownMs=="number"&&(Qs=e.cooldownMs)}function lw(e,t=Date.now()){let n=_o.get(js(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Qs:!1}var B6,_o,$f,Qs,Uf,Ml=f(()=>{"use strict";B6=5,_o=new Map,$f=5,Qs=3e4;Uf=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}}});import{z as L}from"zod";var Dl,OD,uw,dw,Bs=f(()=>{"use strict";Dl=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),OD=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),uw=L.looseObject({objects:L.array(OD),total:L.union([L.number(),L.string()]).optional()}),dw=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});function pw(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function AD(e,t,n,r){e&&En({limit_type:"primary",retry_after_seconds:pw(r),api_method:t,api_url:n,provider:e})}function LD(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Wo.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&qy(r),e.status===429&&AD(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function _D(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=pw(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Ut(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=vD,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let y=e.includes("?")?"&":"?";d=`${e}${y}version=${encodeURIComponent(nr)}`}let m={"User-Agent":`Octocode-MCP/${nr}`,...i},p=globalThis.fetch;if(!p)throw new Error(Wo.FETCH_NOT_AVAILABLE.message);aw(d);let h,g=n+1;for(let y=1;y<=g;y++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(d,{method:s,headers:m,signal:c});if(!b.ok)throw LD(b,s,d,u,l);if(b.status===204)return qf(d),null;let S=await b.json();return qf(d),S}catch(b){let S=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw b;if(h=b instanceof Error?b:new Error(String(b)),y===g)break;let C=_D(y,r,o,S);await new Promise(k=>setTimeout(k,C))}}throw cw(d),new Error(Wo.FETCH_FAILED_AFTER_RETRIES.message(g,h?.message||""))}var vD,zs=f(()=>{"use strict";Va();st();pi();Ml();vD=6e4});function Un(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function Ze(e){return e===void 0?0:Q(e)}async function Nl(e){try{let t=`${FD}/${encodeURIComponent(e)}`,n=await Ut(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:Ze(n)}}catch{return{rawResponseChars:0}}}function mw(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 fw(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 ID(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Gl(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Un(e.repository):(e.repository.url&&(r=Un(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:ID(e),...o?{repositoryDirectory:o}:{},...mw(e.exports)?{exports:mw(e.exports)}:{},...fw(e.bin,e.name)?{bin:fw(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 MD(e){return typeof e.links?.repository=="string"?Un(e.links.repository):typeof e.repository=="string"?Un(e.repository):typeof e.repository?.url=="string"?Un(e.repository.url):null}function hw(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:MD(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 Wf(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function gw(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 FD,Vf=f(()=>{"use strict";zs();le();FD="https://api.npmjs.org/downloads/point/last-week"});function Kf(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 Yf(e){try{let t=await Gs(),n=Wf(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Ut(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ze(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Ut(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ze(i)}}catch{return{rawResponseChars:0}}}async function Ql(e,t,n){let[r,o]=await Promise.all([Nl(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Yf(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 Hl(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function ND(e,t){try{let n=await zn("view",[e,"--json"],{timeout:DD});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,...Hl(c)?{}:{errorDetail:c},rawResponseChars:Ze(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=Ze(o),s=Dl.safeParse(o);return s.success?{pkg:Gl(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,...Hl(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function GD(e,t){try{let n=await Gs(),r=Wf(e),o=`${n}/${r}/latest`,i;try{i=await Ut(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Ze(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=Dl.safeParse(i);return a.success?{pkg:Gl(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,...Hl(r)?{}:{errorDetail:r},rawResponseChars:0}}}function HD(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Xf(e,t){let n=0,r;for(let o of HD(e)){let i;try{i=await Ut(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);Hl(l)||(r=l);continue}if(n+=Ze(i),!i||typeof i!="object")continue;let s=Dl.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Gl(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function jl(e,t=!1){let[n,r]=await Promise.allSettled([ND(e,t),GD(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?Ql(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function yw(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await jl(e,t);if(!r){if(o){let s=Kf(o);if(s&&n){let a=await Xf(e,t);if(a.pkg){let c=await Ql(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}}var DD,Jf=f(()=>{"use strict";Ao();zs();Bs();Hs();Vf();DD=3e3});async function QD(e,t,n,r=0){let o=Math.max(t+r,t),i=await zn("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:Ze(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=Ze(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((h,g)=>{let y=h?.score?.final??0;return(g?.score?.final??0)-y}).slice(r,r+t),d=await Promise.all(u.map(async h=>{if(!h||typeof h!="object")return null;let g=h;if(!g.name)return null;if(n){let y=await jl(g.name,!0);if(y.pkg)return y}return{pkg:hw(g),rawResponseChars:0}})),m=d.map(h=>h?.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function jD(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Lo}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Ut(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(h){return{error:`NPM registry search failed: ${h instanceof Error?h.message:String(h)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ze(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=uw.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 u=[...c.data.objects].sort((h,g)=>{let y=h.score?.final??0;return(g.score?.final??0)-y}).map(h=>h.package).filter(h=>typeof h.name=="string"&&h.name.length>0).slice(0,t),d=await Promise.all(u.map(async h=>{if(n){let g=await jl(h.name,!0);if(g.pkg)return g}return{pkg:{name:h.name,npmUrl:(h.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(h.name)}`,repoUrl:h.links?.repository&&typeof h.links.repository=="string"?Un(h.links.repository):null,version:h.version??"unknown",source:"registry",...h.description?{description:h.description}:{},...h.links?.homepage?{homepage:h.links.homepage}:{}},rawResponseChars:0}})),m=d.map(h=>h.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+g.rawResponseChars,0);return{packages:m,totalFound:gw(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Zf(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 Ut(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:Ze(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ze(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"?Un(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:Ze(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function eh(e,t,n,r=0){try{let o=await QD(e,t,n,r);if(!("error"in o))return o}catch{}return jD(e,t,n,r)}async function th(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}):Nl(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Yf(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)]}}var bw=f(()=>{"use strict";Ao();zs();Bs();Hs();Vf();Jf()});function Us(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Rw(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function nh(e,t,n,r=0){let o=Te("npm-search",{name:e,limit:t,metadata:n,from:r});return He(o,async()=>{if(lw(Lo)){if(r===0&&t===1&&Us(e)){let u=await Xf(e,n);if(u.pkg){let d=await Ql(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await Zf(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Us(e)){let l=await yw(e,n,t===1);if("error"in l){if(!Kf(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await eh(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return th(s);let a=Rw(e);if(a!==e){let l=await eh(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return th(l)}let c=await Zf(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 Sw(e){try{let t=await zn("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=dw.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}}var Pw=f(()=>{"use strict";Ao();lt();Ml();Bs();Hs();Jf();bw()});var rh=f(()=>{"use strict";Hs();Pw()});async function xw(e){let t=Us(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return nh(e.name,n,!0,r)}var oh=f(()=>{"use strict";rh()});function BD(e){return"error"in e}function Bl(e){return"npmUrl"in e}function zD(e){return Bl(e)&&e.path?e.path:e.name}function UD(e){return Bl(e)?e.repoUrl:e.repository}function $D(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function qD(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function ih(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 Cw(e,t){let n=ih(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghHistoryResearch",query:{type:"releases",owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function WD(e){let t=zD(e),n=qD(UD(e)),r={name:t};Bl(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=$D(Bl(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=Cw(n,o);if(i&&(r.next=i),r.version&&ih(n)){let s=`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.warnings=[s],r.diagnostics=[{level:"warning",code:"npmRepoTagDivergence",message:s}]}return r}function VD(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=ih(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:Cw(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function KD(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,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function ww(e){return fe(e.queries,async t=>{try{if(!t.packageName)return N("Package name is required for package search",t);let n=await xw({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(BD(n))return N(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(WD),i=o.length>0,s=r.length>1||n.totalFound>1,a=KD(t,n.totalFound,o.length,s),l={...VD(o),pagination:a};return Ee(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return N(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var sh=f(()=>{"use strict";oh();Xe();Me();me()});function XD(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function Tw(e,t){if(t===void 0||t==="progressIdle")return e;let n=XD(e);if(!n||!YD.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]}}var YD,Ew=f(()=>{"use strict";YD=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as JD,stat as ZD}from"node:fs/promises";import{SymbolResolver as eN,SymbolResolutionError as tN}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as zl}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function ah(e,t){let n=e.uri,r=bt({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await ZD(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:zl.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:zl.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:o,absolutePath:o,content:await JD(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:zl.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function kw(e,t){let n=await ah(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 eN({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:nN(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof tN)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:zl.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 nN(e){return{start:e,end:{line:e.line,character:e.character}}}var Ul=f(()=>{"use strict";Bt()});function lh(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 uh(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:lh(e.type,t),reason:t}}}function St(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:lh(e,n),reason:n}}}function Pt(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}:{}}}}var $n,$l,ch,ql=f(()=>{"use strict";Lt();$n=40,$l=40,ch=10});function $s(e,t,n,r,o){let i=o.length>0,s=o.map(Df),{pageItems:a,pagination:c}=Pt(s,e.page??1,e.itemsPerPage??$l);return{type:e.type,uri:t.uri,resolvedSymbol:an(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 dh(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?Ow(r):void 0,i=o??r.map(Df),{pageItems:s,pagination:a}=Pt(i,e.page??1,e.itemsPerPage??$l),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function ph(e,t,n){let r=vw(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function Ow(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 vw(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=>Aw(r)).join(`
|
|
44
|
+
`).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 Aw(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var Lw=f(()=>{"use strict";Lt();ql()});import{safeReadFile as rN}from"@octocodeai/octocode-engine/lsp/validation";function qs(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Fw(e,t,n){if(t<=0)return e;let r=await rN(e.uri);if(!r)return e;let o=Oi(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
|
|
45
|
+
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function oN(e,t){return Promise.all(e.map(async n=>({...n,from:await Fw(n.from,t,n.fromRanges)})))}async function iN(e,t){return Promise.all(e.map(async n=>({...n,to:await Fw(n.to,t)})))}async function mh(e,t,n,r,o){if(n<=0||!e)return{calls:[],..._w};try{let i=await e.getIncomingCalls(t),s=o>0?await oN(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=qs(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),mh(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function fh(e,t,n,r,o){if(n<=0||!e)return{calls:[],..._w};try{let i=await e.getOutgoingCalls(t),s=o>0?await iN(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=qs(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),fh(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var _w,hh=f(()=>{"use strict";sr();_w={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function Mw(e){return V(e,Q(e))}function Dw(e,t){return e.format!=="compact"||!Gw(t)?t:aN(t)}function Nw(e){if(!Gw(e))return e;let n=e.payload.locations?.[0],r=n?.displayRange?.startLine;if(!n?.uri||typeof r!="number")return e;let o=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri;return{...e,next:{readSite:{tool:"localGetFileContent",query:{path:o,startLine:Math.max(1,r-3),endLine:(n.displayRange?.endLine??r)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}function Gw(e){return kr(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&kr(e.payload)}function aN(e){return{...e,format:"compact",payload:cN(e.payload)}}function cN(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Iw)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(uN)}:{locations:(e.locations??[]).map(Iw)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Hw(e.root)}:{},direction:e.direction,calls:e.calls.map(dN),...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(lN)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function lN(e){if(!kr(e))return String(e);let t=ot(e,"line"),n=ot(e,"character"),r=ot(e,"endLine"),o=ln(e,"kind"),i=ln(e,"name"),s=ot(e,"childCount"),a=ln(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Iw(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${jw(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function uN(e){if(!kr(e))return String(e);let t=ln(e,"uri"),n=ot(e,"firstLine"),r=ot(e,"firstCharacter"),o=ot(e,"count"),i=Qw(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 dN(e){if(!kr(e))return String(e);let t=ln(e,"direction"),n=Hw(e.item),r=Qw(e,"ranges").map(pN).join(","),o=ot(e,"rangeCount"),i=ot(e,"rangeSampleCount"),s=ln(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${jw(s,180)}`:""].filter(Boolean).join(" ")}function Hw(e){if(!kr(e))return String(e);let t=ln(e,"name"),n=ln(e,"kind"),r=ln(e,"uri"),o=ot(e,"line"),i=ot(e,"endLine"),s=ot(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function pN(e){return kr(e)?`${ot(e,"line")}:${ot(e,"character")}`:String(e)}function kr(e){return typeof e=="object"&&e!==null}function ln(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function ot(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Qw(e,t){let n=e[t];return Array.isArray(n)?n:[]}function jw(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 Bw(e,t){let n=Uw(e.fromRanges);return{direction:"incoming",item:Wl(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...$w(e.from,t)}}function zw(e,t){let n=Uw(e.fromRanges);return{direction:"outgoing",item:Wl(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...$w(e.to,t)}}function Wl(e){return{name:e.name,kind:Fo(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 Uw(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>=sN))break}return n}function $w(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Fo(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"}}var sN,Ws=f(()=>{"use strict";le();sN=8});async function gh(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return St(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await mh(n,o,i,new Set([qs(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await fh(n,o,i,new Set([qs(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),m=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],p=m.map(S=>S.direction==="incoming"?Bw(S,e.contextLines??0):zw(S,e.contextLines??0)),{pageItems:h,pagination:g}=Pt(p,e.page??1,e.itemsPerPage??ch),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:an(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Wl(o),direction:y,calls:h,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function yh(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return St(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}=Pt(s,e.page??1,e.itemsPerPage??$n);return{type:e.type,uri:t.uri,resolvedSymbol:an(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 qw=f(()=>{"use strict";hh();Lt();Ws();ql()});var Vs=f(()=>{"use strict";ql();Lw();qw()});import Ks from"node:path";import{readFile as mN}from"node:fs/promises";import{resolveImportAliasDefinitions as fN}from"@octocodeai/octocode-engine/lsp/resolver";async function Kw(e,t,n){if(typeof e.openDocument=="function")try{let r=Ks.extname(t.uri).slice(1),o=Ww.includes(r)?Ww:[r],i=await Rt({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:hN,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=Ks.isAbsolute(a)?a:Ks.join(n,a);if(Ks.resolve(c)!==Ks.resolve(t.uri))try{let l=await mN(c,"utf-8");if(l.length>gN)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function Yw(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?$s(e,t,"definition","definitionProvider",await fN({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):St(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?$s(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):St(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?$s(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):St(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?dh(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):St(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?ph(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):St(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?gh(e,t,n):St(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?yh(e,t,n):St(e.type,t,"typeHierarchyProvider unsupported",!0)}}var Vw,hN,gN,Ww,Xw=f(()=>{"use strict";Sr();Vs();Vw=new Set(["references","callers","callees","callHierarchy","implementation"]),hN=12,gN=512*1024,Ww=["ts","tsx","mts","cts","js","jsx","mjs","cjs"]});import Rh from"node:path";import{fileURLToPath as yN}from"node:url";import{unavailableHintFor as bN}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as RN}from"@octocodeai/octocode-engine/lsp/config";function Jw(e){return bh||(bh=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),bh.has(Rh.extname(e).toLowerCase())}function Ft(e,t){let n=RN(e),r=bN(n,void 0);throw new ze(q.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function Zw(e,t){let n=e.startsWith("file://")?yN(e):e;return Rh.isAbsolute(n)?n:Rh.resolve(t,n)}function Sh(){return[...D.getSupportedJsTsExtensions(),...SN]}function eT(){return Sh().map(e=>`**/*.${e}`)}async function tT(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:eT(),excludeDir:[...PN],maxSnippetChars:1})).files[0]?.path}catch{return}}async function Ph(e,t){if(e.uri)return Zw(e.uri,t);let n=await tT(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Sh(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function xh(e){return e instanceof Error?e.message:String(e)}function Ch(e,t){if(!Jw(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var bh,SN,PN,Vl=f(()=>{"use strict";Ko();bn();Le();SN=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];PN=[".git","node_modules","dist","out","coverage","target"]});import{acquirePooledClient as xN,isLanguageServerAvailable as CN}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as wN}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Eh(e){let t=await ah(e,je);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await wN(t.value.uri),r=await CN(t.value.uri,n),o=r?await xN(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Ch(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let y=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(y)?y:[],a="lsp"}else{let y=Ub(t.value.content,t.value.uri);y&&(s=y,a="markdown")}let l=a!==void 0;!l&&!r&&Ft(t.value.uri,"documentSymbols");let u=nT(s),d=oT(s),{pageItems:m,pagination:p}=Pt(u,e.page??1,e.itemsPerPage??$n),h=iT(u,y=>y.kind),g=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:u.length,returnedSymbols:m.length,topLevelSymbols:d,kinds:h},payload:{kind:"documentSymbols",symbols:m,...g?{empty:g}:{}},pagination:p}}function nT(e){let t=[];for(let n of e)kh(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function kh(e,t,n){if(!e||typeof e!="object")return;let r=e,o=rT(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Fo(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)&&TN.has(Fo(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)kh(s,t,i)}}function rT(e){if(wh(e.range))return e.range;let t=e.location;return t&&wh(t.range)?t.range:void 0}function wh(e){if(!e||typeof e!="object")return!1;let t=e;return Th(t.start)&&Th(t.end)}function Th(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function oT(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function iT(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}var TN,sT=f(()=>{"use strict";dc();Lt();Ul();Vs();Ws();Vl();TN=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});import aT from"node:path";import{acquirePooledClient as cT,isLanguageServerAvailable as lT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as EN}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Oh(e){let t=e.symbolName??"",n=aT.resolve(e.workspaceRoot??process.cwd()),r=await Ph(e,n);await lT(r,n)||Ft(r,"workspaceSymbol");let i=await cT(n,r);if(i||Ft(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{aT.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${xh(u)}`}}}let a=uT(s),{pageItems:c,pagination:l}=Pt(a,e.page??1,e.itemsPerPage??$n);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function uT(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:Fo(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function vh(e){let t=e.uri??"",n=e.workspaceRoot??(t?await EN(t):process.cwd());await lT(t,n)||Ft(t,"diagnostic");let o=await cT(n,t);if(o||Ft(t,"diagnostic"),!o.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 i=await o.getDiagnostics(t),s=dT(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Pt(s,e.page??1,e.itemsPerPage??$n);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function dT(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>pT(r))}return[]}function pT(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}var mT=f(()=>{"use strict";Vs();Ws();Vl()});var fT=f(()=>{"use strict";Vl();sT();mT()});import{acquirePooledClient as kN,isLanguageServerAvailable as ON}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as vN}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Ah(e){return fe(e.queries||[],async t=>ht({toolName:je,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await AN(t);return Mw(Nw(Dw(t,n)))}}),{toolName:je,minQueryTimeoutMs:3e4},e)}async function AN(e){if(e.type==="documentSymbols")return Eh(e);if(e.type==="workspaceSymbol")return Oh(e);if(e.type==="diagnostic")return vh(e);let t=await kw(e,je);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return uh(e,a)}let n=e.workspaceRoot??await vN(t.value.uri);await ON(t.value.uri,n)||Ft(t.value.uri,e.type);let o=await kN(n,t.value.uri);o||Ft(t.value.uri,e.type),Vw.has(e.type)&&await Kw(o,t.value,n);let i=o.getReadiness?.(),s=await Yw(e,t.value,o);return Tw(s,i)}var Kl=f(()=>{"use strict";Xe();Dn();Lt();Ew();Ul();Xw();Vs();fT();Ws()});var Lh,_h=f(()=>{"use strict";me();Lh={hasTool(e){return Yd(e)},getDescription(e){return Vd[e]??""},getToolName(e){return v[e]??String(e)}}});function LN(e,t){return t.getToolName(e)}function It(e,t,n){let r=LN(t,e);return{...n,name:r,description:Fh(r,e)}}function _N(e=Lh){let t=It(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Yi,inputSchema:Xi,executionFn:NS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=It(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:dr,inputSchema:Vi,executionFn:OS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=It(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:is,inputSchema:ss,executionFn:FP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=It(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:rs,inputSchema:os,executionFn:AP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=It(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:hr,inputSchema:ns,executionFn:yP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=It(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:_s,inputSchema:Fs,executionFn:ww,security:"remote",requiresServerRuntime:!0}}),a=It(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:fo,inputSchema:Wi,executionFn:rS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=It(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:on,inputSchema:ms,executionFn:Ex,security:"basic"}}),l=It(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Pr,inputSchema:Ps,executionFn:Mx,security:"basic"}}),u=It(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:yr,inputSchema:ls,executionFn:sx,security:"basic"}}),d=It(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:gr,inputSchema:cs,executionFn:nx,security:"basic"}}),m={name:je,description:Fh(je,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:ko,inputSchema:Oo,executionFn:Ah,security:"basic",requiresServerRuntime:!0}},p={name:Bn,description:Fh(Bn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:ws,inputSchema:Qn,executionFn:gT,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},h=[t,n,r,o,i,s,a,c,l,u,d,m,...Ls()?[p]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,OQL_SEARCH:p,ALL_TOOLS:h}}var Fh,it,h9,g9,y9,b9,R9,S9,P9,x9,C9,w9,T9,E9,k9,hT,Ih=f(()=>{"use strict";Gf();sm();dm();hm();Tm();_m();Im();sh();jm();Um();ff();bf();Kl();Mh();Lt();To();_h();Fh=(e,t=Lh)=>t.getDescription(e);it=_N(),h9=it.GITHUB_SEARCH_CODE,g9=it.GITHUB_FETCH_CONTENT,y9=it.GITHUB_VIEW_REPO_STRUCTURE,b9=it.GITHUB_SEARCH_REPOSITORIES,R9=it.GITHUB_SEARCH_PULL_REQUESTS,S9=it.PACKAGE_SEARCH,P9=it.GITHUB_CLONE_REPO,x9=it.LOCAL_RIPGREP,C9=it.LOCAL_VIEW_STRUCTURE,w9=it.LOCAL_FIND_FILES,T9=it.LOCAL_FETCH_CONTENT,E9=it.LSP_GET_SEMANTIC_CONTENT,k9=it.OQL_SEARCH,hT=it.ALL_TOOLS});import{ContentSanitizer as FN}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as IN}from"@octocodeai/config";function Nh(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:vt(t.structuredContent)}}catch{}return DN(t)?NN(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}=FN.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function DN(e){return IN()==="mcp"&&process.env[MN]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function NN(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:GN(e.structuredContent)},...t]}}function GN(e){let t=["structuredContent available"];if(Dh(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=HN(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Dh(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function HN(e){let t=0,n=0;for(let r of e)Dh(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Dh(e){return typeof e=="object"&&e!==null}function Gh(e,t){let n=jN(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
46
|
+
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:QN,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Nh(r)}catch{return r}}function jN(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:BN(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 BN(e){try{return JSON.stringify(e)}catch{return}}var MN,QN,Hh=f(()=>{"use strict";so();MN="OCTOCODE_MCP_FULL_TEXT";QN="TOOL_CALLBACK_EXCEPTION"});import{getConfigSync as zN}from"@octocodeai/config";function $N(e){let t=e;return n=>t(n)}function qN(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:$N(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function VN(e){return WN.find(t=>t.name===e)}async function Qh(e,t){let n=VN(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=KN(n,t);return await YN(n),XN(n),await JN(n,r)}catch(r){return Gh(n.name,r)}}function KN(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function YN(e){e.requiresServerRuntime&&(Yl||(Yl=UN().catch(t=>{throw Yl=null,t})),await Yl),e.requiresProviders&&(Xl||(Xl=MR().then(()=>{}).catch(t=>{throw Xl=null,t})),await Xl)}function XN(e){if(!e.isLocal&&!e.isClone)return;let t=zN();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 JN(e,t){try{let n=e.security==="remote"?await ZN(e,t):await eG(e,t);return Nh(n)}catch(n){return Gh(e.name,n)}}async function ZN(e,t){return Og(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function eG(e,t){return vg(e.execute,e.name)(t)}var Yl,Xl,UN,WN,yT=f(()=>{"use strict";$r();Ac();Ih();Hh();Iu();zf();Yl=null,Xl=null,UN=$y;WN=hT.map(qN)});var jh=f(()=>{"use strict";zf();yT()});function ke(e,t){return Qh(e,{queries:[{...tG,...t}]})}function qn(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function Io(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ys(e){return typeof e=="string"?e:void 0}var tG,un=f(()=>{"use strict";jh();tG={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function dn(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var Jl=f(()=>{"use strict"});function Bh(e){return dn(e)}function nG(e){if(e)return dn({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function Mo(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges,c=i;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...c.kind!==void 0?{matchKind:c.kind}:{},...c.scoreHint!==void 0?{scoreHint:c.scoreHint}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:zh(nG(e.pagination),n.length)}}function zh(e,t,n=!1){if(e)return e.totalItemsKind!=="files"&&!n?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function Xs(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:Bh(e.pagination)}}function bT(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:Bh(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=oG(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:Bh(e.pagination)}}function oG(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=rG[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function RT(e,t,n,r="standard"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var rG,Wn=f(()=>{"use strict";Jl();rG={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});function ST(e){return JSON.stringify(e)}function Uh(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${ST(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${ST(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Uh(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=Uh(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function PT(e){return["rule:",...Uh(e,1)].join(`
|
|
47
|
+
`)}var xT=f(()=>{"use strict"});function CT(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function wT(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return CT(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),CT(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=PT(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function pn(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return wT(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=wT(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var Js=f(()=>{"use strict";xT()});var Zl=f(()=>{"use strict";mf()});function TT(e,t,n){let r=e.where,o=r?vl(r):[],i=r&&iG.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>x("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function sG(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function Zs(e,t={}){if(!e.where)return{ok:!1,diagnostics:[x("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=sG(e.where);if(n){let m=ET(e,t);if(m.length>0)return{ok:!1,diagnostics:m};let{owner:p,repo:h}=Af(e.from),g=e.params??{},y=typeof g.extension=="string"||typeof n.extension=="string"?{}:Ss(wo(e.scope)),b=Lf(e),S=Qe(e.scope);return TT(e,{...p?{owner:p}:{},...h?{repo:h}:{},...y,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...b?{limit:b}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=pn(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[x("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=ET(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[x("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Af(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Ss(wo(e.scope)),u=Lf(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return TT(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...Qe(e.scope)?{path:Qe(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function ET(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var iG,$h=f(()=>{"use strict";Js();ne();Zl();jn();iG=new Set(["text","regex","structural","field"])});function qh(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function Or(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function Wh(e){return e.structuredContent?.results?.[0]?.status}function kT(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function Vh(...e){return e.map(kT).filter(Boolean).join("/")}function OT(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function Kh(e){return kT(e).split("/").filter(Boolean).length}function aG(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function cG(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function lG(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uG(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(lG).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function vT(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(aG).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!uG(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(cG(o.path)))}function Yh(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function AT(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function LT(e){return typeof e=="string"?[]:e.matches??[]}function De(e){return e.from??{kind:"github"}}function _T(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}var Xh=f(()=>{"use strict"});function dG(e,t){return e>0?[]:[x("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function Do(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function pG(e){if(Wh(e)==="error"){let r=Or(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:Do(o.status),retryAfterSeconds:Do(o.retryAfter),rateLimitRemaining:Do(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:Do(n.status),retryAfterSeconds:Do(n.retryAfterSeconds),rateLimitRemaining:Do(n.rateLimitRemaining)}}function mG(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return x("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?x("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):x("invalidQuery",e.message,{backend:t})}function fG(e,t){let n=pG(e);return n?[mG(n,t)]:Wh(e)==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function ea(e,t,n){let r=fG(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...dG(t,n)]}var FT=f(()=>{"use strict";ne();Xh()});async function IT(e){let t=Zs(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await ke("ghSearchCode",t.query),r=Or(n),o=new Set,i=[];for(let a of r?.files??[]){let c=Yh(a);o.has(c)||(o.add(c),i.push({kind:"file",source:De(e),path:c,entryType:"file"}))}let s=dn(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...ea(n,i.length,"ghSearchCode"),...i.length>0?[x("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:De(e)}]}}async function MT(e){let t=Zs(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await ke("ghSearchCode",t.query),r=Or(n),o=[];for(let s of r?.files??[]){let a=Yh(s),c=AT(s),l=LT(s);if(l.length===0){o.push({kind:"code",source:De(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:De(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=zh(dn(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...ea(n,o.length,"ghSearchCode"),...o.length>0?[x("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:De(e)}]}}async function DT(e){let{owner:t,repo:n}=qh(De(e)),r=e.fetch?.content,o=r?.contentView??"standard",i=_T(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Qe(e.scope)??"",type:"file",minify:o,...De(e).kind==="github"&&De(e).ref?{branch:De(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await ke("ghGetFileContent",s),c=Or(a),l=o,u=c?.pagination,d=c?.results??c?.files??[],m=d.map(h=>{let g=h.pagination??u,y=typeof g?.charOffset=="number",b={...h.startLine!==void 0?{startLine:h.startLine}:{},...h.endLine!==void 0?{endLine:h.endLine}:{},...y?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:De(e),path:h.path,content:h.content,contentView:l,...Object.keys(b).length?{range:b}:{}}}),p=u??d.find(h=>h.pagination)?.pagination;return{results:m,...p?.hasMore!==void 0?{pagination:{hasMore:!!p.hasMore,...p.currentPage!==void 0?{currentPage:p.currentPage}:{},...p.totalPages!==void 0?{totalPages:p.totalPages}:{},...p.charLength!==void 0?{itemsPerPage:p.charLength}:{},...p.totalChars!==void 0?{totalItems:p.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...ea(a,m.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:De(e)}]}}async function NT(e){let{owner:t,repo:n}=qh(De(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Qe(e.scope)??"",...De(e).kind==="github"&&De(e).ref?{branch:De(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await ke("ghViewRepoStructure",r),i=Or(o),s=[],a=Qe(e.scope);for(let u of OT(i?.structure)){let d=u.dir??".";for(let m of u.folders??[]){let p=Vh(a,d,m);s.push({kind:"tree",source:De(e),path:p,entryType:"directory",depth:Kh(p)})}for(let m of u.files??[]){let p=Vh(a,d,m);s.push({kind:"tree",source:De(e),path:p,entryType:"file",depth:Kh(p)})}}let c=vT(s,e),l=dn(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...ea(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:De(e)}]}}var GT=f(()=>{"use strict";un();Jl();Wn();ne();$h();jn();FT();Xh()});async function HT(e){switch(e.target){case"content":return DT(e);case"structure":return NT(e);case"files":return IT(e);default:return MT(e)}}var QT=f(()=>{"use strict";GT()});function No(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Jh=f(()=>{"use strict"});function vr(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function BT(e){return hG.test(e)}function zT(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function Ar(e,t,n){if(n){e.langType=n;return}let r=Pl(wo(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=zT(e.include,r.include))}function gG(e){return xl(wo(e))}function jT(e){let t=No(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function Go(e){return!!(e?.include?.length||e?.exclude?.length)}function ta(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(jT).filter(i=>!!i);n.length>0&&!e.names&&(e.names=zT(e.names,n));let r=(t?.include??[]).filter(i=>!jT(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=gG(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function UT(e,t){if(Go(t.scope)){tu(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function tu(e){e.limit=eu,e.itemsPerPage=eu}function $T(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function nu(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}var eu,hG,Lr=f(()=>{"use strict";ce();Zl();jn();Jh();eu=1e4;hG=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});function qT(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?Zh(e.predicate):!1}function yG(e){return e.kind==="text"||e.kind==="regex"}function ru(e){return e?.kind==="not"&&yG(e.predicate)}function Zh(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}function eg(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?eg(e.predicate):!1}function ou(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(x("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(na(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(na(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(na(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(x("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(na(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(na(i));break}r&&n.push(x("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function na(e){return x("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function $t(e,t){let n=[];e.status==="error"?n.push(x("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(x(bG(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function bG(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function qt(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var Ho=f(()=>{"use strict";ne()});import tg from"node:path";async function VT(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Tl(r);return{...bT(o,t),diagnostics:$t(o,"localViewStructure"),provenance:[qt("localViewStructure",t,void 0)]}}async function KT(e,t,n){let r=e.fetch?.content,o=r?.contentView??"standard",i=RG(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await pl(s);return{...RT(a,t,n,o),diagnostics:$t(a,"localGetFileContent"),provenance:[qt("localGetFileContent",t,void 0)]}}function RG(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function ra(e,t,n){if(!Go(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>SG(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function SG(e,t,n){let r=No(PG(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>WT(r,i))?!1:!(n?.exclude??[]).some(i=>WT(r,i))}function PG(e,t){let n=tg.relative(t,e);return!n||n.startsWith("..")||tg.isAbsolute(n)?e:n}function WT(e,t){let n=No(t),r=No(e),o=xG(n);return o.test(r)?!0:n.includes("/")?!1:o.test(tg.posix.basename(r))}function xG(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=CG(r)}return new RegExp(`${t}$`)}function CG(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}var iu=f(()=>{"use strict";xs();as();Wn();Lr();Ho();Jh()});function su(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}function oa(e){let t=new Map;for(let n of e)t.set(n.path,su(t.get(n.path),n));return t}function YT(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,su(o,i))}return n}function XT(e,t){return new Set([...e].filter(n=>t.has(n)))}var ia=f(()=>{"use strict"});async function ng(e,t,n,r){let o={path:n,entryType:"f"};ta(o,e.scope),Go(e.scope)&&(tu(o),o.page=1);let i=await br(o),s=ra(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),oa(Xs({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function JT(e,t,n,r,o,i){let s={path:r,details:!0};ta(s,e.scope),ou(t,s,i),Go(e.scope)&&(tu(s),s.page=1);let a=await br(s),c=ra(a,e,r);return o.push({backend:"localFindFiles",source:e.from}),oa(Xs(c,n).results)}var ZT=f(()=>{"use strict";So();Wn();Lr();Ho();iu();ia()});async function eE(e,t,n,r,o,i){let s=pn(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:eu,...vr(e.scope)};Ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await Rt(c);return o.push({backend:"localSearchCode",source:e.from}),oa((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}async function tE(e,t,n,r){let o=await Rt(rE(e,n,r.predicate)),i=$t(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[qt("localSearchCode",t,r)]}}async function nE(e,t,n,r){let o=await Rt(rE(e,n,r.predicate));return{...Mo(o,t),diagnostics:$t(o,"localSearchCode"),provenance:[qt("localSearchCode",t,r)]}}function rE(e,t,n){let o=pn(n).match,i={path:t,filesWithoutMatch:!0,...vr(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...nu(e)};return Ar(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}var au=f(()=>{"use strict";Sr();Js();Wn();ne();Lr();Ho();ia()});async function oE(e,t,n,r){let o=[],i=[],a=[...(await cu(e,r,t,n,o,i)).values()].sort(wG(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(x("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function wG(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function cu(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>cu(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:YT(a,c));case"any":{let s=await Promise.all(t.of.map(c=>cu(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,su(a.get(l),u));return a}case"not":{let s=await ng(e,n,r,o),a=await cu(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return iE(e,t,n,r,o,i)}}async function iE(e,t,n,r,o,i){return t.kind==="field"?JT(e,t,n,r,o,i):eE(e,t,n,r,o,i)}async function sE(e,t,n){return new Set((await ng(e,e.from,t,n)).keys())}async function aE(e,t,n,r,o){return new Set((await iE(e,t,e.from,n,r,o)).keys())}var rg=f(()=>{"use strict";ne();ZT();au();ia()});async function cE(e,t,n,r){let o=[],i=[],s=await lu(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(x("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function lu(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>lu(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:XT(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>lu(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await sE(e,r,o),a=await lu(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await aE(e,t,r,o,i),rows:[]};default:{let s=await TG(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function TG(e,t,n,r,o,i){let s=pn(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...vr(e.scope)};Ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await Rt(c);return o.push({backend:"localSearchCode",source:n}),Mo(l,n).results}var lE=f(()=>{"use strict";Sr();Js();Wn();ne();Lr();rg();ia()});async function uu(e,t,n){let r=e.where;if(qT(r))return cE(e,t,n,r);if(e.view==="discovery"&&ru(r))return nE(e,t,n,r);let o=pn(r);if(o.unsupported)return{results:[],diagnostics:[x(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...vr(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...nu(e)};Ar(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await Rt(s),c=Mo(a,t),l=$t(a,"localSearchCode"),u=EG(a);if(u.length>0){let d=u.reduce((p,h)=>p+(h.total??0),0),m=u.reduce((p,h)=>p+h.shown,0);l.push(x("matchTruncated",`${u.length} file(s) have more matches (showed ${m} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(x("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&BT(i.keywords)&&l.push(x("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[qt("localSearchCode",t,r)]}}function EG(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}var og=f(()=>{"use strict";Sr();Js();Wn();ne();Lr();Ho();lE();au()});async function uE(e,t,n){let r=e.where;if(ru(r))return tE(e,t,n,r);if(r&&Zh(r))return oE(e,t,n,r);if(r&&eg(r)){let l=await uu({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};ta(o,e.scope),UT(o,e),$T(o,e);let i=[];r&&ou(r,o,i);let s=await br(o),a=ra(s,e,n);return{...Xs(a,t),diagnostics:[...i,...$t(a,"localFindFiles")],provenance:[qt("localFindFiles",t,r)]}}var dE=f(()=>{"use strict";So();Wn();Lr();Ho();og();rg();au();iu()});import kG from"node:fs";import OG from"node:path";function vG(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}async function sa(e){let t=e.from,n=vG(e),r=Qe(e.scope),o=r?OG.join(n,r):n;if(!kG.existsSync(o))return{results:[],diagnostics:[x("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return uE(e,t,o);case"structure":return VT(e,t,o);case"content":return KT(e,t,o);default:return uu(e,t,o)}}var ig=f(()=>{"use strict";ne();og();dE();iu();jn()});import pE from"node:path";function mE(e){return[...new Set(e)]}function hE(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function gE(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!pE.isAbsolute(r.localPath)?pE.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function yE(e){if(e.from?.kind!=="github")return sa(e);let t=e.from,{owner:n,repo:r}=hE(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Qe(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await ke("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=gE(s);if(u==="error"||!a)return{results:[],diagnostics:[x("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},m={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:mE([...d.excludeDir??[],".git"]),exclude:mE([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},p=await sa(m);return{...p,diagnostics:[...p.diagnostics,...c?[x("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...p.provenance]}}async function bE(e){if(e.from?.kind==="materialized"){let p=e.from.localPath;return{results:[fE(p,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[x("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=hE(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:Qe(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await ke("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=gE(a);if(d==="error"||!c)return{results:[],diagnostics:[x("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let m=!i;return{results:[fE(c,t,t.ref,m,l)],diagnostics:l?[x("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function fE(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var RE=f(()=>{"use strict";un();ig();ne();jn()});import sg from"node:path";function du(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{byVerdict:t,facts:n,edges:r}}function aa(e){let t=e.root,n=[...e.symbols.map(a=>AG(t,a)),...e.files.map(a=>IG(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>MG(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let{byVerdict:o,facts:i,edges:s}=du(n);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function AG(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=LG(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:t.retentionSource==="ast"?"imports":"references",source:t.retentionSource==="ast"?"ast":"ripgrep",confidence:t.retentionSource==="ast"?"exact":"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:_G(r),next:FG(e,t)}}function LG(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function _G(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via AST import/call retention (or lexical fallback); likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable retainers found in analyze (AST import/call scan, then lexical fallback). Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only retained from unreachable code (AST or lexical scan). Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function FG(e,t){let n=sg.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"none"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function IG(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:sg.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:sg.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function MG(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var SE=f(()=>{"use strict"});var pu=f(()=>{"use strict";SE()});function PE(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function ag(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:PE(e.relation),verdicts:PE(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function DG(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function _r(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function ca(e,t){if(!DG(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>_r(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>_r(i.relation,t)),o=e.why.some(i=>_r(i.claim,t));return n||r||o}function mu(e,t){e.set(t.id,t)}function xE(e,t,n){_r(t.claim,n)&&e.set(t.id,t)}function la(e,t,n,r){_r(n.relation,r)&&(mu(e,n.from),mu(e,n.to),t.set(n.id,n))}function CE(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}var fu=f(()=>{"use strict"});import wE from"node:path";function ua(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function EE(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=GG(a.relation);if(!_r(c,i))continue;let l=TE(a.from,e,a.line),u=TE(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||la(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function GG(e){let t=e.trim();return NG.has(t)?t:"references"}function TE(e,t,n){let r=HG(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function HG(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:wE.isAbsolute(o)?wE.relative(t,o):o,name:i}}var NG,cg=f(()=>{"use strict";fu();NG=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});function Fr(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??QG),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function kE(e,t,n,r,o,i){let s=t.filter(g=>ca(g,r)),a=Fr(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,m=new Map,p={},h={};for(let g of s)p[g.verdict]=(p[g.verdict]??0)+1,h[g.proofStatus]=(h[g.proofStatus]??0)+1;for(let g of c){if(mu(l,g.subject),r.includeFacts)for(let y of g.why)xE(d,y,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let y of g.retainedBy)la(l,u,y,r);if(r.direction!=="incoming")for(let y of g.retains??[])la(l,u,y,r)}for(let y of g.missingProof)m.set(CE(y),y)}return r.includeEdges&&EE(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:m.size,byVerdict:p,proofStatus:h},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...m.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function OE(e){let{byVerdict:t,facts:n,edges:r}=du(e);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}var QG,da=f(()=>{"use strict";pu();fu();cg();fu();cg();QG=25});function hu(e){if(!e)return[];for(let t of vE){let n=e[t];if(Array.isArray(n))return n}return[e]}function AE(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function LE(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))jG.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function lg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qo(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function BG(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??Qo(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:Qo(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??Qo(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??Qo(t);case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:Qo(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return Qo(t)}function Vn(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=BG(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}var vE,jG,pa=f(()=>{"use strict";vE=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],jG=new Set([...vE,"pagination","contentPagination","next"])});import{statSync as zG}from"node:fs";import gu from"node:path";function yu(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function _E(e,t){if(!t||gu.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?gu.join(n.base,t):t}function ma(e){try{let t=gu.isAbsolute(e)?e:gu.resolve(e);return zG(t).isDirectory()}catch{return!1}}function Kn(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function xt(e){return e.params??{}}function fa(e,t){let n={...xt(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}var Yn=f(()=>{"use strict"});function bu(e){return e==="plan"||e==="prove"?e:"analyze"}function UG(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;FE.includes(o)&&t.add(o)}return t.size>0?t:void 0}function IE(e,t){let n=UG(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of FE){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:m,pagination:p}=Fr(e,u.length);o[l]=u.slice(d,m),o[`${l}Page`]=p,s=p.itemsPerPage,a=Math.max(a,p.totalPages??1),p.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function ME(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function ug(e,t){let{status:n,data:r}=qn(e);return n==="error"?[x("invalidQuery",yu(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function Ir(e,t,n,r){let{data:o,status:i}=qn(e),s=ug(e,n),a=i==="error"?[]:hu(o);a.length===0&&!s.some(m=>m.code==="zeroMatches"||m.severity==="error")&&s.push(x("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=dn(c,l),d=t==="package"?AE(o):void 0;return{results:Vn(a,t,r,LE(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function dg(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function DE(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:dg(n,t)}}var FE,Mr=f(()=>{"use strict";ne();un();Jl();da();pa();Yn();FE=["manifests","files","dependencies","symbols","graphFacts"]});function $G(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}async function NE(e){let{owner:t}=Kn(e.from),n=fa(e,"limit"),r=typeof n.language=="string"?n.language:$G(e),o=Cl(r);o&&(n.language=o);let i=await ke("ghSearchRepos",{...t?{owner:t}:{},...n}),s=Ir(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&qG(n)&&s.diagnostics.push(x("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function qG(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function GE(e){let t=await ke("npmSearch",{...fa(e)});return Ir(t,"package","npmSearch",e.from??{kind:"npm"})}var HE=f(()=>{"use strict";un();ne();Zl();Mr();Yn()});async function pg(e){let{owner:t,repo:n}=Kn(e.from),r=e.target==="commits",o=r?void 0:VG(e),i=r?WG(e):void 0,s=fa(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await ke("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=Ir(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?jE(c,o):i?QE(c,i):c}function WG(e){let t=xt(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function QE(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),m=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,m)+(m<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function VG(e){let t=xt(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function KG(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
|
|
48
|
+
`)}function jE(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=KG(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}var BE=f(()=>{"use strict";un();ne();Mr();Yn()});function jo(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var Ru=f(()=>{"use strict"});import Su from"node:path";function zE(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}async function $E(e){let t=xt(e),{owner:n,repo:r}=Kn(e.from),o=jo(t);if(o.kind==="prPatch"){let i=await ke("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return Ir(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?YG(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):XG(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function YG(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[x("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=p=>({results:[],diagnostics:[x("invalidQuery",p,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=ma(r)?r:Su.dirname(r),s=Su.isAbsolute(t.path)?Su.relative(i,t.path):t.path;if(!s||s.startsWith("..")||s.startsWith("-"))return o(`params.path must resolve inside from.path for a local ref diff (got "${t.path}").`);if(!UE.test(t.baseRef)||!UE.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(Su.sep).join("/")}`,c=p=>tn("git",["-C",i,"show",`${p}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let p=l.success?u:l,h=l.success?t.headRef:t.baseRef;return o(`git show ${h}:${a} failed: ${p.stderr.trim().split(`
|
|
49
|
+
`)[0]||p.error?.message||`exit ${p.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=mg(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[x("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function XG(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[x("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=m=>ke("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:m,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=zE(i),c=zE(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(m=>m.status==="error"||typeof m.content!="string");if(l){let m=yu(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[x("invalidQuery",m,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=mg(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[x("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function mg(e,t){let n=e===""?[]:e.split(`
|
|
50
50
|
`),r=t===""?[]:t.split(`
|
|
51
51
|
`),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let p=o-1;p>=0;p--)for(let h=i-1;h>=0;h--)s[p][h]=n[p]===r[h]?s[p+1][h+1]+1:Math.max(s[p+1][h],s[p][h+1]);let a=[],c=0,l=0,u=0,d=0,m=0;for(;d<o&&m<i;)n[d]===r[m]?(a.push(` ${n[d]}`),u++,d++,m++):s[d+1][m]>=s[d][m+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[m]}`),c++,m++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;m<i;)a.push(`+ ${r[m++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
|
|
52
|
-
`)}}var BE,UE=f(()=>{"use strict";un();ne();Ru();po();Mr();Yn();BE=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/});import Be from"node:path";function XG(e,t,n){let r=t??n??".";if(!e)return r;if(Be.isAbsolute(e))return e;if(n&&Be.isAbsolute(n))return Be.resolve(n,e);if(t&&Be.isAbsolute(t)){let o=pa(t)?t:Be.dirname(t);return Be.resolve(o,e)}return e}function $E(){return x("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function JG(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(x("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(x("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push($E()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push($E());let i=e?.pagination;return i?.hasMore&&n.push(x("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:dg(i,t)})),n}async function qE(e){let t,n,r=[],o=[],i=xt(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let E=e.from.path,_=pa(E);n=c??(_?Be.resolve(E):void 0),t=a??(_?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=Qe(e.scope),_=E?Be.isAbsolute(E)?E:Be.join(e.from.localPath,E):void 0;s?(n=c??e.from.localPath,t=a??_):t=a??_??e.from.localPath}else if(e.from?.kind==="github"){let{owner:E,repo:_}=Kn(e.from);if(!E||!_)return o.push(x("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,G=Qe(e.scope),M=w&&!Be.isAbsolute(w)?w:G,A=await ke("ghCloneRepo",{owner:E,repo:_,...e.from.ref?{branch:e.from.ref}:{},...M?{sparsePath:M}:{}}),W=qn(A).data,H=AE(A,W?.localPath);if(!H)return o.push(x("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:H}),s?(n=c??H,w?t=Be.isAbsolute(w)?w:Be.join(H,w):G&&(t=Be.isAbsolute(G)?G:Be.join(H,G))):w?t=Be.isAbsolute(w)?w:Be.join(H,w):G?t=Be.isAbsolute(G)?G:Be.join(H,G):t=H}if(!t&&!n)return o.push(x("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...m}=i,p=await ke("lspGetSemantics",{...m,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:h,status:g}=qn(p),y=h,b=IE(y,e),S=XG(Ks(y?.uri),t,n),C=tH(e,S),k=eH(ZG(y),u);return{results:g==="error"?[]:Vn(k,"semantics",C),...b?{pagination:b}:{},diagnostics:[...o,...ug(p,"lspGetSemantics"),...JG(y,e)],provenance:[...r,{backend:"lspGetSemantics",source:C}]}}function ZG(e){if(!e)return[];let n=(lg(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=Ks(e.uri);return n.map(o=>lg(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return hu(e)}function eH(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function tH(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}var WE=f(()=>{"use strict";un();ne();jn();da();Mr();Yn()});import{builtinModules as nH}from"node:module";var fg,VE,KE,YE,fa=f(()=>{"use strict";fg=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],VE="package.json",KE=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),YE=new Set(nH.flatMap(e=>[e,`node:${e}`]))});import Pu from"node:path";function xu(){if(ha)return ha;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());ha=new Set(e.length>0?e:fg)}catch{ha=new Set(fg)}return ha}function XE(){if(ga)return ga;try{let e=JSON.parse(D.getGraphFactCapabilities());ga=Array.isArray(e)?e.filter(rH):[]}catch{ga=[]}return ga}function rH(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function hg(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function Cu(e,t,n){return wu(Pu.resolve(e,t),n)}function wu(e,t){let n=xu(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(Pu.join(e,`index${o}`));return r.find(o=>t.has(o))}function ya(e){return e.startsWith("./")||e.startsWith("../")}function JE(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function ZE(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function gg(e){return typeof e=="string"&&e.trim()?e:void 0}function Tu(e){return typeof e=="string"&&e.length>0}function ek(e){return typeof e=="string"}function tk(e){return[...new Set(e)]}function Wt(e,t){return Pu.relative(e,t)||Pu.basename(t)}function nk(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function rk(e,t){return!!(e===t||e.endsWith(`.${t}`)||e.endsWith(`::${t}`))}var ha,ga,ba=f(()=>{"use strict";Le();fa()});import mn from"node:path";import{readFile as oH,readdir as iH}from"node:fs/promises";async function ok(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await iH(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(KE.has(s.name))continue;await r(mn.join(o,s.name));continue}s.isFile()&&n.push(mn.join(o,s.name))}}return await r(e),n}async function ik(e){return(await Promise.all(e.map(async n=>sH(n)))).filter(n=>n!==null)}async function sH(e){let t=await aH(e);if(!t)return null;let n=mn.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=ZE(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:gg(t.name),deps:r,entrypoints:cH(n,t)}}async function aH(e){try{let t=JSON.parse(await oH(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function cH(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=gg(t[o]);i&&n.add(mn.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(mn.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(mn.resolve(e,o));sk(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(mn.resolve(e,o));return[...n]}function sk(e,t,n){if(typeof t=="string"){n.add(mn.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))sk(e,r,n)}function ak(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=lH(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:Wt(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:Wt(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:Wt(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function lH(e,t){return t.filter(r=>e.startsWith(`${r.dir}${mn.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}var ck=f(()=>{"use strict";fa();ba()});import jo from"node:path";import{readFile as uH}from"node:fs/promises";async function lk(e,t){let n=xu(),r=t.filter(i=>n.has(jo.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await uH(i,"utf8").catch(()=>""),a=jo.extname(i).toLowerCase(),c=dH(s,i,Wt(e,i)),l=tk(c?c.imports.map(u=>u.specifier):pH(s));return{path:i,rel:Wt(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!ya(u)).map(JE).filter(Tu).filter(u=>!YE.has(u)),...c?{graphFacts:c}:{}}}))}function dH(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??jo.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(ek):[]}}catch{return}}function yg(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...xu()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=hg(e,l=>l.language),s=hg(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function pH(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function uk(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,jo.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??jo.dirname(o.path);for(let a of o.imports){if(!ya(a))continue;let c=Cu(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function dk(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=wu(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","lib.rs","main.rs","mod.rs"]){let s=wu(jo.resolve(e,i),r);s&&o.add(s)}return[...o]}function pk(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}var mk=f(()=>{"use strict";Le();fa();ba()});import mH from"node:path";import{readFile as fk}from"node:fs/promises";async function hk(e){return(await Promise.all(e.map(async n=>{let r=fH(n);if(r.length>0)return r;let o=await fk(n.path,"utf8").catch(()=>"");return hH(n.rel,o)}))).flat()}function fH(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function hH(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:nk(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function gk(e,t,n){let r=new Map(t.map(a=>[a.rel,a])),o=new Map(t.map(a=>[a.path,a])),i=new Set(t.map(a=>a.path)),s=gH(t);return e.map(a=>{let c=r.get(a.file),l=yH(a,t,c,s,i,o),u=l.length>0?"ast":"ripgrep",d=l.length>0?l:t.filter(g=>g.rel!==a.file&&bH(g.path,a.symbol)).map(g=>g.rel),m=d.filter(g=>{let y=r.get(g);return y?n.has(y.path):!1}),p=c?n.has(c.path):!1,h=m.length>0?"reachable":d.length>0?"transitive-dead":p?"candidate-unused-export":"unused-export";return{symbol:a.symbol,kind:a.kind,file:a.file,line:a.line,evidenceSource:a.evidenceSource,retentionSource:u,directRefs:d.length,externalRefs:m.length,retainedBy:d,verdict:h}})}function gH(e){let t=new Map;for(let n of e){let r=n.graphFacts;if(r){for(let o of r.declarations){if(!o.exported)continue;let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}for(let o of r.exports){let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}}}return t}function yH(e,t,n,r,o,i){let s=r.get(e.symbol)??(n?new Set([n.path]):new Set),a=new Set;for(let c of t){if(c.rel===e.file)continue;let l=c.graphFacts;if(l){for(let u of l.imports){let d=u.importedName&&u.importedName!=="default"?u.importedName:void 0,m=u.localName;if(!(d===e.symbol||m===e.symbol)||!ya(u.specifier))continue;let h=Cu(mH.dirname(c.path),u.specifier,o);if(h&&s.has(h)){a.add(c.rel);break}}if(!a.has(c.rel)){for(let u of l.calls)if(rk(u.callee,e.symbol)){a.add(c.rel);break}}}}return[...a].sort()}function bH(e,t){return bg.get(e)?.has(t)??!1}async function yk(e){bg.clear(),await Promise.all(e.map(async t=>{let n=await fk(t.path,"utf8").catch(()=>"");bg.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}var bg,bk=f(()=>{"use strict";ba();bg=new Map});import RH from"node:path";async function Eu(e){let t=RH.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=SH(r,e.intent,e.facets),i=PH(o,e.facets),s=xH(o,i),a=XE();if(n==="plan")return CH({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:yg([],[],a)});let c=await ok(t,e.maxFiles??5e3),l=await ik(c.filter(w=>w.endsWith(VE))),u=await lk(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),m=yg(u,d,a);await yk(u);let p=new Set(l.map(w=>w.name).filter(Tu)),h=uk(u),g=dk(t,l,u),y=pk(g,h),b=u.filter(w=>!y.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=ak(t,l,u,p),C=await hk(u),k=gk(C,u,y),E=k.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,_=k.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:y.size,unusedFiles:b.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:k.length,candidateUnusedExports:E,transitiveDeadExports:_,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,G)=>w+G.declarations.length,0),nativeGraphCalls:d.reduce((w,G)=>w+G.calls.length,0)},manifests:l.map(w=>({manifest:Wt(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(G=>Wt(t,G)),dependencyCount:[...w.deps.keys()].length})),files:b,dependencies:S,symbols:k,graphFacts:d,graphCapabilities:m,caveats:["Analyze uses native AST graph facts for inventory and preferred cross-file retention (named imports / call callees). Lexical token scan is fallback only when AST finds no retainers.",'Graph facts are syntax inventory, not semantic identity. Upgrade candidates with target:graph proof:"lsp" (or lspGetSemantics references/callers) before destructive cleanup.',"Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function SH(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function PH(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function xH(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["extractGraphFacts","export regex fallback"],produces:["symbols","lineHints"],evidence:"heuristic"},{id:"reference-scan",purpose:"Candidate cross-file retention from native AST imports/calls (preferred) with lexical token fallback. Upgrade via target:graph proof:lsp \u2014 analyze does not run LSP.",tools:["extractGraphFacts","token scan fallback"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"heuristic"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function CH(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}var Rg=f(()=>{"use strict";ck();mk();bk();fa();ba()});async function Rk(e){let t=xt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=bu(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await Eu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[x("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:sa(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?Fr(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?_E(e,i):{fields:{}},m={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:la(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},p=FE(l?.pagination,d.pagination);return{results:Vn([m],"research",e.from),...p?{pagination:p}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}var Sk=f(()=>{"use strict";ne();Rg();pu();ua();Mr();da();Yn()});import ku from"node:path";function Pg(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function xk(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function Ck(e,t,n,r,o){let i=n.filter(l=>aa(l,r)),s=Fr(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await TH(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(x(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(x("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),wH(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(x("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function wH(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function TH(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=ku.isAbsolute(t.subject.uri)?t.subject.uri:ku.resolve(e,t.subject.uri);try{let i=await ke("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=EH(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=qn(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:Ks(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,m=Fo(a?.totalReferences)??Fo(u?.totalReferences)??Fo(a?.referenceCount)??Fo(u?.referenceCount)??Fo(d?.totalItems)??Pk(u)??Pk(a);return{status:"ok",...typeof m=="number"?{totalReferences:m}:{},files:kH(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function EH(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function Pk(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function kH(e,t){let n=new Set;return Sg(e,n,t),[...n].slice(0,25)}function Sg(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)Sg(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&OH(i)&&t.add(ku.isAbsolute(i)?ku.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])Sg(r[o],t,n)}function OH(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var wk=f(()=>{"use strict";un();ne();ua()});async function Tk(e){let t=xt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=bu(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await Eu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[x("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:sa(i),a=ag(t),c=s?.packets??[],l=Pg(i.mode,t)?await Ck(n,e,c,a,xk(e,t)):[],u=EE(c),d=TE(e,c,u,a,i.graphFacts,n),m=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[Pg(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],p={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:la(i.graphFacts),caveats:m};return{results:Vn([p],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var Ek=f(()=>{"use strict";ne();Rg();pu();ua();wk();Mr();da();Yn()});var kk,Ok=f(()=>{"use strict";NE();QE();UE();WE();Sk();Ek();kk={repositories:ME,packages:DE,pullRequests:pg,commits:pg,diff:zE,semantics:qE,research:Rk,graph:Tk}});function vk(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&vH.has(e.target)&&t.push(x("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "none" or "standard".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "none" or "standard".'}})),t}var vH,Ak=f(()=>{"use strict";ne();vH=new Set(["pullRequests","commits","diff"])});function Lk(e){let t={schema:Ct.schema,view:e.view??Ct.view,page:e.page??Ct.page,itemsPerPage:e.itemsPerPage??Ct.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??Ct.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??Ct.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??Ct.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?Ct.detailedCodeContext:Ct.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??Ct.localSearchSort),t}var Ct,_k=f(()=>{"use strict";Ct={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"standard",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function AH(e){return e?.mode==="auto"||e?.mode==="required"}function LH(e,t){let n=e.target==="files"?Dr:Xn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:Xn,exact:!0,reason:`${t.kind} evaluated locally by ${Xn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function _H(e,t,n){let r=AH(e.materialize);if(n)return FH(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:Dr,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:Dr,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:fn,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:Dr,exact:!0,reason:`${Ou(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:Dr,exact:!1,reason:`GitHub cannot enumerate files by ${Ou(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Ou(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:Xn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:Xn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:fn,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?xg(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:Xn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return xg(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:Dr,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:fn,exact:!0,reason:"path/name predicate pushed to provider"}:xg(e,`field "${t.field}"`,r)}}function Ou(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function FH(e,t,n){let r=Ou(t);return n?{route:"ROUTE",backend:e.target==="files"?Dr:Xn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:fn,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function xg(e,t,n){if(n)return{route:"ROUTE",backend:Xn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:fn,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function Fk(e,t,n=!1){return e.sourceKind==="github"?_H(e,t,n):LH(e,t)}var Xn,Dr,fn,Ik=f(()=>{"use strict";Xn="localSearchCode",Dr="localFindFiles",fn="ghSearchCode"});function Bo(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return Cg.find(n=>n.id===`${t}.diff.${e.variant}`)}return Cg.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function wg(e){return Cg.find(t=>t.id===e)}function Tg(e){let t=IH(e.source,e.target);if(e.target==="diff"){let n=Qo(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return Bo({sourceKind:t,target:"diff",variant:r})}return Bo({sourceKind:t,target:e.target})}function Mk(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function Dk(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function IH(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var Cg,Nk=f(()=>{"use strict";Ru();Cg=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function MH(e,t){return e.id??t}function vu(e,t,n,r,o,i=!1){let s=MH(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,m)=>vu(e,d,`${n}.of[${m}]`,r,o,i)),l=DH(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(x("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=vu(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=Fk(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(x(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&Gk(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:NH(e.target),exact:a.exact}),a.route}function DH(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function NH(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function Gk(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Au(e,t){if(!t)return;let n=Dk(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Ra(e,t,n){if(!t)return!1;for(let r of Mk(t,n))Gk(e.backendCalls,r);return!0}function Hk(e,t){return Eg(e,t,"files")}function Eg(e,t,n,r=Bo({sourceKind:"materialized",target:n})){let o=Bo({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Au(e,o),Au(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),Ra(e,o,t),Ra(e,r,void 0),!0}function Lu(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Lu):e.kind==="not"?Lu(e.predicate):!1:!1}function Qk(e){return e.target==="code"?wg(Lu(e.where)?"local.code.structural":"local.code.textRegex"):Bo({sourceKind:"materialized",target:e.target})}function jk(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?wg(Lu(e.where)?"local.code.structural":"local.code.textRegex")??Tg({source:t,target:e.target,params:e.params}):Tg({source:t,target:e.target,params:e.params})}var Bk=f(()=>{"use strict";Ik();ne();Nk()});function zk(e){return e.kind==="not"&&e.predicate.kind==="not"?zk(e.predicate.predicate):e}function Uk(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Sf[e.target]:void 0;if(n)return n.includes(t)?[]:[x("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[x("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function $k(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=zk(e.where),r=Js({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function qk(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(x("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(x("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var Wk=f(()=>{"use strict";ne();$h();Gn()});function Vk(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=jk(e,o);if(Au(n,s),e.where)vu(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(h=>h.route==="ROUTE")&&Eg(n,o,e.target,Qk(e));else if(e.target==="diff"){let h=Qo(e.params);h.kind==="prPatch"||h.kind==="directFile"?Ra(n,s,o)||n.diagnostics.push(x("unsupportedTarget",`No transformer registered for target:"diff" lane "${h.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let h=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(h?g&&Hk(n,o):Ra(n,s,o))&&(!h||g)&&n.diagnostics.push(x("unsupportedTarget",h?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(x("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...$k(e,n.nodes)),n.diagnostics.push(...Uk(e)),n.diagnostics.push(...vk(e));let a=qk(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??Ct.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(x("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=Po(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(x("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let m={input:t,normalized:e,defaults:Lk(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},p=!n.nodes.some(h=>h.route==="UNSUPPORTED")&&!n.diagnostics.some(h=>h.severity==="error"&&h.code!=="planTruncated");return{plan:m,executable:p}}var Kk=f(()=>{"use strict";Ru();Ak();ne();_k();kf();Bk();Wk()});function GH(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function Yk(e,t,n,r,o,i){let s=o&&i?HH(i):[],a=o&&i?QH(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:Ol(e.plan.diagnostics,t,n,r,GH(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function HH(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[x("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function QH(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}var Xk=f(()=>{"use strict";ne();Es()});function Jk(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):BH.has(c)?o.add(c):zH.has(c)?o.add("data"):UH.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!jH.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[x("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}var jH,BH,zH,UH,Zk=f(()=>{"use strict";ne();jH=new Set(["kind","source","recordType","id","proofGrade"]),BH=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","matchKind","scoreHint","proofGrade","size","modified","entryType","depth","children","data"]),zH=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),UH=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});function Sa(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function _u(e,t,n,r){let o=Vk(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return Yk(o,s,e.id,r,n.dryRun,e);let a=await WH(e,o);bC(e,a.results),$H(e,a),qH(a);let c=LC(e,a);SC(e,a.results);let l=Jk(e,a.results),u=_C(a.results);return Ts({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:hC(o.plan.backendCalls),plan:s})}function $H(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function qH(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}async function WH(e,t){if(e.target==="materialize")return gE(e);let n=kk[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?ia(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?hE(e):NT(e)}var kg=f(()=>{"use strict";GT();ig();yE();Ok();Es();Kk();Mf();Xk();_f();Ff();Zk()});async function eO(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await _u(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=VH(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&Sa(o.merged.results)}else for(let i of r)Sa(i.envelope.results);return o}function VH(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let m=JH(d);n.has(m)||(n.add(m),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),KH(s,u.envelope.nextHints),YH(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),XH(u.envelope)&&(l=!0)}return l&&o.push(x("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Ts({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function KH(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||If(o,r))&&(e[n]=r)}}function YH(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function XH(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function JH(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var tO=f(()=>{"use strict";ne();Es();Mf();kg()});var nO={};lO(nO,{runOqlSearch:()=>ZH});async function ZH(e,t={}){let n;try{n=pC(e)}catch(o){if(o instanceof sn)return Ol(o.diagnostics);throw o}if(xf(n))return eO(n,e,t);let r=await _u(n,e,t);return Sa(r.results),r}var rO=f(()=>{"use strict";mC();ne();Es();Gn();tO();kg()});async function fT(e){let t=eQ(e),n=Qn.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(rO(),nO)),o=await r(n.data,{authInfo:e.authInfo});return tQ(o)}function eQ(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function tQ(e){let t=nQ(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function nQ(e){return Cf(e)?{results:e.children.map(t=>oO(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:iO(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[oO(e,e.queryId??"oqlSearch-1")]}}function oO(e,t){let n=iO(e);return{id:e.queryId??t,...oQ(e),data:n}}function iO(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||rQ(d,u)){let{why:m,confidence:p,...h}=l;s[c]=h,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function rQ(e,t){return e.why===t.why&&e.confidence===t.confidence}function oQ(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var Mh=f(()=>{"use strict";Cr();Gn()});Iu();ce();st();Yo();bn();Nu();Vo();Ae();Fd();op();bd();tt();pp();dp();sc();Tp();Ni();ar();Op();Gi();rr();vp();Mp();Ap();_p();or();Dp();vc();Hp();Bp();Qp();Gp();jp();kt();so();nt();dt();$r();di();Dn();Ti();Yp();sm();am();dm();um();Uc();hm();fm();gm();ym();Sm();Tm();ul();_m();Fm();io();Im();Mm();cc();jm();ss();ml();Um();Ro();fl();ff();lf();uf();bs();ms();Sr();bf();Ps();wl();yf();Mh();Kl();Kl();_l();_l();hh();Ul();Lt();sh();Nf();rn();pr();Ih();Zd();Kd();_h();Xd();Ud();me();Wd();import{completeMetadata as iQ}from"@octocodeai/octocode-core";var Pa=null;function sO(){return Pa||(Pa=ic(iQ)),Pa}async function Voe(){return sO()}async function Koe(){sO()}function Yoe(){return Pa}function Xoe(){Pa=null}jh();wo();Me();Cr();var Zoe={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}"};Dm();Em();yo();sr();Xp();gf();import{getConfigSync as aO}from"@octocodeai/config";function nie(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function rie(){try{return aO().local.enabled}catch{return!1}}function oie(){try{if(!aO().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}vo();po();import{validateCommand as sQ}from"@octocodeai/octocode-engine/commandValidator";async function cie(e,t=[],n={}){let r=sQ(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Gc(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:l=!1}=n,u=await tn(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(u.outputLimitExceeded&&l)return{success:!0,code:u.exitCode,stdout:u.stdout,stderr:u.stderr,truncated:!0};if(u.error)throw u.error;return{success:u.success,code:u.exitCode,stdout:u.stdout,stderr:u.stderr}}po();sp();Kr();us();Bt();lt();Ml();Bs();oh();rh();js();hc();Oi();mc();Tc();Fi();import{z as B}from"zod";var Fu=B.object({text:B.string()}),aQ=B.object({match:B.object({text:B.string()}).optional(),start:B.number(),end:B.number()}),cQ=B.object({type:B.literal("match"),data:B.object({path:Fu,lines:B.object({text:B.string()}),line_number:B.number(),absolute_offset:B.number(),submatches:B.array(aQ)})}),lQ=B.object({type:B.literal("context"),data:B.object({path:Fu,lines:B.object({text:B.string()}),line_number:B.number(),absolute_offset:B.number()})}),uQ=B.object({type:B.literal("begin"),data:B.object({path:Fu})}),dQ=B.object({type:B.literal("end"),data:B.object({path:Fu,stats:B.object({elapsed:B.object({human:B.string()}),searches:B.number(),searches_with_match:B.number()}).optional()})}),pQ=B.object({type:B.literal("summary"),data:B.object({elapsed_total:B.object({human:B.string()}),stats:B.object({elapsed:B.object({human:B.string()}),searches:B.number(),searches_with_match:B.number(),bytes_searched:B.number(),bytes_printed:B.number(),matched_lines:B.number(),matches:B.number()})})}),die=B.discriminatedUnion("type",[cQ,lQ,uQ,dQ,pQ]);Xe();Hh();le();Mc();Zc();jc();lr();om();hl();Yu();Zu();sd();ad();ei();cd();import{securityRegistry as nce,ContentSanitizer as rce}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as ice}from"@octocodeai/octocode-engine/mask";import{configureSecurity as ace}from"@octocodeai/octocode-engine/withSecurityValidation";import{ENV_TOKEN_VARS as uce,getTokenFromEnv as dce,getEnvTokenSource as pce,hasEnvToken as mce,resolveEnvToken as fce}from"@octocodeai/config";import{CONFIG_SCHEMA_VERSION as bce,CONFIG_FILE_NAME as Rce,DEFAULT_CONFIG as Sce,DEFAULT_GITHUB_CONFIG as Pce,DEFAULT_LOCAL_CONFIG as xce,DEFAULT_TOOLS_CONFIG as Cce,DEFAULT_NETWORK_CONFIG as wce,DEFAULT_LSP_CONFIG as Tce,DEFAULT_OUTPUT_CONFIG as Ece,MIN_TIMEOUT as kce,MAX_TIMEOUT as Oce,MIN_RETRIES as vce,MAX_RETRIES as Ace,MIN_OUTPUT_DEFAULT_CHAR_LENGTH as Lce,MAX_OUTPUT_DEFAULT_CHAR_LENGTH as _ce,getConfigFilePath as Fce,loadConfig as Ice,loadConfigSync as Mce,configExists as Dce,validateConfig as Nce,getConfig as Gce,getConfigSync as Hce,reloadConfig as Qce,resolveConfig as jce,resolveConfigSync as Bce,invalidateConfigCache as zce,getConfigValue as Uce,_resetConfigCache as $ce,_getCacheState as qce,setRuntimeSurface as Wce,getRuntimeSurface as Vce}from"@octocodeai/config";import{completeMetadata as Zce}from"@octocodeai/octocode-core";import{z as tle}from"zod";export{SQ as ALL_ERROR_CODES,mT as ALL_TOOLS,TA as BASE_SCHEMA,qi as BulkCloneRepoLocalSchema,ko as BulkLspGetSemanticsQuerySchema,Mu as CONFIG_ERRORS,Rce as CONFIG_FILE_NAME,bce as CONFIG_SCHEMA_VERSION,Bi as CORE_ALLOWED_ENV_VARS,Xt as CREDENTIALS_FILE,Uf as CircuitOpenError,mo as CloneRepoQueryLocalSchema,rce as ContentSanitizer,NY as DEFAULTS,j6 as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,Sce as DEFAULT_CONFIG,Pce as DEFAULT_GITHUB_CONFIG,xce as DEFAULT_LOCAL_CONFIG,Tce as DEFAULT_LSP_CONFIG,Mg as DEFAULT_MATCH_SNIPPET_CHARS,wce as DEFAULT_NETWORK_CONFIG,Ece as DEFAULT_OUTPUT_CONFIG,Cce as DEFAULT_TOOLS_CONFIG,Lh as DEFAULT_TOOL_METADATA_GATEWAY,Vd as DESCRIPTIONS,VA as DIFF_PREVIEW_MAX_LINES,Is as DIRECT_TOOL_AUTO_FILLED_FIELDS,zC as DIRECT_TOOL_CATEGORIES,ZM as DIRECT_TOOL_DEFINITIONS,_t as DirectToolInputError,uce as ENV_TOKEN_VARS,K as ERROR_CODES,Fe as ERROR_MESSAGES,qo as FETCH_ERRORS,gn as FILE_OPERATION_ERRORS,Wi as FileContentBulkQueryLocalSchema,B_ as FileContentQueryBaseLocalSchema,dr as FileContentQueryLocalSchema,S9 as GITHUB_CLONE_REPO,h9 as GITHUB_FETCH_CONTENT,Ig as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,f9 as GITHUB_SEARCH_CODE,ve as GITHUB_SEARCH_DEFAULT_LIMIT,he as GITHUB_SEARCH_MAX_LIMIT,yQ as GITHUB_SEARCH_MAX_PAGES,b9 as GITHUB_SEARCH_PULL_REQUESTS,y9 as GITHUB_SEARCH_REPOSITORIES,_n as GITHUB_STRUCTURE_DEFAULTS,bQ as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Ag as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,g9 as GITHUB_VIEW_REPO_STRUCTURE,xW as GenericToolResultRowSchema,DV as GitHubCloneRepoOutputLocalSchema,Yi as GitHubCodeSearchBulkQueryLocalSchema,i2 as GitHubCodeSearchOutputLocalSchema,Ki as GitHubCodeSearchQueryLocalSchema,$V as GitHubFetchContentOutputLocalSchema,Oc as GitHubProvider,ts as GitHubPullRequestSearchBulkQueryLocalSchema,hr as GitHubPullRequestSearchQueryLocalSchema,rs as GitHubReposSearchBulkQueryLocalSchema,ns as GitHubReposSearchSingleQueryLocalSchema,A4 as GitHubSearchPullRequestsOutputLocalSchema,pY as GitHubSearchRepositoriesOutputLocalSchema,is as GitHubViewRepoStructureBulkQueryLocalSchema,OY as GitHubViewRepoStructureOutputLocalSchema,os as GitHubViewRepoStructureQueryLocalSchema,Qr as HOME,xz as IGNORED_FILE_EXTENSIONS,Cz as IGNORED_FILE_NAMES,wz as IGNORED_FOLDER_NAMES,Dt as KEY_FILE,_g as LOCAL_DEFAULT_FILES_PER_PAGE,w9 as LOCAL_FETCH_CONTENT,C9 as LOCAL_FIND_FILES,Nr as LOCAL_MAX_DEPTH,Ca as LOCAL_MAX_FILES_PER_PAGE,Kt as LOCAL_MAX_LIMIT,P9 as LOCAL_RIPGREP,q as LOCAL_TOOL_ERROR_CODES,Dg as LOCAL_TOOL_ERROR_REGISTRY,x9 as LOCAL_VIEW_STRUCTURE,je as LSP_GET_SEMANTICS_TOOL_NAME,T9 as LSP_GET_SEMANTIC_CONTENT,as as LocalFetchContentBulkQuerySchema,gr as LocalFetchContentQuerySchema,cs as LocalFindFilesBulkQuerySchema,UX as LocalFindFilesOutputSchema,yr as LocalFindFilesQuerySchema,TX as LocalGetFileContentOutputSchema,ps as LocalRipgrepBulkQuerySchema,on as LocalRipgrepQuerySchema,S5 as LocalSearchCodeOutputSchema,hO as LocalToolErrorCategory,Ss as LocalViewStructureBulkQuerySchema,F3 as LocalViewStructureOutputSchema,Pr as LocalViewStructureQuerySchema,YM as LspGetSemanticsOutputSchema,Eo as LspGetSemanticsQueryDisplaySchema,MM as LspGetSemanticsQuerySchema,yv as MAX_BRANCH_CACHE_SIZE,Gr as MAX_CHAR_LENGTH,Fg as MAX_CONTEXT_LINES,Wb as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Ri as MAX_DIRECTORY_FILES,Ta as MAX_MATCH_CONTENT_LENGTH,_ce as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,wa as MAX_PAGE_NUMBER,Ace as MAX_RETRIES,Oce as MAX_TIMEOUT,Za as MAX_TOTAL_SIZE,Lce as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,vce as MIN_RETRIES,kce as MIN_TIMEOUT,gd as NETWORK_ERROR_PATTERNS,lw as NpmDeprecationOutputSchema,cw as NpmRegistrySearchSchema,_s as NpmSearchBulkQueryLocalSchema,LZ as NpmSearchOutputLocalSchema,Ls as NpmSearchQueryLocalSchema,Dl as NpmViewResultSchema,Hu as OCTOCODE_DIR,et as OCTOCODE_HOME,E9 as OQL_SEARCH,Bn as OQL_SEARCH_TOOL_NAME,By as OctocodeConfigSchema,dv as OctokitWithThrottling,Qn as OqlSearchInputSchema,R9 as PACKAGE_SEARCH,Wo as PROMISE_ERRORS,OR as PROVIDER_CAPABILITIES,DR as PROXY_ENV_VARS,Vt as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,Lg as PR_CONTENT_MAX_ITEMS_PER_PAGE,im as ProviderInitializationError,Ka as RATE_LIMIT_CONFIG,yd as RATE_LIMIT_PATTERNS,yn as REPOSITORY_ERRORS,zt as RESOURCE_LIMITS,die as RipgrepJsonMessageSchema,Ke as SEARCH_ERRORS,FC as SEMANTIC_CONTENT_TYPES,FW as SENSITIVE_ENV_VARS,er as SESSION_FILE,mO as STARTUP_ERRORS,X as STATIC_TOOL_NAMES,tr as STATS_FILE,tb as STATUS_TO_ERROR_CODE,Zoe as StatusEmojis,uo as TOOLING_ALLOWED_ENV_VARS,fO as TOOL_ERRORS,pO as TOOL_METADATA_ERRORS,v as TOOL_NAMES,ze as ToolError,at as ToolErrors,$o as VALIDATION_ERRORS,qce as _getCacheState,yw as _packageNameToSearchKeywords,$ce as _resetConfigCache,Xoe as _resetMetadataState,TD as _resetNpmRegistryUrlCache,jy as _resetSessionState,hB as _resetTokenResolvers,fB as _setTokenResolvers,cp as applyContentPagination,vx as applyEntryFilters,pm as applyExactMatchRanking,pc as applyPagination,Mi as applyPartialContentFilter,gR as applyStructurePagination,iw as assertCircuitAvailable,V as attachRawResponseChars,a$ as buildBlockBoundaryHint,Nc as buildChildProcessEnv,Cd as buildCodeSearchQuery,_i as buildDiffPreview,nD as buildDirectToolCommandPatterns,C6 as buildDirectToolExampleQuery,uI as buildEntryPaginationHints,WC as buildExampleValue,mm as buildGhSearchCodeFinalizer,kS as buildGithubFetchContentFinalizer,vd as buildIssueSearchQuery,Am as buildMergedPagination,VD as buildPackagePagination,vm as buildPartialFailureWarnings,oL as buildPullRequestSearchCacheKey,Ed as buildPullRequestSearchQuery,wd as buildRepoSearchQuery,Om as buildResultPagination,qC as buildScalarExampleValue,dx as buildSearchNextMap,Sl as buildSearchResult,Gh as buildToolErrorResult,ds as buildWalkWarnings,Mn as bulkOutputEnvelopeFields,jA as byteSlice,dc as byteToCharIndex,Vb as charToByteIndex,MY as checkLargeOutputSafety,N6 as checkNpmAvailability,bw as checkNpmDeprecation,ED as checkNpmRegistryReachable,hf as checkRegexSafety,z as clampedInt,ur as cleanJsonObject,gB as cleanup,lz as clearAllCache,dz as clearLSPToolCache,uz as clearLocalToolCache,AB as clearOctokitInstances,sW as clearProviderCache,pz as clearRemoteAPICache,BR as cloneRepo,Qf as collectDisplayFields,Xc as collectFlatErrors,S_ as commonDirPrefix,Df as compactLocation,WD as compactPackageRepositories,an as compactResolvedSymbol,wP as compareIsoDateDescending,Zce as completeMetadata,KR as computeQueryTimeout,Dce as configExists,z6 as configureCircuitBreaker,ace as configureSecurity,ao as contextLinesField,e$ as convertByteMatchToChar,Qt as countLines,Q as countSerializedChars,mp as createBasePRTransformation,to as createCacheMeta,$s as createCallItemKey,N as createErrorResult,en as createGitHubProviderError,kc as createGitHubProviderErrorFromResult,gt as createLazyProviderContext,ap as createPaginationInfo,__ as createProviderExecutionContext,ge as createRelaxedBulkQuerySchema,Fn as createResponseFormat,dW as createResult,M3 as createSafeRegExp,Ee as createSuccessResult,Fa as decrypt,ry as deleteCredentials,Qy as deleteSession,tD as describeSchemaConstraints,Hf as describeSchemaType,nie as detectEnvironment,_a as encrypt,Bg as ensureClone,An as ensureCloneParentDir,Aa as ensureHome,Rn as ensureOctocodeDir,RO as ensureRepos,Gu as ensureTmp,SO as ensureTree,gi as etagSoftCache,rc as evictExpiredClones,Jr as evictExpiredTrees,fe as executeBulkOperation,rS as executeCloneRepo,Qh as executeDirectTool,ex as executeFetchContent,ox as executeFindFiles,Ah as executeLspGetSemantics,zn as executeNpmCommand,fT as executeOqlSearchTool,nn as executeProviderOperation,nS as executeProviderOperations,wx as executeRipgrepSearch,hx as executeRipgrepSearchInternal,Fx as executeViewStructure,qR as executeWithErrorIsolation,ht as executeWithToolBoundary,FP as exploreMultipleRepositoryStructures,Yr as extractEtag,ac as extractMatchingLines,NP as fallbackOnBestEffortFailure,pl as fetchContent,Bd as fetchDirectoryContents,Qi as fetchDirectoryContentsRecursivelyAPI,rp as fetchFileContentToDisk,lp as fetchFileTimestamp,Zb as fetchGitHubFileContentAPI,l1 as fetchGitHubPullRequestByNumberAPI,wp as fetchGitHubPullRequestByNumberAPIInternal,pR as fetchHistory,OS as fetchMultipleGitHubFileContents,Ei as fetchRawGitHubFileContent,Ut as fetchWithRetries,eR as filterPatch,jF as filterStructure,Qm as finalizeFetchContentResult,rx as finalizeFindFilesResult,px as finalizeRipgrepResult,_x as finalizeViewStructureResult,Er as findDirectToolDefinition,br as findFiles,Ai as findNextBlockBoundary,Ly as flushSession,_y as flushSessionSync,rv as formatBytes,pW as formatCallToolResultForOutput,YC as formatDirectToolCommandPattern,c6 as formatDirectToolMetadataSchemaText,d6 as formatDirectToolOutputSchemaText,a6 as formatDirectToolSchemaText,lD as formatDirectToolValidationIssues,bo as formatFileSize,Jc as formatFinalizedResponse,no as formatPRForResponse,qD as formatPackageData,nY as formatRepoLine,mh as gatherIncomingCallsRecursive,fh as gatherOutgoingCallsRecursive,Te as generateCacheKey,q1 as generatePaginationHints,wc as generateStructurePaginationHints,pd as getActiveProvider,md as getActiveProviderConfig,my as getAppDataPath,gy as getArchitecture,XU as getBulkDefaultCharLength,Kb as getByteLength,mz as getCacheStats,pA as getCacheTTL,Si as getCloneBaseDir,Gd as getCloneDir,Gce as getConfig,Fce as getConfigFilePath,Hce as getConfigSync,Uce as getConfigValue,Zn as getCredentials,cy as getCredentialsFilePath,Da as getCredentialsSync,jg as getDefaultOctocodeHome,Fh as getDescription,l6 as getDirectToolAutoFilledFields,Fs as getDirectToolCategory,p6 as getDirectToolDescription,Fl as getDirectToolDisplayFields,u6 as getDirectToolOutputFields,li as getDirectorySizeBytes,pce as getEnvTokenSource,db as getExtension,LR as getFileContent,Ia as getGhCliToken,dd as getGitHubToken,fy as getLocalAppDataPath,oie as getLspEnvironmentHint,mA as getMaxCacheSizeBytes,fA as getMaxCloneCount,Yoe as getMetadataOrNull,Ns as getNpmRegistryUrl,Jn as getOctocodeDir,oe as getOctokit,Fy as getOrCreateSession,Ln as getOutputCharLimit,rb as getOwnerQualifier,hy as getPlatformName,Up as getProvider,ue as getRawResponseChars,Hi as getRecursiveFetchFailureCount,FR as getRepoStructure,Zv as getReposBaseDir,Vce as getRuntimeSurface,ui as getServerConfig,Iy as getSessionId,ly as getToken,dce as getTokenFromEnv,RB as getTokenSource,uy as getTokenSync,Vu as getTokenWithRefresh,nc as getTreeBaseDir,Pi as getTreeDir,Ve as handleCatchError,re as handleGitHubAPIError,Dc as handleProviderError,sy as hasCredentials,ay as hasCredentialsSync,mce as hasEnvToken,a2 as hasExpensiveContentRequest,jf as hasSchemaDefault,uF as hasValidCodeSearchParams,Xy as hashGitHubToken,Qc as hoistSharedFields,HY as ignoreBestEffortFailure,Dy as incrementErrors,$a as incrementGitHubCacheHits,qa as incrementGitHubCacheRateLimits,Gy as incrementPackageRegistryFailures,Ny as incrementRateLimitByProvider,za as incrementRateLimits,My as incrementToolCalls,Ua as incrementToolCharSavings,YI as inferLspSymbolName,$y as initialize,MR as initializeProviders,Koe as initializeToolMetadata,zce as invalidateConfigCache,Zo as invalidateCredentialsCache,vW as invokeCallbackSafely,eo as isCacheHit,kb as isCacheValid,aw as isCircuitOpen,bB as isCloneEnabled,zs as isExactPackageName,Et as isGitHubAPIError,SL as isGitHubAPISuccess,Oo as isJsonSchemaObject,Ju as isLinux,yB as isLocalEnabled,PZ as isLocalTool,Xu as isMac,vi as isMidBlockCut,Ht as isNoResultsSearchError,As as isOqlEnabled,A_ as isProviderError,Bc as isProviderSuccess,cn as isRecord,Xo as isRefreshTokenExpired,PL as isRepository,Yt as isTokenExpired,Du as isToolError,Yd as isToolInMetadata,ti as isWindows,co as lineNumberField,oy as listStoredHosts,iy as listStoredHostsSync,Ice as loadConfig,Mce as loadConfigSync,Voe as loadToolContent,KL as makeToolResultRowSchema,uS as mapCodeSearchProviderResult,lS as mapCodeSearchToolQuery,RS as mapFileContentProviderResult,bS as mapFileContentToolQuery,gS as mapPullRequestProviderResultData,hS as mapPullRequestToolQuery,mS as mapRepoSearchProviderRepositories,pS as mapRepoSearchToolQuery,PS as mapRepoStructureProviderResult,lm as mapRepoStructureToolQuery,ice as maskSensitiveData,Ii as normalizeOwnerRepo,QS as normalizePullRequestContentRequest,bi as normalizeResponseHeaders,zm as paginateEntries,ls as parseFileSize,Ie as parseGitHubProjectId,oo as parseHasMore,Ue as paths,fx as preflightValidateRipgrepPattern,cD as prepareDirectToolInput,k6 as prepareDirectToolInputFromJsonText,Jb as processFileContentAPI,zc as providerSupports,Qd as readCacheMeta,Jt as readCredentialsStore,sw as recordCircuitFailure,qf as recordCircuitSuccess,qy as recordPackageRegistryFailure,En as recordRateLimit,Ko as redactPath,dy as refreshAuthToken,Hc as relativizeResultPaths,Pe as relaxedPageNumberField,Qce as reloadConfig,oc as removeCloneDir,B6 as resetCircuitBreaker,Hy as resetSessionStats,Uu as resetTokenResolution,Ge as resolveCacheAuthFingerprint,jce as resolveConfig,Bce as resolveConfigSync,Ye as resolveDefaultBranch,fce as resolveEnvToken,ah as resolveFileAnchor,Ui as resolveQueryId,Tw as resolveSymbolAnchor,$u as resolveToken,Pn as resolveTokenFull,qu as resolveTokenWithRefresh,$i as resolveUniqueQueryIds,We as responseEnvelopeFields,cie as safeExec,pt as safeParseOrError,Nh as sanitizeCallToolResult,vt as sanitizeStructuredContent,vR as searchCode,Rt as searchContentRipgrep,hb as searchGitHubCodeAPI,uR as searchGitHubPullRequestsAPI,hR as searchGitHubReposAPI,NS as searchMultipleGitHubCode,yP as searchMultipleGitHubPullRequests,AP as searchMultipleGitHubRepos,nh as searchNpmPackage,Sw as searchPackage,xw as searchPackages,_R as searchPullRequests,AR as searchRepos,nce as securityRegistry,r$ as serializeForPagination,Wce as setRuntimeSurface,KS as shapePullRequestForContent,fp as shouldEnrichPullRequestFromSearch,yi as shouldIgnoreDir,Vr as shouldIgnoreFile,rie as shouldUseMCPLsp,Ad as shouldUseSearchForIssues,kd as shouldUseSearchForPRs,o$ as sliceByCharRespectLines,ip as sliceContent,fc as snapToSemanticBoundary,s6 as sortDirectToolNames,NR as spawnCheckSuccess,HW as spawnCollectStdout,tn as spawnWithTimeout,ki as splitLines,Kz as startCacheGC,Yz as stopCacheGC,Wu as storeCredentials,Bm as summarizeEntries,Lx as toEntryObject,Ax as toGroupedLists,Ng as toToolError,TL as transformCodeSearchResult,OL as transformFileContentResult,Di as transformPullRequestItemFromREST,Cp as transformPullRequestItemFromSearch,LL as transformPullRequestResult,EL as transformRepoSearchResult,FL as transformRepoStructureResult,tR as trimDiffContext,z_ as truncateSnippetChars,ct as updateSessionStats,Na as updateToken,Gc as validateArgs,Nce as validateConfig,bt as validateToolPath,Ip as viewGitHubRepositoryStructureAPI,Tl as viewStructure,vg as withBasicSecurityValidation,He as withDataCache,Ja as withDataCacheConditional,PW as withResponseEnvelope,Og as withSecurityValidation,Zr as writeCacheMeta,tle as z};
|
|
52
|
+
`)}}var UE,qE=f(()=>{"use strict";un();ne();Ru();mo();Mr();Yn();UE=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/});import Be from"node:path";function JG(e,t,n){let r=t??n??".";if(!e)return r;if(Be.isAbsolute(e))return e;if(n&&Be.isAbsolute(n))return Be.resolve(n,e);if(t&&Be.isAbsolute(t)){let o=ma(t)?t:Be.dirname(t);return Be.resolve(o,e)}return e}function WE(){return x("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function ZG(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(x("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(x("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push(WE()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push(WE());let i=e?.pagination;return i?.hasMore&&n.push(x("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:dg(i,t)})),n}async function VE(e){let t,n,r=[],o=[],i=xt(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let E=e.from.path,_=ma(E);n=c??(_?Be.resolve(E):void 0),t=a??(_?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=Qe(e.scope),_=E?Be.isAbsolute(E)?E:Be.join(e.from.localPath,E):void 0;s?(n=c??e.from.localPath,t=a??_):t=a??_??e.from.localPath}else if(e.from?.kind==="github"){let{owner:E,repo:_}=Kn(e.from);if(!E||!_)return o.push(x("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,G=Qe(e.scope),M=w&&!Be.isAbsolute(w)?w:G,A=await ke("ghCloneRepo",{owner:E,repo:_,...e.from.ref?{branch:e.from.ref}:{},...M?{sparsePath:M}:{}}),W=qn(A).data,H=_E(A,W?.localPath);if(!H)return o.push(x("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:H}),s?(n=c??H,w?t=Be.isAbsolute(w)?w:Be.join(H,w):G&&(t=Be.isAbsolute(G)?G:Be.join(H,G))):w?t=Be.isAbsolute(w)?w:Be.join(H,w):G?t=Be.isAbsolute(G)?G:Be.join(H,G):t=H}if(!t&&!n)return o.push(x("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...m}=i,p=await ke("lspGetSemantics",{...m,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:h,status:g}=qn(p),y=h,b=DE(y,e),S=JG(Ys(y?.uri),t,n),C=nH(e,S),k=tH(eH(y),u);return{results:g==="error"?[]:Vn(k,"semantics",C),...b?{pagination:b}:{},diagnostics:[...o,...ug(p,"lspGetSemantics"),...ZG(y,e)],provenance:[...r,{backend:"lspGetSemantics",source:C}]}}function eH(e){if(!e)return[];let n=(lg(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=Ys(e.uri);return n.map(o=>lg(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return hu(e)}function tH(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function nH(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}var KE=f(()=>{"use strict";un();ne();jn();pa();Mr();Yn()});import{builtinModules as rH}from"node:module";var fg,YE,XE,JE,ha=f(()=>{"use strict";fg=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],YE="package.json",XE=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),JE=new Set(rH.flatMap(e=>[e,`node:${e}`]))});import Pu from"node:path";function xu(){if(ga)return ga;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());ga=new Set(e.length>0?e:fg)}catch{ga=new Set(fg)}return ga}function ZE(){if(ya)return ya;try{let e=JSON.parse(D.getGraphFactCapabilities());ya=Array.isArray(e)?e.filter(oH):[]}catch{ya=[]}return ya}function oH(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function hg(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function Cu(e,t,n){return wu(Pu.resolve(e,t),n)}function wu(e,t){let n=xu(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(Pu.join(e,`index${o}`));return r.find(o=>t.has(o))}function ba(e){return e.startsWith("./")||e.startsWith("../")}function ek(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function tk(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function gg(e){return typeof e=="string"&&e.trim()?e:void 0}function Tu(e){return typeof e=="string"&&e.length>0}function nk(e){return typeof e=="string"}function rk(e){return[...new Set(e)]}function Wt(e,t){return Pu.relative(e,t)||Pu.basename(t)}function ok(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function ik(e,t){return!!(e===t||e.endsWith(`.${t}`)||e.endsWith(`::${t}`))}var ga,ya,Ra=f(()=>{"use strict";Le();ha()});import mn from"node:path";import{readFile as iH,readdir as sH}from"node:fs/promises";async function sk(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await sH(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(XE.has(s.name))continue;await r(mn.join(o,s.name));continue}s.isFile()&&n.push(mn.join(o,s.name))}}return await r(e),n}async function ak(e){return(await Promise.all(e.map(async n=>aH(n)))).filter(n=>n!==null)}async function aH(e){let t=await cH(e);if(!t)return null;let n=mn.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=tk(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:gg(t.name),deps:r,entrypoints:lH(n,t)}}async function cH(e){try{let t=JSON.parse(await iH(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function lH(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=gg(t[o]);i&&n.add(mn.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(mn.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(mn.resolve(e,o));ck(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(mn.resolve(e,o));return[...n]}function ck(e,t,n){if(typeof t=="string"){n.add(mn.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))ck(e,r,n)}function lk(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=uH(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:Wt(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:Wt(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:Wt(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function uH(e,t){return t.filter(r=>e.startsWith(`${r.dir}${mn.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}var uk=f(()=>{"use strict";ha();Ra()});import Bo from"node:path";import{readFile as dH}from"node:fs/promises";async function dk(e,t){let n=xu(),r=t.filter(i=>n.has(Bo.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await dH(i,"utf8").catch(()=>""),a=Bo.extname(i).toLowerCase(),c=pH(s,i,Wt(e,i)),l=rk(c?c.imports.map(u=>u.specifier):mH(s));return{path:i,rel:Wt(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!ba(u)).map(ek).filter(Tu).filter(u=>!JE.has(u)),...c?{graphFacts:c}:{}}}))}function pH(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??Bo.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(nk):[]}}catch{return}}function yg(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...xu()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=hg(e,l=>l.language),s=hg(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function mH(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function pk(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,Bo.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??Bo.dirname(o.path);for(let a of o.imports){if(!ba(a))continue;let c=Cu(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function mk(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=wu(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","lib.rs","main.rs","mod.rs"]){let s=wu(Bo.resolve(e,i),r);s&&o.add(s)}return[...o]}function fk(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}var hk=f(()=>{"use strict";Le();ha();Ra()});import fH from"node:path";import{readFile as gk}from"node:fs/promises";async function yk(e){return(await Promise.all(e.map(async n=>{let r=hH(n);if(r.length>0)return r;let o=await gk(n.path,"utf8").catch(()=>"");return gH(n.rel,o)}))).flat()}function hH(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function gH(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:ok(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function bk(e,t,n){let r=new Map(t.map(a=>[a.rel,a])),o=new Map(t.map(a=>[a.path,a])),i=new Set(t.map(a=>a.path)),s=yH(t);return e.map(a=>{let c=r.get(a.file),l=bH(a,t,c,s,i,o),u=l.length>0?"ast":"ripgrep",d=l.length>0?l:t.filter(g=>g.rel!==a.file&&RH(g.path,a.symbol)).map(g=>g.rel),m=d.filter(g=>{let y=r.get(g);return y?n.has(y.path):!1}),p=c?n.has(c.path):!1,h=m.length>0?"reachable":d.length>0?"transitive-dead":p?"candidate-unused-export":"unused-export";return{symbol:a.symbol,kind:a.kind,file:a.file,line:a.line,evidenceSource:a.evidenceSource,retentionSource:u,directRefs:d.length,externalRefs:m.length,retainedBy:d,verdict:h}})}function yH(e){let t=new Map;for(let n of e){let r=n.graphFacts;if(r){for(let o of r.declarations){if(!o.exported)continue;let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}for(let o of r.exports){let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}}}return t}function bH(e,t,n,r,o,i){let s=r.get(e.symbol)??(n?new Set([n.path]):new Set),a=new Set;for(let c of t){if(c.rel===e.file)continue;let l=c.graphFacts;if(l){for(let u of l.imports){let d=u.importedName&&u.importedName!=="default"?u.importedName:void 0,m=u.localName;if(!(d===e.symbol||m===e.symbol)||!ba(u.specifier))continue;let h=Cu(fH.dirname(c.path),u.specifier,o);if(h&&s.has(h)){a.add(c.rel);break}}if(!a.has(c.rel)){for(let u of l.calls)if(ik(u.callee,e.symbol)){a.add(c.rel);break}}}}return[...a].sort()}function RH(e,t){return bg.get(e)?.has(t)??!1}async function Rk(e){bg.clear(),await Promise.all(e.map(async t=>{let n=await gk(t.path,"utf8").catch(()=>"");bg.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}var bg,Sk=f(()=>{"use strict";Ra();bg=new Map});import SH from"node:path";async function Eu(e){let t=SH.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=PH(r,e.intent,e.facets),i=xH(o,e.facets),s=CH(o,i),a=ZE();if(n==="plan")return wH({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:yg([],[],a)});let c=await sk(t,e.maxFiles??5e3),l=await ak(c.filter(w=>w.endsWith(YE))),u=await dk(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),m=yg(u,d,a);await Rk(u);let p=new Set(l.map(w=>w.name).filter(Tu)),h=pk(u),g=mk(t,l,u),y=fk(g,h),b=u.filter(w=>!y.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=lk(t,l,u,p),C=await yk(u),k=bk(C,u,y),E=k.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,_=k.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:y.size,unusedFiles:b.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:k.length,candidateUnusedExports:E,transitiveDeadExports:_,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,G)=>w+G.declarations.length,0),nativeGraphCalls:d.reduce((w,G)=>w+G.calls.length,0)},manifests:l.map(w=>({manifest:Wt(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(G=>Wt(t,G)),dependencyCount:[...w.deps.keys()].length})),files:b,dependencies:S,symbols:k,graphFacts:d,graphCapabilities:m,caveats:["Analyze uses native AST graph facts for inventory and preferred cross-file retention (named imports / call callees). Lexical token scan is fallback only when AST finds no retainers.",'Graph facts are syntax inventory, not semantic identity. Upgrade candidates with target:graph proof:"lsp" (or lspGetSemantics references/callers) before destructive cleanup.',"Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function PH(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function xH(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function CH(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["extractGraphFacts","export regex fallback"],produces:["symbols","lineHints"],evidence:"heuristic"},{id:"reference-scan",purpose:"Candidate cross-file retention from native AST imports/calls (preferred) with lexical token fallback. Upgrade via target:graph proof:lsp \u2014 analyze does not run LSP.",tools:["extractGraphFacts","token scan fallback"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"heuristic"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function wH(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}var Rg=f(()=>{"use strict";uk();hk();Sk();ha();Ra()});async function Pk(e){let t=xt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=bu(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await Eu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[x("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:aa(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?Fr(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?IE(e,i):{fields:{}},m={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:ua(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},p=ME(l?.pagination,d.pagination);return{results:Vn([m],"research",e.from),...p?{pagination:p}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}var xk=f(()=>{"use strict";ne();Rg();pu();da();Mr();pa();Yn()});import ku from"node:path";function Pg(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function wk(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function Tk(e,t,n,r,o){let i=n.filter(l=>ca(l,r)),s=Fr(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await EH(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(x(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(x("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),TH(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(x("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function TH(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function EH(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=ku.isAbsolute(t.subject.uri)?t.subject.uri:ku.resolve(e,t.subject.uri);try{let i=await ke("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=kH(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=qn(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:Ys(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,m=Io(a?.totalReferences)??Io(u?.totalReferences)??Io(a?.referenceCount)??Io(u?.referenceCount)??Io(d?.totalItems)??Ck(u)??Ck(a);return{status:"ok",...typeof m=="number"?{totalReferences:m}:{},files:OH(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function kH(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function Ck(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function OH(e,t){let n=new Set;return Sg(e,n,t),[...n].slice(0,25)}function Sg(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)Sg(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&vH(i)&&t.add(ku.isAbsolute(i)?ku.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])Sg(r[o],t,n)}function vH(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var Ek=f(()=>{"use strict";un();ne();da()});async function kk(e){let t=xt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=bu(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await Eu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[x("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:aa(i),a=ag(t),c=s?.packets??[],l=Pg(i.mode,t)?await Tk(n,e,c,a,wk(e,t)):[],u=OE(c),d=kE(e,c,u,a,i.graphFacts,n),m=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[Pg(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],p={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:ua(i.graphFacts),caveats:m};return{results:Vn([p],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var Ok=f(()=>{"use strict";ne();Rg();pu();da();Ek();Mr();pa();Yn()});var vk,Ak=f(()=>{"use strict";HE();BE();qE();KE();xk();Ok();vk={repositories:NE,packages:GE,pullRequests:pg,commits:pg,diff:$E,semantics:VE,research:Pk,graph:kk}});function Lk(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&AH.has(e.target)&&t.push(x("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "none" or "standard".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "none" or "standard".'}})),t}var AH,_k=f(()=>{"use strict";ne();AH=new Set(["pullRequests","commits","diff"])});function Fk(e){let t={schema:Ct.schema,view:e.view??Ct.view,page:e.page??Ct.page,itemsPerPage:e.itemsPerPage??Ct.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??Ct.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??Ct.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??Ct.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?Ct.detailedCodeContext:Ct.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??Ct.localSearchSort),t}var Ct,Ik=f(()=>{"use strict";Ct={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"standard",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function LH(e){return e?.mode==="auto"||e?.mode==="required"}function _H(e,t){let n=e.target==="files"?Dr:Xn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:Xn,exact:!0,reason:`${t.kind} evaluated locally by ${Xn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function FH(e,t,n){let r=LH(e.materialize);if(n)return IH(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:Dr,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:Dr,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:fn,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:Dr,exact:!0,reason:`${Ou(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:Dr,exact:!1,reason:`GitHub cannot enumerate files by ${Ou(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Ou(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:Xn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:Xn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:fn,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?xg(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:Xn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return xg(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:Dr,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:fn,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:fn,exact:!0,reason:"path/name predicate pushed to provider"}:xg(e,`field "${t.field}"`,r)}}function Ou(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function IH(e,t,n){let r=Ou(t);return n?{route:"ROUTE",backend:e.target==="files"?Dr:Xn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:fn,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function xg(e,t,n){if(n)return{route:"ROUTE",backend:Xn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:fn,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function Mk(e,t,n=!1){return e.sourceKind==="github"?FH(e,t,n):_H(e,t)}var Xn,Dr,fn,Dk=f(()=>{"use strict";Xn="localSearchCode",Dr="localFindFiles",fn="ghSearchCode"});function zo(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return Cg.find(n=>n.id===`${t}.diff.${e.variant}`)}return Cg.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function wg(e){return Cg.find(t=>t.id===e)}function Tg(e){let t=MH(e.source,e.target);if(e.target==="diff"){let n=jo(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return zo({sourceKind:t,target:"diff",variant:r})}return zo({sourceKind:t,target:e.target})}function Nk(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function Gk(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function MH(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var Cg,Hk=f(()=>{"use strict";Ru();Cg=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function DH(e,t){return e.id??t}function vu(e,t,n,r,o,i=!1){let s=DH(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,m)=>vu(e,d,`${n}.of[${m}]`,r,o,i)),l=NH(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(x("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=vu(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=Mk(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(x(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&Qk(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:GH(e.target),exact:a.exact}),a.route}function NH(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function GH(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function Qk(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Au(e,t){if(!t)return;let n=Gk(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Sa(e,t,n){if(!t)return!1;for(let r of Nk(t,n))Qk(e.backendCalls,r);return!0}function jk(e,t){return Eg(e,t,"files")}function Eg(e,t,n,r=zo({sourceKind:"materialized",target:n})){let o=zo({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Au(e,o),Au(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),Sa(e,o,t),Sa(e,r,void 0),!0}function Lu(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Lu):e.kind==="not"?Lu(e.predicate):!1:!1}function Bk(e){return e.target==="code"?wg(Lu(e.where)?"local.code.structural":"local.code.textRegex"):zo({sourceKind:"materialized",target:e.target})}function zk(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?wg(Lu(e.where)?"local.code.structural":"local.code.textRegex")??Tg({source:t,target:e.target,params:e.params}):Tg({source:t,target:e.target,params:e.params})}var Uk=f(()=>{"use strict";Dk();ne();Hk()});function $k(e){return e.kind==="not"&&e.predicate.kind==="not"?$k(e.predicate.predicate):e}function qk(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Sf[e.target]:void 0;if(n)return n.includes(t)?[]:[x("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[x("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function Wk(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=$k(e.where),r=Zs({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function Vk(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(x("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(x("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var Kk=f(()=>{"use strict";ne();$h();Gn()});function Yk(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=zk(e,o);if(Au(n,s),e.where)vu(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(h=>h.route==="ROUTE")&&Eg(n,o,e.target,Bk(e));else if(e.target==="diff"){let h=jo(e.params);h.kind==="prPatch"||h.kind==="directFile"?Sa(n,s,o)||n.diagnostics.push(x("unsupportedTarget",`No transformer registered for target:"diff" lane "${h.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let h=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(h?g&&jk(n,o):Sa(n,s,o))&&(!h||g)&&n.diagnostics.push(x("unsupportedTarget",h?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(x("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...Wk(e,n.nodes)),n.diagnostics.push(...qk(e)),n.diagnostics.push(...Lk(e));let a=Vk(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??Ct.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(x("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=xo(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(x("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let m={input:t,normalized:e,defaults:Fk(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},p=!n.nodes.some(h=>h.route==="UNSUPPORTED")&&!n.diagnostics.some(h=>h.severity==="error"&&h.code!=="planTruncated");return{plan:m,executable:p}}var Xk=f(()=>{"use strict";Ru();_k();ne();Ik();kf();Uk();Kk()});function HH(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function Jk(e,t,n,r,o,i){let s=o&&i?QH(i):[],a=o&&i?jH(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:Ol(e.plan.diagnostics,t,n,r,HH(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function QH(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[x("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function jH(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}var Zk=f(()=>{"use strict";ne();ks()});function eO(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):zH.has(c)?o.add(c):UH.has(c)?o.add("data"):$H.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!BH.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[x("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}var BH,zH,UH,$H,tO=f(()=>{"use strict";ne();BH=new Set(["kind","source","recordType","id","proofGrade"]),zH=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","matchKind","scoreHint","proofGrade","size","modified","entryType","depth","children","data"]),UH=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),$H=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});function Pa(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function _u(e,t,n,r){let o=Yk(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return Jk(o,s,e.id,r,n.dryRun,e);let a=await VH(e,o);SC(e,a.results),qH(e,a),WH(a);let c=FC(e,a);xC(e,a.results);let l=eO(e,a.results),u=IC(a.results);return Es({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:yC(o.plan.backendCalls),plan:s})}function qH(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function WH(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}async function VH(e,t){if(e.target==="materialize")return bE(e);let n=vk[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?sa(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?yE(e):HT(e)}var kg=f(()=>{"use strict";QT();ig();RE();Ak();ks();Xk();Mf();Zk();_f();Ff();tO()});async function nO(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await _u(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=KH(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&Pa(o.merged.results)}else for(let i of r)Pa(i.envelope.results);return o}function KH(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let m=ZH(d);n.has(m)||(n.add(m),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),YH(s,u.envelope.nextHints),XH(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),JH(u.envelope)&&(l=!0)}return l&&o.push(x("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Es({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function YH(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||If(o,r))&&(e[n]=r)}}function XH(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function JH(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function ZH(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var rO=f(()=>{"use strict";ne();ks();Mf();kg()});var oO={};dO(oO,{runOqlSearch:()=>eQ});async function eQ(e,t={}){let n;try{n=fC(e)}catch(o){if(o instanceof sn)return Ol(o.diagnostics);throw o}if(xf(n))return nO(n,e,t);let r=await _u(n,e,t);return Pa(r.results),r}var iO=f(()=>{"use strict";hC();ne();ks();Gn();rO();kg()});async function gT(e){let t=tQ(e),n=Qn.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(iO(),oO)),o=await r(n.data,{authInfo:e.authInfo});return nQ(o)}function tQ(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function nQ(e){let t=rQ(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function rQ(e){return Cf(e)?{results:e.children.map(t=>sO(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:aO(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[sO(e,e.queryId??"oqlSearch-1")]}}function sO(e,t){let n=aO(e);return{id:e.queryId??t,...iQ(e),data:n}}function aO(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||oQ(d,u)){let{why:m,confidence:p,...h}=l;s[c]=h,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function oQ(e,t){return e.why===t.why&&e.confidence===t.confidence}function iQ(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var Mh=f(()=>{"use strict";Cr();Gn()});Iu();ce();st();Xo();bn();Nu();Ko();Ae();Fd();op();bd();tt();pp();dp();ac();Tp();Gi();ar();Op();Hi();rr();vp();Mp();Ap();_p();or();Dp();Ac();Hp();Bp();Qp();Gp();jp();kt();so();nt();dt();$r();pi();Dn();Ei();Yp();sm();am();dm();um();Uc();hm();fm();gm();ym();Sm();Tm();ul();_m();Fm();io();Im();Mm();lc();jm();as();ml();Um();So();fl();ff();lf();uf();Rs();fs();Sr();bf();xs();wl();yf();Mh();Kl();Kl();_l();_l();hh();Ul();Lt();sh();Nf();rn();pr();Ih();Zd();Kd();_h();Xd();Ud();me();Wd();import{completeMetadata as sQ}from"@octocodeai/octocode-core";var xa=null;function cO(){return xa||(xa=sc(sQ)),xa}async function Koe(){return cO()}async function Yoe(){cO()}function Xoe(){return xa}function Joe(){xa=null}jh();To();Me();Cr();var eie={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}"};Dm();Em();bo();sr();Xp();gf();import{getConfigSync as lO}from"@octocodeai/config";function rie(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function oie(){try{return lO().local.enabled}catch{return!1}}function iie(){try{if(!lO().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}Ao();mo();import{validateCommand as aQ}from"@octocodeai/octocode-engine/commandValidator";async function lie(e,t=[],n={}){let r=aQ(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Gc(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:l=!1}=n,u=await tn(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(u.outputLimitExceeded&&l)return{success:!0,code:u.exitCode,stdout:u.stdout,stderr:u.stderr,truncated:!0};if(u.error)throw u.error;return{success:u.success,code:u.exitCode,stdout:u.stdout,stderr:u.stderr}}mo();sp();Kr();ds();Bt();lt();Ml();zs();oh();rh();Bs();gc();vi();fc();Ec();Ii();import{z as B}from"zod";var Fu=B.object({text:B.string()}),cQ=B.object({match:B.object({text:B.string()}).optional(),start:B.number(),end:B.number()}),lQ=B.object({type:B.literal("match"),data:B.object({path:Fu,lines:B.object({text:B.string()}),line_number:B.number(),absolute_offset:B.number(),submatches:B.array(cQ)})}),uQ=B.object({type:B.literal("context"),data:B.object({path:Fu,lines:B.object({text:B.string()}),line_number:B.number(),absolute_offset:B.number()})}),dQ=B.object({type:B.literal("begin"),data:B.object({path:Fu})}),pQ=B.object({type:B.literal("end"),data:B.object({path:Fu,stats:B.object({elapsed:B.object({human:B.string()}),searches:B.number(),searches_with_match:B.number()}).optional()})}),mQ=B.object({type:B.literal("summary"),data:B.object({elapsed_total:B.object({human:B.string()}),stats:B.object({elapsed:B.object({human:B.string()}),searches:B.number(),searches_with_match:B.number(),bytes_searched:B.number(),bytes_printed:B.number(),matched_lines:B.number(),matches:B.number()})})}),pie=B.discriminatedUnion("type",[lQ,uQ,dQ,pQ,mQ]);Xe();Hh();le();Mc();Zc();jc();lr();om();hl();Yu();Zu();sd();ad();ti();cd();import{securityRegistry as rce,ContentSanitizer as oce}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as sce}from"@octocodeai/octocode-engine/mask";import{configureSecurity as cce}from"@octocodeai/octocode-engine/withSecurityValidation";import{ENV_TOKEN_VARS as dce,getTokenFromEnv as pce,getEnvTokenSource as mce,hasEnvToken as fce,resolveEnvToken as hce}from"@octocodeai/config";import{CONFIG_SCHEMA_VERSION as Rce,CONFIG_FILE_NAME as Sce,DEFAULT_CONFIG as Pce,DEFAULT_GITHUB_CONFIG as xce,DEFAULT_LOCAL_CONFIG as Cce,DEFAULT_TOOLS_CONFIG as wce,DEFAULT_NETWORK_CONFIG as Tce,DEFAULT_LSP_CONFIG as Ece,DEFAULT_OUTPUT_CONFIG as kce,MIN_TIMEOUT as Oce,MAX_TIMEOUT as vce,MIN_RETRIES as Ace,MAX_RETRIES as Lce,MIN_OUTPUT_DEFAULT_CHAR_LENGTH as _ce,MAX_OUTPUT_DEFAULT_CHAR_LENGTH as Fce,getConfigFilePath as Ice,loadConfig as Mce,loadConfigSync as Dce,configExists as Nce,validateConfig as Gce,getConfig as Hce,getConfigSync as Qce,reloadConfig as jce,resolveConfig as Bce,resolveConfigSync as zce,invalidateConfigCache as Uce,getConfigValue as $ce,_resetConfigCache as qce,_getCacheState as Wce,setRuntimeSurface as Vce,getRuntimeSurface as Kce}from"@octocodeai/config";import{completeMetadata as ele}from"@octocodeai/octocode-core";import{z as nle}from"zod";export{PQ as ALL_ERROR_CODES,hT as ALL_TOOLS,kA as BASE_SCHEMA,Wi as BulkCloneRepoLocalSchema,Oo as BulkLspGetSemanticsQuerySchema,Mu as CONFIG_ERRORS,Sce as CONFIG_FILE_NAME,Rce as CONFIG_SCHEMA_VERSION,zi as CORE_ALLOWED_ENV_VARS,Xt as CREDENTIALS_FILE,Uf as CircuitOpenError,fo as CloneRepoQueryLocalSchema,oce as ContentSanitizer,GY as DEFAULTS,B6 as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,Pce as DEFAULT_CONFIG,xce as DEFAULT_GITHUB_CONFIG,Cce as DEFAULT_LOCAL_CONFIG,Ece as DEFAULT_LSP_CONFIG,Mg as DEFAULT_MATCH_SNIPPET_CHARS,Tce as DEFAULT_NETWORK_CONFIG,kce as DEFAULT_OUTPUT_CONFIG,wce as DEFAULT_TOOLS_CONFIG,Lh as DEFAULT_TOOL_METADATA_GATEWAY,Vd as DESCRIPTIONS,YA as DIFF_PREVIEW_MAX_LINES,Ms as DIRECT_TOOL_AUTO_FILLED_FIELDS,$C as DIRECT_TOOL_CATEGORIES,eD as DIRECT_TOOL_DEFINITIONS,_t as DirectToolInputError,dce as ENV_TOKEN_VARS,K as ERROR_CODES,Fe as ERROR_MESSAGES,Wo as FETCH_ERRORS,gn as FILE_OPERATION_ERRORS,Vi as FileContentBulkQueryLocalSchema,U_ as FileContentQueryBaseLocalSchema,dr as FileContentQueryLocalSchema,P9 as GITHUB_CLONE_REPO,g9 as GITHUB_FETCH_CONTENT,Ig as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,h9 as GITHUB_SEARCH_CODE,ve as GITHUB_SEARCH_DEFAULT_LIMIT,he as GITHUB_SEARCH_MAX_LIMIT,bQ as GITHUB_SEARCH_MAX_PAGES,R9 as GITHUB_SEARCH_PULL_REQUESTS,b9 as GITHUB_SEARCH_REPOSITORIES,_n as GITHUB_STRUCTURE_DEFAULTS,RQ as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Ag as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,y9 as GITHUB_VIEW_REPO_STRUCTURE,CW as GenericToolResultRowSchema,NV as GitHubCloneRepoOutputLocalSchema,Xi as GitHubCodeSearchBulkQueryLocalSchema,s2 as GitHubCodeSearchOutputLocalSchema,Yi as GitHubCodeSearchQueryLocalSchema,qV as GitHubFetchContentOutputLocalSchema,vc as GitHubProvider,ns as GitHubPullRequestSearchBulkQueryLocalSchema,hr as GitHubPullRequestSearchQueryLocalSchema,os as GitHubReposSearchBulkQueryLocalSchema,rs as GitHubReposSearchSingleQueryLocalSchema,L4 as GitHubSearchPullRequestsOutputLocalSchema,mY as GitHubSearchRepositoriesOutputLocalSchema,ss as GitHubViewRepoStructureBulkQueryLocalSchema,vY as GitHubViewRepoStructureOutputLocalSchema,is as GitHubViewRepoStructureQueryLocalSchema,Qr as HOME,Cz as IGNORED_FILE_EXTENSIONS,wz as IGNORED_FILE_NAMES,Tz as IGNORED_FOLDER_NAMES,Dt as KEY_FILE,_g as LOCAL_DEFAULT_FILES_PER_PAGE,T9 as LOCAL_FETCH_CONTENT,w9 as LOCAL_FIND_FILES,Nr as LOCAL_MAX_DEPTH,wa as LOCAL_MAX_FILES_PER_PAGE,Kt as LOCAL_MAX_LIMIT,x9 as LOCAL_RIPGREP,q as LOCAL_TOOL_ERROR_CODES,Dg as LOCAL_TOOL_ERROR_REGISTRY,C9 as LOCAL_VIEW_STRUCTURE,je as LSP_GET_SEMANTICS_TOOL_NAME,E9 as LSP_GET_SEMANTIC_CONTENT,cs as LocalFetchContentBulkQuerySchema,gr as LocalFetchContentQuerySchema,ls as LocalFindFilesBulkQuerySchema,$X as LocalFindFilesOutputSchema,yr as LocalFindFilesQuerySchema,EX as LocalGetFileContentOutputSchema,ms as LocalRipgrepBulkQuerySchema,on as LocalRipgrepQuerySchema,P5 as LocalSearchCodeOutputSchema,yO as LocalToolErrorCategory,Ps as LocalViewStructureBulkQuerySchema,I3 as LocalViewStructureOutputSchema,Pr as LocalViewStructureQuerySchema,XM as LspGetSemanticsOutputSchema,ko as LspGetSemanticsQueryDisplaySchema,DM as LspGetSemanticsQuerySchema,Rv as MAX_BRANCH_CACHE_SIZE,Gr as MAX_CHAR_LENGTH,Fg as MAX_CONTEXT_LINES,Wb as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Si as MAX_DIRECTORY_FILES,Ea as MAX_MATCH_CONTENT_LENGTH,Fce as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,Ta as MAX_PAGE_NUMBER,Lce as MAX_RETRIES,vce as MAX_TIMEOUT,ec as MAX_TOTAL_SIZE,_ce as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,Ace as MIN_RETRIES,Oce as MIN_TIMEOUT,gd as NETWORK_ERROR_PATTERNS,dw as NpmDeprecationOutputSchema,uw as NpmRegistrySearchSchema,Fs as NpmSearchBulkQueryLocalSchema,_Z as NpmSearchOutputLocalSchema,_s as NpmSearchQueryLocalSchema,Dl as NpmViewResultSchema,Hu as OCTOCODE_DIR,et as OCTOCODE_HOME,k9 as OQL_SEARCH,Bn as OQL_SEARCH_TOOL_NAME,By as OctocodeConfigSchema,mv as OctokitWithThrottling,Qn as OqlSearchInputSchema,S9 as PACKAGE_SEARCH,Vo as PROMISE_ERRORS,OR as PROVIDER_CAPABILITIES,DR as PROXY_ENV_VARS,Vt as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,Lg as PR_CONTENT_MAX_ITEMS_PER_PAGE,im as ProviderInitializationError,Ya as RATE_LIMIT_CONFIG,yd as RATE_LIMIT_PATTERNS,yn as REPOSITORY_ERRORS,zt as RESOURCE_LIMITS,pie as RipgrepJsonMessageSchema,Ke as SEARCH_ERRORS,MC as SEMANTIC_CONTENT_TYPES,IW as SENSITIVE_ENV_VARS,er as SESSION_FILE,hO as STARTUP_ERRORS,X as STATIC_TOOL_NAMES,tr as STATS_FILE,tb as STATUS_TO_ERROR_CODE,eie as StatusEmojis,po as TOOLING_ALLOWED_ENV_VARS,gO as TOOL_ERRORS,fO as TOOL_METADATA_ERRORS,v as TOOL_NAMES,ze as ToolError,at as ToolErrors,qo as VALIDATION_ERRORS,Wce as _getCacheState,Rw as _packageNameToSearchKeywords,qce as _resetConfigCache,Joe as _resetMetadataState,ED as _resetNpmRegistryUrlCache,jy as _resetSessionState,gB as _resetTokenResolvers,hB as _setTokenResolvers,$F as applyConfiguredAllowedRoots,cp as applyContentPagination,Lx as applyEntryFilters,pm as applyExactMatchRanking,mc as applyPagination,Di as applyPartialContentFilter,gR as applyStructurePagination,aw as assertCircuitAvailable,V as attachRawResponseChars,c$ as buildBlockBoundaryHint,Nc as buildChildProcessEnv,Cd as buildCodeSearchQuery,Fi as buildDiffPreview,rD as buildDirectToolCommandPatterns,w6 as buildDirectToolExampleQuery,dI as buildEntryPaginationHints,KC as buildExampleValue,mm as buildGhSearchCodeFinalizer,kS as buildGithubFetchContentFinalizer,vd as buildIssueSearchQuery,Am as buildMergedPagination,KD as buildPackagePagination,vm as buildPartialFailureWarnings,sL as buildPullRequestSearchCacheKey,Ed as buildPullRequestSearchQuery,wd as buildRepoSearchQuery,Om as buildResultPagination,VC as buildScalarExampleValue,mx as buildSearchNextMap,Sl as buildSearchResult,Gh as buildToolErrorResult,ps as buildWalkWarnings,Mn as bulkOutputEnvelopeFields,zA as byteSlice,pc as byteToCharIndex,Vb as charToByteIndex,DY as checkLargeOutputSafety,G6 as checkNpmAvailability,Sw as checkNpmDeprecation,kD as checkNpmRegistryReachable,hf as checkRegexSafety,z as clampedInt,ur as cleanJsonObject,yB as cleanup,uz as clearAllCache,pz as clearLSPToolCache,dz as clearLocalToolCache,LB as clearOctokitInstances,aW as clearProviderCache,mz as clearRemoteAPICache,BR as cloneRepo,Qf as collectDisplayFields,Xc as collectFlatErrors,x_ as commonDirPrefix,Df as compactLocation,VD as compactPackageRepositories,an as compactResolvedSymbol,wP as compareIsoDateDescending,ele as completeMetadata,KR as computeQueryTimeout,Nce as configExists,U6 as configureCircuitBreaker,cce as configureSecurity,ao as contextLinesField,t$ as convertByteMatchToChar,Qt as countLines,Q as countSerializedChars,mp as createBasePRTransformation,to as createCacheMeta,qs as createCallItemKey,N as createErrorResult,en as createGitHubProviderError,Oc as createGitHubProviderErrorFromResult,gt as createLazyProviderContext,ap as createPaginationInfo,I_ as createProviderExecutionContext,ge as createRelaxedBulkQuerySchema,Fn as createResponseFormat,pW as createResult,D3 as createSafeRegExp,Ee as createSuccessResult,Ia as decrypt,ry as deleteCredentials,Qy as deleteSession,nD as describeSchemaConstraints,Hf as describeSchemaType,rie as detectEnvironment,Fa as encrypt,Bg as ensureClone,An as ensureCloneParentDir,La as ensureHome,Rn as ensureOctocodeDir,PO as ensureRepos,Gu as ensureTmp,xO as ensureTree,yi as etagSoftCache,oc as evictExpiredClones,Jr as evictExpiredTrees,fe as executeBulkOperation,rS as executeCloneRepo,Qh as executeDirectTool,nx as executeFetchContent,sx as executeFindFiles,Ah as executeLspGetSemantics,zn as executeNpmCommand,gT as executeOqlSearchTool,nn as executeProviderOperation,nS as executeProviderOperations,Ex as executeRipgrepSearch,yx as executeRipgrepSearchInternal,Mx as executeViewStructure,qR as executeWithErrorIsolation,ht as executeWithToolBoundary,FP as exploreMultipleRepositoryStructures,Yr as extractEtag,cc as extractMatchingLines,HP as fallbackOnBestEffortFailure,pl as fetchContent,Bd as fetchDirectoryContents,ji as fetchDirectoryContentsRecursivelyAPI,rp as fetchFileContentToDisk,lp as fetchFileTimestamp,Zb as fetchGitHubFileContentAPI,u1 as fetchGitHubPullRequestByNumberAPI,wp as fetchGitHubPullRequestByNumberAPIInternal,pR as fetchHistory,OS as fetchMultipleGitHubFileContents,ki as fetchRawGitHubFileContent,Ut as fetchWithRetries,eR as filterPatch,zF as filterStructure,Qm as finalizeFetchContentResult,ix as finalizeFindFilesResult,fx as finalizeRipgrepResult,Ix as finalizeViewStructureResult,Er as findDirectToolDefinition,br as findFiles,Li as findNextBlockBoundary,Ly as flushSession,_y as flushSessionSync,iv as formatBytes,mW as formatCallToolResultForOutput,JC as formatDirectToolCommandPattern,l6 as formatDirectToolMetadataSchemaText,p6 as formatDirectToolOutputSchemaText,c6 as formatDirectToolSchemaText,uD as formatDirectToolValidationIssues,Ro as formatFileSize,Jc as formatFinalizedResponse,no as formatPRForResponse,WD as formatPackageData,rY as formatRepoLine,mh as gatherIncomingCallsRecursive,fh as gatherOutgoingCallsRecursive,Te as generateCacheKey,W1 as generatePaginationHints,Tc as generateStructurePaginationHints,pd as getActiveProvider,md as getActiveProviderConfig,my as getAppDataPath,gy as getArchitecture,JU as getBulkDefaultCharLength,Kb as getByteLength,fz as getCacheStats,fA as getCacheTTL,Pi as getCloneBaseDir,Gd as getCloneDir,Hce as getConfig,Ice as getConfigFilePath,Qce as getConfigSync,$ce as getConfigValue,Zn as getCredentials,cy as getCredentialsFilePath,Na as getCredentialsSync,jg as getDefaultOctocodeHome,Fh as getDescription,u6 as getDirectToolAutoFilledFields,Is as getDirectToolCategory,m6 as getDirectToolDescription,Fl as getDirectToolDisplayFields,d6 as getDirectToolOutputFields,ui as getDirectorySizeBytes,mce as getEnvTokenSource,db as getExtension,LR as getFileContent,Ma as getGhCliToken,dd as getGitHubToken,fy as getLocalAppDataPath,iie as getLspEnvironmentHint,hA as getMaxCacheSizeBytes,gA as getMaxCloneCount,Xoe as getMetadataOrNull,Gs as getNpmRegistryUrl,Jn as getOctocodeDir,oe as getOctokit,Fy as getOrCreateSession,Ln as getOutputCharLimit,rb as getOwnerQualifier,hy as getPlatformName,Up as getProvider,ue as getRawResponseChars,Qi as getRecursiveFetchFailureCount,FR as getRepoStructure,tA as getReposBaseDir,Kce as getRuntimeSurface,di as getServerConfig,Iy as getSessionId,ly as getToken,pce as getTokenFromEnv,SB as getTokenSource,uy as getTokenSync,Vu as getTokenWithRefresh,rc as getTreeBaseDir,xi as getTreeDir,Ve as handleCatchError,re as handleGitHubAPIError,Dc as handleProviderError,sy as hasCredentials,ay as hasCredentialsSync,fce as hasEnvToken,c2 as hasExpensiveContentRequest,jf as hasSchemaDefault,pF as hasValidCodeSearchParams,Xy as hashGitHubToken,Qc as hoistSharedFields,QY as ignoreBestEffortFailure,Dy as incrementErrors,qa as incrementGitHubCacheHits,Wa as incrementGitHubCacheRateLimits,Gy as incrementPackageRegistryFailures,Ny as incrementRateLimitByProvider,Ua as incrementRateLimits,My as incrementToolCalls,$a as incrementToolCharSavings,XI as inferLspSymbolName,$y as initialize,MR as initializeProviders,Yoe as initializeToolMetadata,Uce as invalidateConfigCache,ei as invalidateCredentialsCache,AW as invokeCallbackSafely,eo as isCacheHit,kb as isCacheValid,lw as isCircuitOpen,RB as isCloneEnabled,Us as isExactPackageName,Et as isGitHubAPIError,xL as isGitHubAPISuccess,vo as isJsonSchemaObject,Ju as isLinux,bB as isLocalEnabled,xZ as isLocalTool,Xu as isMac,Ai as isMidBlockCut,Ht as isNoResultsSearchError,Ls as isOqlEnabled,__ as isProviderError,Bc as isProviderSuccess,cn as isRecord,Jo as isRefreshTokenExpired,CL as isRepository,Yt as isTokenExpired,Du as isToolError,Yd as isToolInMetadata,ni as isWindows,co as lineNumberField,oy as listStoredHosts,iy as listStoredHostsSync,Mce as loadConfig,Dce as loadConfigSync,Koe as loadToolContent,XL as makeToolResultRowSchema,uS as mapCodeSearchProviderResult,lS as mapCodeSearchToolQuery,RS as mapFileContentProviderResult,bS as mapFileContentToolQuery,gS as mapPullRequestProviderResultData,hS as mapPullRequestToolQuery,mS as mapRepoSearchProviderRepositories,pS as mapRepoSearchToolQuery,PS as mapRepoStructureProviderResult,lm as mapRepoStructureToolQuery,sce as maskSensitiveData,Mi as normalizeOwnerRepo,QS as normalizePullRequestContentRequest,Ri as normalizeResponseHeaders,zm as paginateEntries,us as parseFileSize,Ie as parseGitHubProjectId,oo as parseHasMore,Ue as paths,gx as preflightValidateRipgrepPattern,lD as prepareDirectToolInput,O6 as prepareDirectToolInputFromJsonText,Jb as processFileContentAPI,zc as providerSupports,Qd as readCacheMeta,Jt as readCredentialsStore,cw as recordCircuitFailure,qf as recordCircuitSuccess,qy as recordPackageRegistryFailure,En as recordRateLimit,Yo as redactPath,dy as refreshAuthToken,Hc as relativizeResultPaths,Pe as relaxedPageNumberField,jce as reloadConfig,ic as removeCloneDir,z6 as resetCircuitBreaker,Hy as resetSessionStats,Uu as resetTokenResolution,Ge as resolveCacheAuthFingerprint,Bce as resolveConfig,zce as resolveConfigSync,Ye as resolveDefaultBranch,hce as resolveEnvToken,ah as resolveFileAnchor,$i as resolveQueryId,kw as resolveSymbolAnchor,$u as resolveToken,Pn as resolveTokenFull,qu as resolveTokenWithRefresh,qi as resolveUniqueQueryIds,We as responseEnvelopeFields,lie as safeExec,pt as safeParseOrError,Nh as sanitizeCallToolResult,vt as sanitizeStructuredContent,vR as searchCode,Rt as searchContentRipgrep,hb as searchGitHubCodeAPI,uR as searchGitHubPullRequestsAPI,hR as searchGitHubReposAPI,NS as searchMultipleGitHubCode,yP as searchMultipleGitHubPullRequests,AP as searchMultipleGitHubRepos,nh as searchNpmPackage,xw as searchPackage,ww as searchPackages,_R as searchPullRequests,AR as searchRepos,rce as securityRegistry,o$ as serializeForPagination,Vce as setRuntimeSurface,KS as shapePullRequestForContent,fp as shouldEnrichPullRequestFromSearch,bi as shouldIgnoreDir,Vr as shouldIgnoreFile,oie as shouldUseMCPLsp,Ad as shouldUseSearchForIssues,kd as shouldUseSearchForPRs,i$ as sliceByCharRespectLines,ip as sliceContent,hc as snapToSemanticBoundary,a6 as sortDirectToolNames,NR as spawnCheckSuccess,QW as spawnCollectStdout,tn as spawnWithTimeout,Oi as splitLines,Yz as startCacheGC,Xz as stopCacheGC,Wu as storeCredentials,Bm as summarizeEntries,Fx as toEntryObject,_x as toGroupedLists,Ng as toToolError,kL as transformCodeSearchResult,AL as transformFileContentResult,Ni as transformPullRequestItemFromREST,Cp as transformPullRequestItemFromSearch,FL as transformPullRequestResult,OL as transformRepoSearchResult,ML as transformRepoStructureResult,tR as trimDiffContext,$_ as truncateSnippetChars,ct as updateSessionStats,Ga as updateToken,Gc as validateArgs,Gce as validateConfig,bt as validateToolPath,Ip as viewGitHubRepositoryStructureAPI,Tl as viewStructure,vg as withBasicSecurityValidation,He as withDataCache,Za as withDataCacheConditional,xW as withResponseEnvelope,Og as withSecurityValidation,Zr as writeCacheMeta,nle as z};
|