@octocodeai/octocode-tools-core 16.6.0 → 16.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +179 -249
- package/dist/direct.js +37 -35
- package/dist/errors/localToolErrors.d.ts +1 -0
- package/dist/github/pullRequestSearch.d.ts +1 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.js +39 -44
- package/dist/oql/adapters/graphProof.d.ts +6 -0
- package/dist/oql/adapters/graphView.d.ts +28 -0
- package/dist/oql/adapters/local.d.ts +1 -0
- package/dist/oql/adapters/resultMap.d.ts +7 -0
- package/dist/oql/adapters/runner.d.ts +7 -0
- package/dist/oql/envelope.d.ts +2 -0
- package/dist/oql/index.d.ts +2 -1
- package/dist/oql/index.js +37 -34
- package/dist/oql/schema.d.ts +24 -8
- package/dist/oql/schemeText.d.ts +27 -10
- package/dist/oql/transformers/github/common.d.ts +7 -1
- package/dist/oql/types.d.ts +19 -2
- package/dist/responses.d.ts +4 -35
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +2 -1
- package/dist/scheme/pagination.d.ts +51 -0
- package/dist/scheme/responseEnvelope.d.ts +67 -1
- package/dist/shared/config/index.d.ts +1 -8
- package/dist/shared/config/index.js +1 -2
- package/dist/shared/credentials/index.d.ts +1 -1
- package/dist/shared/credentials/index.js +2 -1
- package/dist/shared/credentials/storage.d.ts +0 -2
- package/dist/shared/credentials/testing.js +1 -1
- package/dist/shared/credentials/types.d.ts +1 -1
- package/dist/shared/paths.d.ts +6 -1
- package/dist/shared/paths.js +1 -1
- package/dist/shared/session/index.js +1 -1
- package/dist/tools/directToolCatalog.exec.d.ts +5 -0
- package/dist/tools/directToolCatalog.meta.d.ts +1 -0
- package/dist/tools/github_clone_repo/scheme.d.ts +0 -1
- package/dist/tools/github_fetch_content/scheme.d.ts +6 -89
- package/dist/tools/github_search_code/scheme.d.ts +4 -6
- package/dist/tools/github_search_pull_requests/scheme.d.ts +0 -1
- package/dist/tools/github_search_repos/execution.d.ts +58 -0
- package/dist/tools/github_search_repos/scheme.d.ts +3 -6
- package/dist/tools/github_view_repo_structure/scheme.d.ts +0 -1
- package/dist/tools/local_binary_inspect/binaryInspector.d.ts +0 -4
- package/dist/tools/local_binary_inspect/scheme.d.ts +97 -0
- package/dist/tools/local_fetch_content/scheme.d.ts +66 -0
- package/dist/tools/local_find_files/scheme.d.ts +49 -0
- package/dist/tools/local_ripgrep/scheme.d.ts +75 -0
- package/dist/tools/local_view_structure/scheme.d.ts +52 -0
- package/dist/tools/lsp/semantic_content/scheme.d.ts +8 -22
- package/dist/tools/lsp/shared/readiness.d.ts +17 -0
- package/dist/tools/lsp/shared/semanticTypes.d.ts +2 -2
- package/dist/tools/package_search/execution.d.ts +23 -0
- package/dist/tools/package_search/scheme.d.ts +10 -4
- package/dist/tools/toolNames.d.ts +2 -1
- package/dist/types/server.d.ts +1 -1
- package/dist/utils/response/bulk.d.ts +1 -0
- package/dist/utils/response/groupedFinalizer.d.ts +7 -2
- package/package.json +7 -3
- package/dist/oql/adapters/v2.d.ts +0 -32
- package/dist/oql/v2params.d.ts +0 -22
- package/dist/shared/config/defaults.d.ts +0 -14
- package/dist/shared/config/loader.d.ts +0 -7
- package/dist/shared/config/resolver.d.ts +0 -2
- package/dist/shared/config/resolverCache.d.ts +0 -12
- package/dist/shared/config/resolverSections.d.ts +0 -10
- package/dist/shared/config/runtimeSurface.d.ts +0 -21
- package/dist/shared/config/types.d.ts +0 -92
- package/dist/shared/config/validator.d.ts +0 -2
- package/dist/shared/credentials/envTokens.d.ts +0 -9
package/dist/index.js
CHANGED
|
@@ -5,58 +5,53 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
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 Zr}from"@octocodeai/octocode-engine/pathUtils";var Lc=y(()=>{"use strict"});var Xe,eo=y(()=>{"use strict";Bi();jn();Lc();Xe={pathValidationFailed:(e,t,n)=>new De($.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Zr(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Zr(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 De($.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new De($.FILE_READ_FAILED,`Failed to read file: ${Zr(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new De($.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 De($.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Zr(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new De($.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new De($.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 De($.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new De($.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});function Pt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function vt(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 to(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Qi=y(()=>{"use strict"});function wP(e){let t=Pt(e),n=no.get(t);return!n||Date.now()-n.cachedAt>=xP?!1:n.credentials?!vt(n.credentials):!0}function ro(e){e?no.delete(Pt(e)):no.clear()}function Pf(e){let t=Pt(e);if(wP(t))return no.get(t).credentials}function xf(e,t){let n=Pt(e);no.set(n,{credentials:t,cachedAt:Date.now()})}var no,xP,wf=y(()=>{"use strict";Qi();no=new Map,xP=300*1e3});import $n from"node:os";import Tf from"node:path";function Ui(){return fn?process.env.APPDATA||Tf.join(At,"AppData","Roaming"):At}function Ef(){return fn?process.env.LOCALAPPDATA||Tf.join(At,"AppData","Local"):At}function kf(){return oo?"macOS":fn?"Windows":_c?"Linux":$n.platform()}function Of(){return $n.arch()}var fn,oo,_c,At,vf=y(()=>{"use strict";fn=$n.platform()==="win32",oo=$n.platform()==="darwin",_c=$n.platform()==="linux",At=$n.homedir()});var ji=y(()=>{"use strict";vf()});import{existsSync as qn,mkdirSync as Vn}from"node:fs";import{join as ke}from"node:path";function TP(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function Af(){return fn?ke(Ui(),Ic):oo?ke(At,Ic):ke(TP("XDG_CONFIG_HOME")??ke(At,".config"),Ic)}function $i(){qn(ne.home)||Vn(ne.home,{recursive:!0,mode:Wn})}function EP(){Lf()}function io(){$i(),qn(ne.tmp)||Vn(ne.tmp,{recursive:!0,mode:Wn})}function Lf(){io(),qn(ne.clone)||Vn(ne.clone,{recursive:!0,mode:Wn})}function kP(){io(),qn(ne.tree)||Vn(ne.tree,{recursive:!0,mode:Wn})}function OP(){io(),qn(ne.binary)||Vn(ne.binary,{recursive:!0,mode:Wn})}function vP(){io(),qn(ne.unzip)||Vn(ne.unzip,{recursive:!0,mode:Wn})}var Ic,Wn,Ne,ne,mn=y(()=>{"use strict";ji();Ic=".octocode",Wn=448;Ne=Af(),ne={home:Ne,config:ke(Ne,".octocoderc"),credentials:ke(Ne,"credentials.json"),key:ke(Ne,".key"),session:ke(Ne,"session.json"),stats:ke(Ne,"stats.json"),tmp:ke(Ne,"tmp"),clone:ke(Ne,"tmp","clone"),tree:ke(Ne,"tmp","tree"),binary:ke(Ne,"tmp","binary"),repos:ke(Ne,"tmp","clone"),unzip:ke(Ne,"tmp","unzip"),cliConfig:ke(Ne,"config.json"),lspConfig:ke(Ne,"lsp-servers.json")}});import{z as we}from"zod";var AP,LP,_f,If=y(()=>{"use strict";AP=we.object({token:we.string(),tokenType:we.literal("oauth"),scopes:we.array(we.string()).optional(),refreshToken:we.string().optional(),expiresAt:we.string().optional(),refreshTokenExpiresAt:we.string().optional()}),LP=we.object({hostname:we.string(),username:we.string(),token:AP,gitProtocol:we.enum(["ssh","https"]),createdAt:we.string(),updatedAt:we.string()}),_f=we.object({version:we.number(),credentials:we.record(we.string(),LP)})});import{existsSync as qi,readFileSync as Mf,writeFileSync as Df,unlinkSync as Ff,statSync as _P,chmodSync as IP}from"node:fs";import{createCipheriv as FP,createDecipheriv as MP,randomBytes as Nf}from"node:crypto";function $t(){$i()}function Hf(){if($t(),qi(xt))return _P(xt).mode&511&63&&IP(xt,384),Buffer.from(Mf(xt,"utf8"),"hex");let e=Nf(32);return Df(xt,e.toString("hex"),{mode:384}),e}function Vi(e){let t=Hf(),n=Nf(DP),r=FP(Gf,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 Wi(e){let t=Hf(),[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=MP(Gf,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function _t(){if($t(),!qi(Lt))return{version:1,credentials:{}};try{let e=Mf(Lt,"utf8"),t=Wi(e),n=JSON.parse(t),r=_f.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Mc(e){$t();let t=Vi(JSON.stringify(e,null,2));Df(Lt,t,{mode:384})}function zf(){try{qi(Lt)&&Ff(Lt),qi(xt)&&Ff(xt)}catch{}}var Fc,Lt,xt,Gf,DP,Bf=y(()=>{"use strict";mn();If();Fc=ne.home,Lt=ne.credentials,xt=ne.key,Gf="aes-256-gcm",DP=16});var Kn,qt,Dc=y(()=>{"use strict";Kn="178c6fc778ccc68e1d6a",qt="github.com"});import{refreshToken as NP}from"@octokit/oauth-methods";import{request as GP}from"@octokit/request";function HP(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 zP(e){return e==="github.com"||e===qt?"https://api.github.com":`https://${e}/api/v3`}async function Nc(e,t=qt,n=Kn){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(to(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await NP({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:GP.defaults({baseUrl:zP(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?HP(o.message):"Token refresh failed"}}}async function Qf(e,t=qt,n=Kn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!vt(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Nc(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 Uf=y(()=>{"use strict";Qi();Dc()});function Ki(){for(let e of Yn){let t=process.env[e];if(t&&t.trim())return t.trim()}return null}function Gc(){for(let e of Yn){let t=process.env[e];if(t&&t.trim())return`env:${e}`}return null}function Hc(){return Ki()!==null}function jf(){for(let e of Yn){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}var Yn,zc=y(()=>{"use strict";Yn=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN"]});import{execFile as BP}from"child_process";function Yi(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=QP.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;BP("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var QP,Bc=y(()=>{"use strict";QP=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function $f(e){Xi=e}function Qc(){Xi=null}function UP(){if(!Xi)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Xi}async function Vt(e){let t=e?.hostname??qt,n=e?.clientId??Kn,r=e?.getGhCliToken??Yi,o=jf();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await UP().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch{}return null}async function Uc(e=qt){let t=await Vt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function jc(e=qt,t=Kn){let n=await Vt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var Xi,qf=y(()=>{"use strict";zc();Bc();Dc();Xi=null});async function $c(e){let t=Pt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=_t();return r.credentials[t]=n,Mc(r),ro(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function gn(e="github.com",t){let n=Pt(e);if(!t?.bypassCache){let i=Pf(n);if(i!==void 0)return i}let o=_t().credentials[n]||null;return xf(n,o),o}function Ji(e="github.com"){let t=Pt(e);return _t().credentials[t]||null}async function Vf(e="github.com"){let t=Pt(e),n=!1,r=_t();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?zf():Mc(r),n=!0),ro(t),{success:n,deletedFromFile:n}}async function Wf(){let e=_t();return Object.keys(e.credentials)}function Kf(){let e=_t();return Object.keys(e.credentials)}async function Yf(e="github.com"){return await gn(e)!==null}function Xf(e="github.com"){return Ji(e)!==null}async function Zi(e,t){let n=await gn(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await $c(n),!0):!1}function Jf(){return Lt}async function Zf(e="github.com"){let t=await gn(e);return!t||!t.token||vt(t)?null:t.token.token}function em(e="github.com"){let t=Ji(e);return!t||!t.token||vt(t)?null:t.token.token}async function tm(e,t){return Nc({getCredentials:gn,updateToken:Zi},e,t)}async function qc(e,t){return Qf({getCredentials:gn,updateToken:Zi},e,t)}var Vc=y(()=>{"use strict";wf();Bf();Uf();qf();zc();Qi();$f({getTokenWithRefresh:qc})});var Wc=y(()=>{"use strict";Vc();Bc()});import{z as K}from"zod";var jP,$P,es,qP,ts,nm,rm,om=y(()=>{"use strict";jP=K.object({rawChars:K.number(),responseChars:K.number(),savedChars:K.number(),calls:K.number()}),$P=K.object({hits:K.record(K.string(),K.number()).default({}),rateLimits:K.number().default(0)}),es=K.record(K.string(),K.number()).default({}),qP=K.object({toolCalls:K.number(),errors:K.number(),rateLimits:K.number(),rateLimitsByProvider:es,rawChars:K.number(),responseChars:K.number(),savedChars:K.number(),charSavingsCalls:K.number(),githubCacheHits:K.number(),githubCacheRateLimits:K.number(),packageRegistryFailures:K.number().default(0),packageRegistryFailuresByRegistry:es}),ts=K.object({toolCalls:K.number(),errors:K.number(),rateLimits:K.number(),rateLimitsByProvider:es,charsSavedByTool:K.record(K.string(),jP).default({}),githubCacheHits:$P.default({hits:{},rateLimits:0}),packageRegistryFailures:es,totalUsage:qP.optional()}),nm=K.object({version:K.literal(1),sessionId:K.string(),createdAt:K.string(),lastActiveAt:K.string(),stats:ts.optional()}),rm=K.object({version:K.literal(1),stats:ts})});function im(e){return Object.values(e).reduce((t,n)=>t+n,0)}function VP(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:im(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:im(o),packageRegistryFailuresByRegistry:o}}function It(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:VP(t)}}function so(){return It({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Kc=y(()=>{"use strict"});import{existsSync as Yc,readFileSync as am,writeFileSync as WP,unlinkSync as KP,renameSync as YP}from"node:fs";function sm(e,t){let n=`${e}.tmp`;WP(n,JSON.stringify(t,null,2),{mode:384}),YP(n,e)}function XP(e){let{stats:t,...n}=e;return n}function JP(e){let t=JSON.parse(e),n=rm.safeParse(t);if(n.success)return It(n.data.stats);let r=ts.safeParse(t);return r.success?It(r.data):null}function ZP(e){let t=e?It(e):so();if(!Yc(yn))return t;try{let n=am(yn,"utf8"),r=JP(n);return r||t}catch{return t}}function ns(e){$t(),sm(yn,{version:e.version,stats:It(e.stats)}),sm(hn,XP(e))}function cm(){if(!Yc(hn))return null;try{let e=am(hn,"utf8"),t=JSON.parse(e),n=nm.safeParse(t);return n.success?{...n.data,stats:ZP(n.data.stats)}:null}catch{return null}}function lm(){let e=!1;for(let t of[hn,yn])if(Yc(t))try{KP(t),e=!0}catch{return!1}return e}var hn,yn,rs=y(()=>{"use strict";Vc();mn();om();Kc();hn=ne.session,yn=ne.stats});function tx(){Xc||(Xc=!0,ao=()=>{uo()},co=()=>{uo()},lo=()=>{uo()},process.on("exit",ao),process.on("SIGINT",co),process.on("SIGTERM",lo))}function Jc(){ao&&(process.removeListener("exit",ao),ao=null),co&&(process.removeListener("SIGINT",co),co=null),lo&&(process.removeListener("SIGTERM",lo),lo=null),Xc=!1}function nx(){Xn||(Xn=setInterval(()=>{Wt&&mt&&(ns(mt),Wt=!1)},ex),Xn.unref())}function Zc(){Xn&&(clearInterval(Xn),Xn=null)}function po(){if(mt)return mt;let e=cm();return e&&(mt=e),e}function Jn(e){mt=e,Wt=!0,tx(),nx()}function fo(){Wt&&mt&&(ns(mt),Wt=!1)}function uo(){if(!os&&Wt&&mt){os=!0;try{ns(mt),Wt=!1}catch{}finally{os=!1}}}function el(){mt=null,Wt=!1,os=!1}function um(){el(),Zc(),Jc()}var ex,mt,Wt,Xn,Xc,ao,co,lo,os,dm=y(()=>{"use strict";rs();ex=6e4,mt=null,Wt=!1,Xn=null,Xc=!1,ao=null,co=null,lo=null,os=!1});import{randomUUID as rx}from"node:crypto";function ix(e){return It(e)}function sx(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 pm(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 ax(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 fm(){let e=new Date().toISOString();return{version:ox,sessionId:rx(),createdAt:e,lastActiveAt:e,stats:so()}}function mm(){fo()}function gm(){uo()}function hm(e){if(e?.forceNew){let r=fm();return Jn(r),fo(),r}let t=po();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return Jn(r),fo(),r}let n=fm();return Jn(n),fo(),n}function ym(){return po()?.sessionId??null}function Je(e){let t=po();if(!t)return{success:!1,session:null};let n=ix(t.stats),r=It({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:pm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:sx(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:ax(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:pm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Jn(o),{success:!0,session:o}}function bm(e=1){return Je({toolCalls:e})}function Rm(e=1){return Je({errors:e})}function is(e=1){return Je({rateLimits:e})}function Sm(e,t=1){return Je({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function ss(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Je({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function as(e,t=1){return Je({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function cs(e=1){return Je({githubCacheHits:{hits:{},rateLimits:e}})}function Cm(e,t=1){return Je({packageRegistryFailures:{[e]:t}})}function Pm(){let e=po();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:so()};return Jn(t),{success:!0,session:t}}function xm(){return el(),Zc(),Jc(),lm()}function wm(){um()}var ox,mo=y(()=>{"use strict";rs();Kc();dm();rs();ox=1});var tl=y(()=>{"use strict";mo();mo();mo();mo()});var go,Tm,nl=y(()=>{"use strict";go=1,Tm=".octocoderc"});var ho,Kt,bn,Zn,yo,Ft,ls,er,tr,nr,rr,or,ir,bo=y(()=>{"use strict";ho={apiUrl:"https://api.github.com"},Kt={enabled:!1,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},bn={enabled:null,enableAdditional:null,disabled:null},Zn={timeout:3e4,maxRetries:3},yo={configPath:void 0},Ft={format:"yaml",pagination:{defaultCharLength:2e4}},ls={version:1,github:ho,local:Kt,tools:bn,network:Zn,lsp:yo,output:Ft},er=5e3,tr=3e5,nr=0,rr=10,or=1e3,ir=5e4});import{z as ye}from"zod";var us,rl=y(()=>{"use strict";us=ye.looseObject({$schema:ye.string().optional(),version:ye.number().int().optional(),github:ye.record(ye.string(),ye.unknown()).optional(),local:ye.record(ye.string(),ye.unknown()).optional(),tools:ye.record(ye.string(),ye.unknown()).optional(),network:ye.record(ye.string(),ye.unknown()).optional(),lsp:ye.record(ye.string(),ye.unknown()).optional(),output:ye.record(ye.string(),ye.unknown()).optional()})});import{existsSync as Em,readFileSync as cx}from"node:fs";function lx(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
|
|
10
|
-
`;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t=t.replace(/,(\s*[}\]])/g,"$1"),t}function ux(e){let t=lx(e);return JSON.parse(t)}function km(){return Em(Ro)}async function Om(){return So()}function So(){let e=Ro;if(!Em(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=cx(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=ux(t),r=us.safeParse(n);return r.success?{success:!0,config:r.data,path:e}:{success:!1,error:`Config file has invalid structure: ${r.error.issues[0]?.message??"unknown error"}`,path:e}}catch(t){return{success:!1,error:`Failed to parse config file: ${t instanceof Error?t.message:"Unknown error"}`,path:e}}}function vm(){return Ro}function Rn(){return ne.home}var Ro,ds=y(()=>{"use strict";mn();rl();Ro=ne.config});function dx(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function il(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Am(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function Lm(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function px(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function ol(e,t){return e===void 0||e===null?null:Lm(e,t)}function _m(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function fx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=dx(e.apiUrl,"github.apiUrl");r&&t.push(r)}function mx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Am(n.enabled,"local.enabled");r&&t.push(r);let o=Am(n.enableClone,"local.enableClone");o&&t.push(o);let i=Lm(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=px(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=_m(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function gx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=ol(n.enabled,"tools.enabled");r&&t.push(r);let o=ol(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=ol(n.disabled,"tools.disabled");i&&t.push(i)}function hx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=il(n.timeout,"network.timeout",er,tr);r&&t.push(r);let o=il(n.maxRetries,"network.maxRetries",nr,rr);o&&t.push(o)}function yx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=_m(e.configPath,"lsp.configPath");r&&t.push(r)}function bx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=il(r.defaultCharLength,"output.pagination.defaultCharLength",or,ir);o&&t.push(o)}}function ps(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>1&&n.push(`version: Config version ${r.version} is newer than supported version ${1}`)),fx(r.github,t),mx(r.local,t),gx(r.tools,t),hx(r.network,t),yx(r.lsp,t),bx(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}var sl=y(()=>{"use strict";nl();bo()});function al(){return globalThis[Rx]??"mcp"}var Rx,cl=y(()=>{"use strict";Rx="__octocodeRuntimeSurface__"});function Im(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function ll(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function fs(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function Fm(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||ho.apiUrl}}function Mm(e){let t=al()==="cli",n=Im(process.env.ENABLE_LOCAL),r=Im(process.env.ENABLE_CLONE),o=fs(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:t?!0:n??e?.enabled??Kt.enabled,enableClone:r??e?.enableClone??(t?!0:Kt.enableClone),allowedPaths:o??e?.allowedPaths??Kt.allowedPaths,workspaceRoot:i??e?.workspaceRoot??Kt.workspaceRoot}}function Dm(e){let t=fs(process.env.TOOLS_TO_RUN),n=fs(process.env.ENABLE_TOOLS),r=fs(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??bn.enabled,enableAdditional:n??e?.enableAdditional??bn.enableAdditional,disabled:r??e?.disabled??bn.disabled}}function Nm(e){let t=ll(process.env.REQUEST_TIMEOUT),n=ll(process.env.MAX_RETRIES),r=t??e?.timeout??Zn.timeout;r=Math.max(er,Math.min(tr,r));let o=n??e?.maxRetries??Zn.maxRetries;return o=Math.max(nr,Math.min(rr,o)),{timeout:r,maxRetries:o}}function Gm(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??yo.configPath}}function Hm(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=ll(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||Ft.format,o=n??e?.pagination?.defaultCharLength??Ft.pagination.defaultCharLength,i=Math.max(or,Math.min(ir,o));return{format:Sx.has(r)?r:Ft.format,pagination:{defaultCharLength:i}}}var Sx,zm=y(()=>{"use strict";bo();cl();Sx=new Set(["yaml","json"])});function ul(e,t){let n=e!==void 0,r=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??ls.version,github:Fm(e?.github),local:Mm(e?.local),tools:Dm(e?.tools),network:Nm(e?.network),lsp:Gm(e?.lsp),output:Hm(e?.output),source:o,configPath:n?t:void 0}}function Po(){let e=So();return e.success&&e.config&&ps(e.config).valid?ul(e.config,e.path):ul(void 0)}async function dl(){return Po()}function ge(){let e=Date.now();return Sn&&e-Co<Cx||(Sn=Po(),Co=e),Sn}async function ms(){return ge()}async function pl(){return sr(),ms()}function sr(){Sn=null,Co=0}function fl(){Sn=null,Co=0}function ml(){return{cached:Sn!==null,timestamp:Co}}var Sn,Co,Cx,gl=y(()=>{"use strict";bo();ds();sl();zm();Sn=null,Co=0,Cx=6e4});function Bm(e){let t=ge(),n=e.split("."),r=t;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}var Qm=y(()=>{"use strict";gl();gl()});var hl=y(()=>{"use strict";nl();bo();ds();ds();sl();Qm();cl();rl()});import{existsSync as Px,readdirSync as xx,lstatSync as wx}from"node:fs";import{join as Tx}from"node:path";function xo(e){if(!Px(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=xx(r)}catch{continue}for(let i of o){let s=Tx(r,i);try{let a=wx(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function Ex(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 yl=y(()=>{"use strict"});var Ae=y(()=>{"use strict";Wc();ji();tl();hl();mn();yl()});var Cn,gs=y(()=>{Cn="16.6.0"});import{maskSensitiveData as Ox}from"@octocodeai/octocode-engine/mask";function AH(e){e.resolveTokenFull&&(bl=e.resolveTokenFull)}function LH(){bl=Vt}async function Rl(){try{let e=await bl({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:vx.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Um(){if(cr!==null)return;if(ar!==null)return ar;let e=(async()=>{let t=ge(),n=await Rl();cr={version:Cn,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}})();ar=e;try{await e}catch(t){throw ar===e&&(cr=null,ar=null),t}}function _H(){cr=null,ar=null,sr()}function hs(){if(!cr){let e=Ox(vc.NOT_INITIALIZED.message);throw new Error(e)}return cr}async function jm(){return(await Rl()).token}function IH(){return hs().enableLocal}function FH(){let e=hs();return e.enableLocal&&e.enableClone}async function MH(){return(await Rl()).source}function Sl(){return"github"}function Cl(){let e=ge().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var cr,ar,bl,vx,lr=y(()=>{"use strict";Ae();gs();ft();cr=null,ar=null,bl=Vt;vx=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"])});function Yt(e){(e.provider?Je({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):is(1)).session&&e.provider==="github"&&cs(1)}function $m(e){Je({packageRegistryFailures:{[e]:1}})}var wo=y(()=>{"use strict";Ae()});import{Octokit as Ax}from"octokit";import{throttling as Lx}from"@octokit/plugin-throttling";import{createHash as _x}from"crypto";function Ix(e){return _x("sha256").update(e).digest("hex").substring(0,16)}function xl(e){return Date.now()-e.createdAt>Mx}function Xm(){for(let[e,t]of it.entries())xl(t)&&it.delete(e);if(it.size>Pl){let e=[...it.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=it.size-Pl;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&it.delete(r[0])}}}function Nx(){Xt||(Xt=setInterval(Xm,Dx),typeof Xt=="object"&&"unref"in Xt&&Xt.unref())}function Wm(e,t,n){Yt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function Km(e){let t=hs(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Cn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:Gx(),log:r,...e&&{auth:e}};return new Fx(o)}async function pe(e){if(Nx(),e?.token){let n=Ix(e.token),r=it.get(n);if(r&&!xl(r))return r.client;it.size>=Pl&&Xm();let o=Km(e.token);return it.set(n,{client:o,createdAt:Date.now()}),o}let t=it.get("DEFAULT");return t&&!xl(t)?t.client:ur||(ur=(async()=>{try{let n=await jm(),r=Km(n??void 0);return it.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{ur=null}})(),ur)}async function Ze(e,t,n){let r=`${e}/${t}`,o=dr.get(r);if(o)return o;let i=await pe(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Ym(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}),Ym(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 Ym(e,t){if(dr.size>=Hx){let n=dr.keys().next().value;n!==void 0&&dr.delete(n)}dr.set(e,t)}function qH(){it.clear(),ur=null,dr.clear(),Xt&&(clearInterval(Xt),Xt=null)}var Fx,Mx,Pl,Dx,it,ur,Xt,qm,Vm,Gx,Hx,dr,Ge=y(()=>{"use strict";lr();lr();gs();wo();Fx=Ax.plugin(Lx),Mx=300*1e3,Pl=50,Dx=60*1e3;it=new Map,ur=null,Xt=null;qm=3,Vm=60;Gx=()=>({onRateLimit:(e,t,n,r)=>(Wm("primary",e,t),r<qm&&e<Vm),onSecondaryRateLimit:(e,t,n,r)=>(Wm("secondary",e,t),r<qm&&e<Vm)});Hx=200,dr=new Map});import{createRequire as zx}from"node:module";function X(){if(ys)return ys;try{return ys=Qx(),ys}catch(e){throw new wl(e)}}var Bx,Jm,ys,Qx,wl,F,be=y(()=>{"use strict";Bx=zx(import.meta.url),Jm="@octocodeai/octocode-engine",Qx=()=>Bx(Jm),wl=class extends Error{constructor(n){super(`Failed to load native dependency ${Jm}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};F={applyContentViewMinification(e,t){return X().applyContentViewMinification(e,t)},applyMinification(e,t){return X().applyMinification(e,t)},minifyContent(e,t){return X().minifyContent(e,t)},minifyContentSync(e,t){return X().minifyContentSync(e,t)},minifyContentResult(e,t){return X().minifyContentResult(e,t)},minifyMarkdownCore(e){return X().minifyMarkdownCore(e)},extractSignatures(e,t){return X().extractSignatures(e,t)},extractJsSymbols(e,t){return X().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return X().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return X().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return X().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return X().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return X().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return X().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return X().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return X().getSupportedStructuralExtensions()},inspectBinaryNative(e){return X().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return X().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return X().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return X().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return X().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return X().parseRipgrepJson(e,t)},searchRipgrep(e){return X().searchRipgrep(e)},queryFileSystem(e){return X().queryFileSystem(e)},extractMatchingLines(e,t,n){return X().extractMatchingLines(e,t,n)},filterPatch(e,t){return X().filterPatch(e,t)},charToByteOffset(e,t){return X().charToByteOffset(e,t)},byteToCharOffset(e,t){return X().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return X().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return X().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return X().SIGNATURES_ONLY_HINT}}});var q,Se,Zm,Tl,El,bs,kl=y(()=>{"use strict";q={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"},Se={[q.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."},[q.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."},[q.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},[q.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)."},[q.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."},[q.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."},[q.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."},[q.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."},[q.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."},[q.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Zm={401:q.AUTH_REQUIRED,403:q.FORBIDDEN_PERMISSIONS,404:q.NOT_FOUND,422:q.INVALID_REQUEST,502:q.SERVER_UNAVAILABLE,503:q.SERVER_UNAVAILABLE,504:q.SERVER_UNAVAILABLE},Tl={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},El={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},bs={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as eg}from"octokit";function Pn(e){if(!(e instanceof eg)||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 Ux.some(o=>r.includes(o))})}function re(e){return e instanceof eg?jx(e):e instanceof Error?Jx(e):{error:typeof e=="string"?e:Se[q.UNKNOWN].message,type:"unknown"}}function jx(e){let{status:t,message:n,response:r}=e;if(t===403)return qx(n,r);if(t===429)return $x(n,r);let o=Zm[t];return o?Xx(o,t):pr(q.UNKNOWN,{error:n||Se[q.UNKNOWN].message,status:t})}function Ol(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function $x(e,t){let n=t?.headers,r=Ol(n,"retry-after"),o=Ol(n,"x-ratelimit-reset"),i=Ol(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+bs.RESET_BUFFER_SECONDS,0):void 0);return Yt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),pr(q.RATE_LIMIT_PRIMARY,{error:e||Se[q.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Se[q.RATE_LIMIT_PRIMARY].suggestion})}function qx(e,t){let n=t?.headers;if(El.SECONDARY.test(e))return Vx(n);let r=n?.["x-ratelimit-remaining"],o=Yx(t);return r!==void 0&&String(r)==="0"||o?Wx(n):Kx(n)}function Vx(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?bs.SECONDARY_FALLBACK_SECONDS:t;return Yt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),pr(q.RATE_LIMIT_SECONDARY,{error:Se[q.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Se[q.RATE_LIMIT_SECONDARY].suggestion})}function Wx(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)+bs.RESET_BUFFER_SECONDS,0):void 0,i=r?Se[q.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Se[q.RATE_LIMIT_PRIMARY].messageWithoutTime;return Yt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),pr(q.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Se[q.RATE_LIMIT_PRIMARY].suggestion})}function Kx(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Se[q.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Zx(String(t),String(n))),pr(q.FORBIDDEN_PERMISSIONS,{error:Se[q.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Yx(e){return e?.data?.errors?.some(n=>n.type===El.GRAPHQL_TYPE)??!1}function Xx(e,t){let n=Se[e];return pr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function Jx(e){return Tl.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Se[q.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Se[q.NETWORK_CONNECTION_FAILED].suggestion}:Tl.TIMEOUT.some(t=>e.message.includes(t))?{error:Se[q.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Se[q.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function pr(e,t){return{type:"http",...t}}function Zx(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?Se[q.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Se[q.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var Ux,wt=y(()=>{"use strict";kl();wo();Ux=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function ew(e){return`user:${e}`}function tg(e){return e.startsWith('"')||rw.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function ng(e){return new vl().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function rg(e){return new Al().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function og(e){return new Ll().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function ig(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 tw,nw,rw,To,vl,Al,Ll,Eo=y(()=>{"use strict";tw=/[@/]/,nw=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,rw=/^[A-Za-z0-9_-]+$/;To=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(ew(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=tw.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},vl=class extends To{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(tg))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(nw):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}},Al=class extends To{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(tg)),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}},Ll=class extends To{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}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});import ow from"node-cache";import iw from"crypto";function cw(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function lw(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function uw(e){let t=cw(e);if(!(!t||!lw(t)))try{as(t,1)}catch{}}function dw(){let e=Date.now();for(let[t,n]of fr.entries())e-n.startedAt>aw&&fr.delete(t)}function fw(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(pw.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function He(e,t,n){let r=_l(fw(t)),o=n?`${n}:${r}`:r,i=iw.createHash("sha256").update(o).digest("hex");return`${sw}-${e}:${i}`}function _l(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=>_l(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${_l(i,t)}`}).join(",")}}`)}function mw(e){return sg[e]||sg.default}function gw(e,t,n){try{return st.set(e,t,n),Le.sets++,Le.totalKeys=st.keys().length,!0}catch{try{let r=st.keys();for(let o of r)st.get(o);return st.set(e,t,n),Le.sets++,Le.totalKeys=st.keys().length,!0}catch{return!1}}}async function ze(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=st.get(e);if(i!==void 0)return Le.hits++,uw(e),i}catch{}dw();let r=fr.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Le.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=mw(l)}gw(e,i,a)}return i}finally{fr.delete(e)}})();return fr.set(e,{promise:o,startedAt:Date.now()}),o}function iz(){st.flushAll(),fr.clear(),Le.hits=0,Le.misses=0,Le.sets=0,Le.totalKeys=0,Le.lastReset=new Date}function Jt(e){let t=st.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||st.del(r)>0&&n++}return n>0&&(Le.totalKeys=st.keys().length),n}function sz(){return Jt("local-")}function az(){return Jt("lsp-")}function cz(){let e=0;return e+=Jt("gh-api-"),e+=Jt("bb-api-"),e+=Jt("gh-repo-"),e+=Jt("bb-repo-"),e+=Jt("github-user"),e+=Jt("npm-search"),e}function lz(){let e=Le.hits+Le.misses;return{...Le,hitRate:e>0?Le.hits/e*100:0,cacheSize:st.keys().length}}var sw,aw,st,Le,sg,fr,pw,Mt=y(()=>{"use strict";Ae();sw="v1",aw=300*1e3,st=new ow({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Le={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},sg={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},fr=new Map;pw=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as fz,DISCOVERY_IGNORED_FILE_NAMES as mz,DISCOVERY_IGNORED_FOLDER_NAMES as gz,getDiscoveryExtension as ag,shouldIgnoreDiscoveryDir as ko,shouldIgnoreDiscoveryFile as mr}from"@octocodeai/octocode-engine/security";var gr=y(()=>{"use strict"});function U(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function lg(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function j(e,t){let n=typeof t=="number"?lg(t):U(t);if(n===void 0)return e;try{Object.defineProperty(e,cg,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function le(e){if(!(typeof e!="object"||e===null))return lg(e[cg])}var cg,oe=y(()=>{"use strict";cg=Symbol.for("octocode.rawResponseChars")});function Rs(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var Ss=y(()=>{"use strict"});import{ContentSanitizer as hw}from"@octocodeai/octocode-engine/contentSanitizer";async function dg(e,t,n){let r=He("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await ze(r,async()=>await yw(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function yw(e,t){try{let n=await pe(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(S=>S&&S.trim()).length===0)return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let r=ng(e);if(!r.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:ug,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 bw(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),p=Math.min(Math.ceil(d/o),10),f=Math.min(i,Math.max(1,p)),m=f<p,g=Math.min(d,p*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:f,totalPages:p,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:m,...m?{nextPage:f+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Rs(a.headers),rawResponseChars:U(a.data)}}catch(n){if(Pn(n)){let o=Math.min(typeof e.limit=="number"?e.limit:ug,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 bw(e,t){let n=Rw(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!mr(f.path)),c=0,l=0,u=await Promise.allSettled(a.map(async f=>{s.add(f.path);let m=[],g=await Promise.allSettled((f.text_matches||[]).map(async _=>{let E=_.fragment,O=hw.sanitizeContent(E||"",f.path);E=O.content,O.hasSecrets&&r.add(`Secrets detected in ${f.path}: ${O.secretsDetected.join(", ")}`),O.warnings.length>0&&O.warnings.forEach(w=>r.add(`${f.path}: ${w}`));try{let w=await F.minifyContent(E||"",f.path);E=w.content,w.failed?o=!0:w.type!=="failed"&&(m.push(w.type),i.push(w.type))}catch{o=!0}return{context:E||"",positions:_.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),b=g.filter(_=>_.status==="fulfilled").map(_=>_.value),S=g.filter(_=>_.status==="rejected").length;S>0&&(l+=S);let C=f,k=Array.from(new Set(m));return{path:f.path,matches:b,url:f.html_url,repository:{nameWithOwner:f.repository.full_name,url:f.repository.url,pushedAt:f.repository.pushed_at||void 0},...C.last_modified_at&&{lastModifiedAt:C.last_modified_at},...k.length>0&&{minificationType:k.join(",")}}})),d=u.filter(f=>f.status==="fulfilled").map(f=>f.value);c=u.filter(f=>f.status==="rejected").length;let p={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let f=n.full_name.split("/");return f.length===2&&f[0]&&f[1]?{owner:f[0],repo:f[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(p.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&&(p.matchLocations=Array.from(r)),p.minified=!o,p.minificationFailed=o,i.length>0&&(p.minificationTypes=Array.from(new Set(i))),p}function Rw(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 ug,Il=y(()=>{"use strict";be();Ge();wt();Eo();Mt();gr();ft();oe();Ss();me();ug=30});import{completeMetadata as Fl}from"@octocodeai/octocode-core";var A,Ml=y(()=>{"use strict";A=new Proxy({},{get(e,t){return Fl.toolNames[t]},ownKeys(){return Object.keys(Fl.toolNames)},getOwnPropertyDescriptor(e,t){let n=Fl.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as Sw}from"@octocodeai/octocode-core";var Dl,Nl=y(()=>{"use strict";Dl=new Proxy({},{get(e,t){return Sw.tools[t]?.description??""}})});import{completeMetadata as Cw}from"@octocodeai/octocode-core";function Gl(e){return Object.prototype.hasOwnProperty.call(Cw.tools,e)}var Hl=y(()=>{"use strict"});import{completeMetadata as Pw}from"@octocodeai/octocode-core";function zl(){return Pw.baseSchema}var xw,Bl=y(()=>{"use strict";xw=new Proxy({},{get(e,t){return zl()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(zl())]))},getOwnPropertyDescriptor(e,t){let n=zl();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var fe=y(()=>{"use strict";Ml();Nl();Hl();Bl()});import{RequestError as pg}from"octokit";async function ww(e,t,n,r,o,i,s,a){let c=await Ze(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?`,p=await hg(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...gg(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function Tw(e,t,n,r,o,i){let s=re(t),a=await hg(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...gg(o,a)]),s}async function fg(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:jt.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:jt.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:jt.DECODE_FAILED.message,type:"unknown",status:422}}}async function mg(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"?fg(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 Ew(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 Ze(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(p=>p.name===a&&p.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await mg(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 Cs(e,t){try{let n=await pe(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof pg&&d.status===404)if(s){let p=await ww(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await Tw(n,d,r,o,i,s);else{if(d instanceof pg&&d.status===413)return await Ew(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:jt.PATH_IS_DIRECTORY.message(A.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in u&&u.type==="file"){let d=typeof u.content=="string"?u.content:"",p=u.size??0,f;if(d.length>0)f=await fg(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await mg(n,r,o,u.sha,i);else return{error:jt.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await Ze(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:U(u)}}return{error:jt.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return re(n)}}function gg(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 hg(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(f=>f.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(f=>f.name===s?!1:!!f.name.startsWith(d+".")).forEach(f=>l.push(f.path)),l.length===0&&d.length>=3&&c.filter(m=>{let g=m.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(m=>l.push(m.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var Ps=y(()=>{"use strict";Ge();wt();fe();ft();oe()});import{existsSync as Lo,readFileSync as kw,writeFileSync as Ow,mkdirSync as vw,rmSync as vo,readdirSync as Aw,statSync as Lw}from"node:fs";import{join as at}from"node:path";import{createHash as _w}from"node:crypto";function tB(e){return Ql(e)}function Ql(e){return at(e,"tmp","clone")}function Rg(e){return at(e,"tmp","tree")}function Nw(e){return e?`__sp_${_w("sha256").update(e).digest("hex").substring(0,6)}`:""}function Sg(e,t,n,r,o){let i=`${r}${Nw(o)}`;return at(Ql(e),t,n,i)}function Ul(e,t,n,r){return at(Rg(e),t,n,r)}function Gw(e){return typeof e=="object"&&e!==null}function Hw(e){if(!Gw(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 jl(e){let t=at(e,bg);if(!Lo(t))return null;try{return Hw(JSON.parse(kw(t,"utf-8")))}catch{return null}}function _o(e,t){try{Ow(at(e,bg),JSON.stringify(t,null,2),"utf-8")}catch{}}function Cg(e){return Date.now()<new Date(e.expiresAt).getTime()}function Io(e){let t=jl(e);return t?Cg(t)?Lo(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function zw(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Iw}function Bw(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Mw}function Qw(){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 Dw}function Fo(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+zw()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function wn(e){let t=at(e,"..");try{Lo(t)||vw(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 ws(e){try{Lo(e)&&vo(e,{recursive:!0,force:!0})}catch{}}function Oo(e){try{return Lw(e).isDirectory()}catch{return!1}}function xn(e){try{return Aw(e)}catch{return[]}}function*Pg(e){for(let t of xn(e)){let n=at(e,t);if(Oo(n))for(let r of xn(n)){let o=at(n,r);if(Oo(o))for(let i of xn(o)){let s=at(o,i);Oo(s)&&(yield s)}}}}function yg(e){for(let t of[...xn(e)]){let n=at(e,t);if(Oo(n)){for(let r of[...xn(n)]){let o=at(n,r);if(Oo(o)&&xn(o).length===0)try{vo(o,{recursive:!0,force:!0})}catch{}}if(xn(n).length===0)try{vo(n,{recursive:!0,force:!0})}catch{}}}}function Uw(e){let t=0;for(let n of Pg(e))try{let r=jl(n);(!r||!Cg(r))&&(vo(n,{recursive:!0,force:!0}),t++)}catch{}return t}function jw(e){let t=[];for(let n of Pg(e)){let r=jl(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??xo(n)})}return t}function $w(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{vo(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function xg(e){if(!Lo(e))return 0;let t=0;try{t+=Uw(e)}catch{return t}yg(e);let n=$w(jw(e),Bw(),Qw());return t+=n,n>0&&yg(e),t}function xs(e){return xg(Ql(e))}function Ao(e){return xg(Rg(e))}function nB(e){hr||(xs(e),Ao(e),hr=setInterval(()=>{xs(e),Ao(e)},Fw),hr.unref())}function rB(){hr&&(clearInterval(hr),hr=null)}var Iw,Fw,Mw,Dw,bg,hr,Ts=y(()=>{"use strict";Ae();Iw=1440*60*1e3,Fw=600*1e3,Mw=2*1024*1024*1024,Dw=50,bg=".octocode-clone-meta.json",hr=null});import{writeFileSync as kg,mkdirSync as $l,existsSync as Mo,rmSync as qw,readdirSync as Vw,statSync as Og}from"node:fs";import{join as Es,dirname as vg,resolve as ql,sep as Vl}from"node:path";function Tg(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function Xw(e){return Object.values(e).every(t=>t===0)}function Eg(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 _g(e,t,n,r,o,i=!1){let s=Rn(),a=Ul(s,e,t,r),c=ql(Es(a,n));if(!c.startsWith(a+Vl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Io(a);if(l.hit&&!i&&Mo(c)){let v=tT(c,a),D=Tg();return{localPath:c,repoRoot:a,files:v.files,fileCount:v.fileCount,totalSize:v.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:v.fileCount,eligibleFileCount:v.fileCount,savedFileCount:v.fileCount,skipped:D,limits:wg,warnings:Eg(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await pe(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:p}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(p))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=p,m=Tg(),g=[];for(let v of f){if(v.type!=="file"){m.nonFile+=1;continue}if(!v.download_url){m.missingDownloadUrl+=1;continue}if(v.size>Lg){m.oversized+=1;continue}let D=ag(v.name,{lowercase:!0,leadingDot:!0});if(Yw.has(D)){m.binary+=1;continue}g.push(v)}m.fileLimit=Math.max(0,g.length-Wl);let b=g.slice(0,Wl),S=o?.token,C=await Jw(b,Ww,S);m.fetchFailed=b.length-C.length;let k=0,_=[];for(let v=0;v<C.length;v+=1){let{entry:D,content:Q}=C[v];if(k+Q.length>Ag){m.totalSizeLimit=C.length-v;break}k+=Q.length,_.push({entry:D,content:Q})}Ao(s),wn(a),Mo(c)&&qw(c,{recursive:!0,force:!0}),$l(c,{recursive:!0,mode:448});let E=[];for(let{entry:v,content:D}of _){let Q=ql(Es(a,v.path));if(!Q.startsWith(a+Vl)){m.pathTraversal+=1;continue}let ee=vg(Q);Mo(ee)||$l(ee,{recursive:!0,mode:448}),kg(Q,D,"utf-8"),E.push({path:v.path,size:D.length,type:"file"})}let O=Fo(e,t,r,"treeFetch",void 0,void 0,d);_o(a,O);let w=Xw(m),H=w,I=m.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:k,complete:w,verified:H,...d?{commitSha:d}:{},...I?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:m,limits:wg,warnings:Eg(w,H),cached:!1,expiresAt:O.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function Ig(e,t,n,r,o,i=!1){let s=Rn(),a=Ul(s,e,t,r),c=ql(Es(a,n));if(!c.startsWith(a+Vl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Io(a);if(!i&&l.hit&&Mo(c))return{localPath:c,repoRoot:a,path:n,size:nT(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await Cs({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 m="error"in u?u.error:void 0;throw new Error(m||`Failed to fetch ${e}/${t}/${n}`)}Ao(s),wn(a);let d=vg(c);Mo(d)||$l(d,{recursive:!0,mode:448}),kg(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=Fo(e,t,p,"treeFetch");return _o(a,f),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:p}}async function Jw(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 eT(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 eT(e,t){try{let o=new URL(e);if(!Zw.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(),Kw);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 tT(e,t){let n=[],r=0;function o(i){let s;try{s=Vw(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Es(i,a);try{let l=Og(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function nT(e){try{return Og(e).size}catch{return 0}}var Wl,Ag,Lg,Ww,Kw,Yw,wg,Zw,Kl=y(()=>{"use strict";Ae();Ge();Ps();Ts();gr();Wl=50,Ag=5*1024*1024,Lg=300*1024,Ww=5,Kw=1e4,Yw=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"]),wg={maxDirectoryFiles:Wl,maxTotalSize:Ag,maxFileSize:Lg};Zw=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function et(){try{return ge().output.pagination.defaultCharLength}catch{return Ft.pagination.defaultCharLength}}function gB(e){let t=Math.min(Math.max(et(),1),Fg),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,Fg)}var Fg,yr=y(()=>{"use strict";Ae();Ae();Fg=1e5});function Do(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Dt(e){return Do(e).length}var br=y(()=>{"use strict"});function rT(e,t,n){return F.byteSliceContent(e,t,n)}function ks(e,t){return F.byteToCharOffset(e,t)}function Mg(e,t){return F.charToByteOffset(e,t)}function Dg(e){return F.charToByteOffset(e,e.length)}function RB(e,t,n){let r=rT(e,t,t+n);return{charOffset:ks(e,t),charLength:r.length,text:r}}function Yl(e,t,n,r){return F.sliceContent(e,t,n,r)}var Xl=y(()=>{"use strict";be()});function Rr(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Dg(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,p,f,m,g;if(o==="bytes"){let b=Math.min(t,s),S=Math.min(b+n,s);d=ks(e,b),p=ks(e,S),p<i&&Mg(e,p)<S&&(p+=1);let C=Yl(e,d,p-d);c=C.text,d=C.charOffset,p=C.charOffset+C.charLength,l=C.byteOffset,u=C.byteOffset+C.byteLength,f=u<s;let k=r.actualOffset??b;m=Math.floor(k/a)+1,g=Math.max(m,Math.ceil(s/a))}else{let b=Yl(e,t,n);c=b.text,d=b.charOffset,p=b.charOffset+b.charLength,l=b.byteOffset,u=b.byteOffset+b.byteLength,f=p<i;let S=r.actualOffset??d;m=Math.floor(S/a)+1,g=Math.max(m,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:f?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:f?p:void 0,hasMore:f,estimatedTokens:Math.ceil(c.length/4),currentPage:m,totalPages:g}}function PB(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function Ng(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 xB(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
|
|
8
|
+
var kC=Object.defineProperty;var y=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var OC=(e,t)=>{for(var n in t)kC(e,n,{get:t[n],enumerable:!0})};import{withSecurityValidation as vC,withBasicSecurityValidation as AC}from"@octocodeai/octocode-engine/security";function mf(e,t){let n=vC(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function gf(e,t){let n=AC(r=>e(r),t);return(r,o)=>n(r,o)}var Oc=y(()=>{"use strict"});var pt,_e,kG,OG,hf,xn,yf,bf,Qi,zt,Xn,Bi,Rf,Jn,Sf,ji,Pf,Se=y(()=>{"use strict";pt=30,_e=100,kG=10,OG=100,hf=200,xn=20,yf=100,bf=20,Qi=50,zt=1e4,Xn=20,Bi=1e3,Rf=100,Jn=5e4,Sf=8e3,ji=1e5,Pf=500});var vc,io,so,LC,rn,Zn,Xe,_C,ao,IC,AG,Pt=y(()=>{"use strict";vc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},io={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"}},so={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})`}},LC={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"}},rn={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}`}},Zn={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"}},Xe={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}`}},_C={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}`}},ao={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"}},IC={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}`}},AG={...vc,...io,...so,...LC,...rn,...Zn,...Xe,..._C,...ao,...IC}});var Q,FC,Cf,wn=y(()=>{"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"},FC=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(FC||{}),Cf={[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 Ac(e){return e instanceof Me}function xf(e,t=Q.TOOL_EXECUTION_FAILED,n){if(Ac(e))return e;if(e instanceof Error)return new Me(t,e.message,n,e);let r=String(e);return new Me(t,r,n)}var Me,co=y(()=>{"use strict";wn();Me=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Cf[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 lo}from"@octocodeai/octocode-engine/pathUtils";var Lc=y(()=>{"use strict"});var rt,uo=y(()=>{"use strict";co();wn();Lc();rt={pathValidationFailed:(e,t,n)=>new Me(Q.PATH_VALIDATION_FAILED,t||`Path validation failed: ${lo(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=lo(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 Me(Q.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Me(Q.FILE_READ_FAILED,`Failed to read file: ${lo(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Me(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 Me(Q.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${lo(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Me(Q.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Me(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 Me(Q.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Me(Q.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});function At(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function Qt(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 po(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Ui=y(()=>{"use strict"});function DC(e){let t=At(e),n=fo.get(t);return!n||Date.now()-n.cachedAt>=MC?!1:n.credentials?!Qt(n.credentials):!0}function mo(e){e?fo.delete(At(e)):fo.clear()}function wf(e){let t=At(e);if(DC(t))return fo.get(t).credentials}function Ef(e,t){let n=At(e);fo.set(n,{credentials:t,cachedAt:Date.now()})}var fo,MC,Tf=y(()=>{"use strict";Ui();fo=new Map,MC=300*1e3});import qG from"node:fs";import VG from"node:path";import kf from"node:os";import er from"node:path";import{existsSync as Df,readFileSync as qC}from"node:fs";import WC from"node:path";function Nc(e=process.env){let t=e.OCTOCODE_HOME;if(t&&t.trim())return er.resolve(t.trim());let n=kf.homedir(),r=kf.platform();if(r==="win32"){let i=e.APPDATA??er.join(n,"AppData","Roaming");return er.join(i,".octocode")}if(r==="darwin")return er.join(n,".octocode");let o=e.XDG_CONFIG_HOME??er.join(n,".config");return er.join(o,".octocode")}function _f(e){globalThis[Lf]=e}function Wi(){return globalThis[Lf]??"mcp"}function GC(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function Mc(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Of(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function If(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function HC(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function _c(e,t){return e===void 0||e===null?null:If(e,t)}function Ff(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function zC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=GC(e.apiUrl,"github.apiUrl");r&&t.push(r)}function QC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Of(n.enabled,"local.enabled");r&&t.push(r);let o=Of(n.enableClone,"local.enableClone");o&&t.push(o);let i=If(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=HC(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=Ff(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function BC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=_c(n.enabled,"tools.enabled");r&&t.push(r);let o=_c(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=_c(n.disabled,"tools.disabled");i&&t.push(i)}function jC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=Mc(n.timeout,"network.timeout",zc,Qc);r&&t.push(r);let o=Mc(n.maxRetries,"network.maxRetries",Bc,jc);o&&t.push(o)}function UC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=Ff(e.configPath,"lsp.configPath");r&&t.push(r)}function $C(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=Mc(r.defaultCharLength,"output.pagination.defaultCharLength",Uc,$c);o&&t.push(o)}}function Mf(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>Fc&&n.push(`version: Config version ${r.version} is newer than supported version ${Fc}`)),zC(r.github,t),QC(r.local,t),BC(r.tools,t),jC(r.network,t),UC(r.lsp,t),$C(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}function VC(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
|
|
10
|
+
`;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t.replace(/,(\s*[}\]])/g,"$1")}function KC(e){return JSON.parse(VC(e))}function qc(e=Nc()){return WC.join(e,".octocoderc")}function YC(e){return Df(qc(e))}function Wc(e){let t=qc(e);if(!Df(t))return{success:!1,error:"Config file does not exist",path:t};try{let n=qC(t,"utf-8");if(!n.trim())return{success:!0,config:{},path:t};let r=KC(n);return typeof r!="object"||r===null||Array.isArray(r)?{success:!1,error:"Config file has invalid structure: must be a JSON object",path:t}:{success:!0,config:r,path:t}}catch(n){return{success:!1,error:`Failed to parse config file: ${n instanceof Error?n.message:String(n)}`,path:t}}}async function XC(e){return Wc(e)}function vf(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Dc(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function $i(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function JC(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||Gc.apiUrl}}function ZC(e){let t=Wi()==="cli",n=vf(process.env.ENABLE_LOCAL),r=vf(process.env.ENABLE_CLONE),o=$i(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??tr.enabled,enableClone:r??e?.enableClone??(t?!0:tr.enableClone),allowedPaths:o??e?.allowedPaths??tr.allowedPaths,workspaceRoot:i??e?.workspaceRoot??tr.workspaceRoot}}function ex(e){let t=$i(process.env.TOOLS_TO_RUN),n=$i(process.env.ENABLE_TOOLS),r=$i(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??go.enabled,enableAdditional:n??e?.enableAdditional??go.enableAdditional,disabled:r??e?.disabled??go.disabled}}function tx(e){let t=Dc(process.env.REQUEST_TIMEOUT),n=Dc(process.env.MAX_RETRIES),r=t??e?.timeout??qi.timeout;r=Math.max(zc,Math.min(Qc,r));let o=n??e?.maxRetries??qi.maxRetries;return o=Math.max(Bc,Math.min(jc,o)),{timeout:r,maxRetries:o}}function nx(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??Hc.configPath}}function ox(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=Dc(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||Tn.format,o=n??e?.pagination?.defaultCharLength??Tn.pagination.defaultCharLength,i=Math.max(Uc,Math.min($c,o));return{format:rx.has(r)?r:Tn.format,pagination:{defaultCharLength:i}}}function Ic(e,t){let n=e!==void 0,r=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??Af.version,github:JC(e?.github),local:ZC(e?.local),tools:ex(e?.tools),network:tx(e?.network),lsp:nx(e?.lsp),output:ox(e?.output),source:o,configPath:n?t:void 0}}function Vc(){let e=Wc();return e.success&&e.config&&Mf(e.config).valid?Ic(e.config,e.path):Ic(void 0)}async function ix(){return Vc()}function De(){let e=Date.now();return En&&e-ho<sx||(En=Vc(),ho=e),En}async function Nf(){return De()}async function ax(){return yo(),Nf()}function yo(){En=null,ho=0}function cx(){En=null,ho=0}function lx(){return{cached:En!==null,timestamp:ho}}function ux(e){let t=De(),n=e.split("."),r=t;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function Gf(e=process.env){for(let t of Vi){let n=e[t];if(n&&n.trim())return n.trim()}return null}function dx(e=process.env){for(let t of Vi){let n=e[t];if(n&&n.trim())return`env:${t}`}return null}function px(e=process.env){return Gf(e)!==null}function Kc(e=process.env){for(let t of Vi){let n=e[t];if(n?.trim())return{token:n.trim(),source:`env:${t}`}}return null}var Fc,NC,Gc,tr,go,qi,Hc,Tn,Af,zc,Qc,Bc,jc,Uc,$c,Lf,rx,En,ho,sx,Vi,ot=y(()=>{"use strict";Fc=1,NC=".octocoderc",Gc={apiUrl:"https://api.github.com"},tr={enabled:!0,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},go={enabled:null,enableAdditional:null,disabled:null},qi={timeout:3e4,maxRetries:3},Hc={configPath:void 0},Tn={format:"yaml",pagination:{defaultCharLength:2e4}},Af={version:1,github:Gc,local:tr,tools:go,network:qi,lsp:Hc,output:Tn},zc=5e3,Qc=3e5,Bc=0,jc=10,Uc=1e3,$c=5e4,Lf="__octocodeRuntimeSurface__";rx=new Set(["yaml","json"]);En=null,ho=0,sx=6e4;Vi=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN"]});import{existsSync as nr,mkdirSync as rr}from"node:fs";import{join as it}from"node:path";function Hf(){return Nc(process.env)}function ir(){return Ne}function Ki(){nr(ye.home)||rr(ye.home,{recursive:!0,mode:or})}function fx(){zf()}function bo(){Ki(),nr(ye.tmp)||rr(ye.tmp,{recursive:!0,mode:or})}function zf(){bo(),nr(ye.clone)||rr(ye.clone,{recursive:!0,mode:or})}function mx(){bo(),nr(ye.tree)||rr(ye.tree,{recursive:!0,mode:or})}function gx(){bo(),nr(ye.binary)||rr(ye.binary,{recursive:!0,mode:or})}function hx(){bo(),nr(ye.unzip)||rr(ye.unzip,{recursive:!0,mode:or})}var or,Ne,ye,sr=y(()=>{"use strict";ot();or=448;Ne=Hf(),ye={home:Ne,config:it(Ne,".octocoderc"),credentials:it(Ne,"credentials.json"),key:it(Ne,".key"),session:it(Ne,"session.json"),stats:it(Ne,"stats.json"),tmp:it(Ne,"tmp"),clone:it(Ne,"tmp","clone"),tree:it(Ne,"tmp","tree"),binary:it(Ne,"tmp","binary"),repos:it(Ne,"tmp","clone"),unzip:it(Ne,"tmp","unzip"),cliConfig:it(Ne,"config.json"),lspConfig:it(Ne,"lsp-servers.json")}});import{z as Ie}from"zod";var yx,bx,Qf,Bf=y(()=>{"use strict";yx=Ie.object({token:Ie.string(),tokenType:Ie.literal("oauth"),scopes:Ie.array(Ie.string()).optional(),refreshToken:Ie.string().optional(),expiresAt:Ie.string().optional(),refreshTokenExpiresAt:Ie.string().optional()}),bx=Ie.object({hostname:Ie.string(),username:Ie.string(),token:yx,gitProtocol:Ie.enum(["ssh","https"]),createdAt:Ie.string(),updatedAt:Ie.string()}),Qf=Ie.object({version:Ie.number(),credentials:Ie.record(Ie.string(),bx)})});import{existsSync as Yi,readFileSync as Uf,writeFileSync as $f,unlinkSync as jf,statSync as Rx,chmodSync as Sx}from"node:fs";import{createCipheriv as Px,createDecipheriv as Cx,randomBytes as qf}from"node:crypto";function on(){Ki()}function Vf(){if(on(),Yi(Lt))return Rx(Lt).mode&511&63&&Sx(Lt,384),Buffer.from(Uf(Lt,"utf8"),"hex");let e=qf(32);return $f(Lt,e.toString("hex"),{mode:384}),e}function Xi(e){let t=Vf(),n=qf(xx),r=Px(Wf,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 Ji(e){let t=Vf(),[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=Cx(Wf,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function jt(){if(on(),!Yi(Bt))return{version:1,credentials:{}};try{let e=Uf(Bt,"utf8"),t=Ji(e),n=JSON.parse(t),r=Qf.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Xc(e){on();let t=Xi(JSON.stringify(e,null,2));$f(Bt,t,{mode:384})}function Kf(){try{Yi(Bt)&&jf(Bt),Yi(Lt)&&jf(Lt)}catch{}}var Yc,Bt,Lt,Wf,xx,Yf=y(()=>{"use strict";sr();Bf();Yc=ye.home,Bt=ye.credentials,Lt=ye.key,Wf="aes-256-gcm",xx=16});var ar,sn,Jc=y(()=>{"use strict";ar="178c6fc778ccc68e1d6a",sn="github.com"});import{refreshToken as wx}from"@octokit/oauth-methods";import{request as Ex}from"@octokit/request";function Tx(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 kx(e){return e==="github.com"||e===sn?"https://api.github.com":`https://${e}/api/v3`}async function Zc(e,t=sn,n=ar){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(po(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await wx({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:Ex.defaults({baseUrl:kx(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?Tx(o.message):"Token refresh failed"}}}async function Xf(e,t=sn,n=ar){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!Qt(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Zc(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 Jf=y(()=>{"use strict";Ui();Jc()});import{execFile as Ox}from"child_process";function Zi(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=vx.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Ox("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var vx,el=y(()=>{"use strict";vx=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function Zf(e){es=e}function tl(){es=null}function Ax(){if(!es)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return es}async function an(e){let t=e?.hostname??sn,n=e?.clientId??ar,r=e?.getGhCliToken??Zi,o=Kc();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await Ax().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)}
|
|
11
|
+
`)}return null}async function nl(e=sn){let t=await an({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function rl(e=sn,t=ar){let n=await an({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var es,em=y(()=>{"use strict";ot();el();Jc();es=null});async function ol(e){let t=At(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=jt();return r.credentials[t]=n,Xc(r),mo(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function kn(e="github.com",t){let n=At(e);if(!t?.bypassCache){let i=wf(n);if(i!==void 0)return i}let o=jt().credentials[n]||null;return Ef(n,o),o}function ts(e="github.com"){let t=At(e);return jt().credentials[t]||null}async function tm(e="github.com"){let t=At(e),n=!1,r=jt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Kf():Xc(r),n=!0),mo(t),{success:n,deletedFromFile:n}}async function nm(){let e=jt();return Object.keys(e.credentials)}function rm(){let e=jt();return Object.keys(e.credentials)}async function om(e="github.com"){return await kn(e)!==null}function im(e="github.com"){return ts(e)!==null}async function ns(e,t){let n=await kn(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await ol(n),!0):!1}function sm(){return Bt}async function am(e="github.com"){let t=await kn(e);return!t||!t.token||Qt(t)?null:t.token.token}function cm(e="github.com"){let t=ts(e);return!t||!t.token||Qt(t)?null:t.token.token}async function lm(e,t){return Zc({getCredentials:kn,updateToken:ns},e,t)}async function il(e,t){return Xf({getCredentials:kn,updateToken:ns},e,t)}var sl=y(()=>{"use strict";Tf();Yf();Jf();em();Ui();Zf({getTokenWithRefresh:il})});var al=y(()=>{"use strict";sl();el()});import lr from"node:os";import um from"node:path";function dm(){return Ro?process.env.APPDATA||um.join(cr,"AppData","Roaming"):cr}function pm(){return Ro?process.env.LOCALAPPDATA||um.join(cr,"AppData","Local"):cr}function fm(){return cl?"macOS":Ro?"Windows":ll?"Linux":lr.platform()}function mm(){return lr.arch()}var Ro,cl,ll,cr,gm=y(()=>{"use strict";Ro=lr.platform()==="win32",cl=lr.platform()==="darwin",ll=lr.platform()==="linux",cr=lr.homedir()});var ul=y(()=>{"use strict";gm()});import{z as Y}from"zod";var Lx,_x,rs,Ix,os,hm,ym,bm=y(()=>{"use strict";Lx=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),_x=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),rs=Y.record(Y.string(),Y.number()).default({}),Ix=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:rs,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:rs}),os=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:rs,charsSavedByTool:Y.record(Y.string(),Lx).default({}),githubCacheHits:_x.default({hits:{},rateLimits:0}),packageRegistryFailures:rs,totalUsage:Ix.optional()}),hm=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:os.optional()}),ym=Y.object({version:Y.literal(1),stats:os})});function Rm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Fx(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:Rm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Rm(o),packageRegistryFailuresByRegistry:o}}function Ut(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Fx(t)}}function So(){return Ut({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var dl=y(()=>{"use strict"});import{existsSync as pl,readFileSync as Pm,writeFileSync as Mx,unlinkSync as Dx,renameSync as Nx}from"node:fs";function Sm(e,t){let n=`${e}.tmp`;Mx(n,JSON.stringify(t,null,2),{mode:384}),Nx(n,e)}function Gx(e){let{stats:t,...n}=e;return n}function Hx(e){let t=JSON.parse(e),n=ym.safeParse(t);if(n.success)return Ut(n.data.stats);let r=os.safeParse(t);return r.success?Ut(r.data):null}function zx(e){let t=e?Ut(e):So();if(!pl(vn))return t;try{let n=Pm(vn,"utf8"),r=Hx(n);return r||t}catch{return t}}function is(e){on(),Sm(vn,{version:e.version,stats:Ut(e.stats)}),Sm(On,Gx(e))}function Cm(){if(!pl(On))return null;try{let e=Pm(On,"utf8"),t=JSON.parse(e),n=hm.safeParse(t);return n.success?{...n.data,stats:zx(n.data.stats)}:null}catch{return null}}function xm(){let e=!1;for(let t of[On,vn])if(pl(t))try{Dx(t),e=!0}catch{return!1}return e}var On,vn,ss=y(()=>{"use strict";sl();sr();bm();dl();On=ye.session,vn=ye.stats});function Bx(){fl||(fl=!0,Po=()=>{wo()},Co=()=>{wo()},xo=()=>{wo()},process.on("exit",Po),process.on("SIGINT",Co),process.on("SIGTERM",xo))}function ml(){Po&&(process.removeListener("exit",Po),Po=null),Co&&(process.removeListener("SIGINT",Co),Co=null),xo&&(process.removeListener("SIGTERM",xo),xo=null),fl=!1}function jx(){ur||(ur=setInterval(()=>{cn&&Ct&&(is(Ct),cn=!1)},Qx),ur.unref())}function gl(){ur&&(clearInterval(ur),ur=null)}function Eo(){if(Ct)return Ct;let e=Cm();return e&&(Ct=e),e}function dr(e){Ct=e,cn=!0,Bx(),jx()}function To(){cn&&Ct&&(is(Ct),cn=!1)}function wo(){if(!as&&cn&&Ct){as=!0;try{is(Ct),cn=!1}catch{}finally{as=!1}}}function hl(){Ct=null,cn=!1,as=!1}function wm(){hl(),gl(),ml()}var Qx,Ct,cn,ur,fl,Po,Co,xo,as,Em=y(()=>{"use strict";ss();Qx=6e4,Ct=null,cn=!1,ur=null,fl=!1,Po=null,Co=null,xo=null,as=!1});import{randomUUID as Ux}from"node:crypto";function qx(e){return Ut(e)}function Wx(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 Tm(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 Vx(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 km(){let e=new Date().toISOString();return{version:$x,sessionId:Ux(),createdAt:e,lastActiveAt:e,stats:So()}}function Om(){To()}function vm(){wo()}function Am(e){if(e?.forceNew){let r=km();return dr(r),To(),r}let t=Eo();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return dr(r),To(),r}let n=km();return dr(n),To(),n}function Lm(){return Eo()?.sessionId??null}function st(e){let t=Eo();if(!t)return{success:!1,session:null};let n=qx(t.stats),r=Ut({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Tm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Wx(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:Vx(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Tm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return dr(o),{success:!0,session:o}}function _m(e=1){return st({toolCalls:e})}function Im(e=1){return st({errors:e})}function cs(e=1){return st({rateLimits:e})}function Fm(e,t=1){return st({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function ls(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return st({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function us(e,t=1){return st({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ds(e=1){return st({githubCacheHits:{hits:{},rateLimits:e}})}function Mm(e,t=1){return st({packageRegistryFailures:{[e]:t}})}function Dm(){let e=Eo();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:So()};return dr(t),{success:!0,session:t}}function Nm(){return hl(),gl(),ml(),xm()}function Gm(){wm()}var $x,ko=y(()=>{"use strict";ss();dl();Em();ss();$x=1});var yl=y(()=>{"use strict";ko();ko();ko();ko()});import{z as xe}from"zod";var Hm,bl=y(()=>{"use strict";Hm=xe.looseObject({$schema:xe.string().optional(),version:xe.number().int().optional(),github:xe.record(xe.string(),xe.unknown()).optional(),local:xe.record(xe.string(),xe.unknown()).optional(),tools:xe.record(xe.string(),xe.unknown()).optional(),network:xe.record(xe.string(),xe.unknown()).optional(),lsp:xe.record(xe.string(),xe.unknown()).optional(),output:xe.record(xe.string(),xe.unknown()).optional()})});var zm=y(()=>{"use strict";bl();ot()});import{existsSync as Kx,readdirSync as Yx,lstatSync as Xx}from"node:fs";import{join as Jx}from"node:path";function Oo(e){if(!Kx(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Yx(r)}catch{continue}for(let i of o){let s=Jx(r,i);try{let a=Xx(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function Zx(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 Rl=y(()=>{"use strict"});var $t=y(()=>{"use strict";al();ul();yl();zm();sr();Rl()});var An,ps=y(()=>{An="16.6.3"});import{maskSensitiveData as tw}from"@octocodeai/octocode-engine/mask";function Az(e){e.resolveTokenFull&&(Sl=e.resolveTokenFull)}function Lz(){Sl=an}async function Pl(){try{let e=await Sl({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:nw.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Qm(){if(ln!==null)return;if(pr!==null)return pr;let e=(async()=>{let t=De(),n=await Pl();ln={version:An,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}})();pr=e;try{await e}catch(t){throw pr===e&&(ln=null,pr=null),t}}function _z(){ln=null,pr=null,yo()}function fs(){if(!ln){let e=tw(vc.NOT_INITIALIZED.message);throw new Error(e)}return ln}async function Bm(){return(await Pl()).token}function Iz(){return fs().enableLocal}function Fz(){let e=fs();return e.enableLocal&&e.enableClone}async function Mz(){return ln!==null?ln.tokenSource:(await Pl()).source}function Cl(){return"github"}function xl(){let e=De().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var ln,pr,Sl,nw,fr=y(()=>{"use strict";$t();ot();ps();Pt();ln=null,pr=null,Sl=an;nw=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});function un(e){(e.provider?st({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):cs(1)).session&&e.provider==="github"&&ds(1)}function jm(e){st({packageRegistryFailures:{[e]:1}})}var vo=y(()=>{"use strict";$t()});import{Octokit as rw}from"octokit";import{throttling as ow}from"@octokit/plugin-throttling";import{createHash as iw}from"crypto";function sw(e){return iw("sha256").update(e).digest("hex").substring(0,16)}function Vm(e){return Date.now()-e.createdAt>cw}function Km(){for(let[e,t]of _t.entries())Vm(t)&&_t.delete(e);if(_t.size>wl){let e=_t.size-wl,t=0;for(let[n]of _t){if(t>=e)break;_t.delete(n),t++}}}function uw(){dn||(dn=setInterval(Km,lw),typeof dn=="object"&&"unref"in dn&&dn.unref())}function qm(e,t,n){un({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function pw(e){let t=fs(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${An}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:dw(),log:r,...e&&{auth:e}};return new aw(o)}async function be(e){uw();let t=e?.token??await Bm(),n=t?sw(t):"ANONYMOUS",r=_t.get(n);if(r&&!Vm(r))return r.client;_t.size>=wl&&Km();let o=pw(t??void 0);return _t.set(n,{client:o,createdAt:Date.now()}),o}async function at(e,t,n){let r=`${e}/${t}`,o=mr.get(r);if(o)return o;let i=await be(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Wm(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}),Wm(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 Wm(e,t){if(mr.size>=fw){let n=mr.keys().next().value;n!==void 0&&mr.delete(n)}mr.set(e,t)}function qz(){_t.clear(),mr.clear(),dn&&(clearInterval(dn),dn=null)}var aw,cw,wl,lw,_t,dn,Um,$m,dw,fw,mr,je=y(()=>{"use strict";fr();fr();ps();vo();aw=rw.plugin(ow),cw=300*1e3,wl=50,lw=60*1e3;_t=new Map,dn=null;Um=3,$m=60;dw=()=>({onRateLimit:(e,t,n,r)=>(qm("primary",e,t),r<Um&&e<$m),onSecondaryRateLimit:(e,t,n,r)=>(qm("secondary",e,t),r<Um&&e<$m)});fw=200,mr=new Map});import{createRequire as mw}from"node:module";function Z(){if(ms)return ms;try{return ms=hw(),ms}catch(e){throw new El(e)}}var gw,Ym,ms,hw,El,M,we=y(()=>{"use strict";gw=mw(import.meta.url),Ym="@octocodeai/octocode-engine",hw=()=>gw(Ym),El=class extends Error{constructor(n){super(`Failed to load native dependency ${Ym}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};M={applyContentViewMinification(e,t){return Z().applyContentViewMinification(e,t)},applyMinification(e,t){return Z().applyMinification(e,t)},minifyContent(e,t){return Z().minifyContent(e,t)},minifyContentSync(e,t){return Z().minifyContentSync(e,t)},minifyContentResult(e,t){return Z().minifyContentResult(e,t)},minifyMarkdownCore(e){return Z().minifyMarkdownCore(e)},extractSignatures(e,t){return Z().extractSignatures(e,t)},extractJsSymbols(e,t){return Z().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return Z().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return Z().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return Z().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return Z().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return Z().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return Z().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return Z().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return Z().getSupportedStructuralExtensions()},inspectBinaryNative(e){return Z().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return Z().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return Z().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return Z().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return Z().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return Z().parseRipgrepJson(e,t)},searchRipgrep(e){return Z().searchRipgrep(e)},queryFileSystem(e){return Z().queryFileSystem(e)},extractMatchingLines(e,t,n){return Z().extractMatchingLines(e,t,n)},filterPatch(e,t){return Z().filterPatch(e,t)},charToByteOffset(e,t){return Z().charToByteOffset(e,t)},byteToCharOffset(e,t){return Z().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return Z().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return Z().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return Z().SIGNATURES_ONLY_HINT}}});var W,Te,Xm,Tl,kl,gs,Ol=y(()=>{"use strict";W={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"},Te={[W.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."},[W.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."},[W.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},[W.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)."},[W.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."},[W.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."},[W.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."},[W.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."},[W.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."},[W.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Xm={401:W.AUTH_REQUIRED,403:W.FORBIDDEN_PERMISSIONS,404:W.NOT_FOUND,422:W.INVALID_REQUEST,502:W.SERVER_UNAVAILABLE,503:W.SERVER_UNAVAILABLE,504:W.SERVER_UNAVAILABLE},Tl={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},kl={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},gs={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as Jm}from"octokit";function Ln(e){if(!(e instanceof Jm)||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 yw.some(o=>r.includes(o))})}function ae(e){return e instanceof Jm?bw(e):e instanceof Error?Tw(e):{error:typeof e=="string"?e:Te[W.UNKNOWN].message,type:"unknown"}}function bw(e){let{status:t,message:n,response:r}=e;if(t===403)return Sw(n,r);if(t===429)return Rw(n,r);let o=Xm[t];return o?Ew(o,t):gr(W.UNKNOWN,{error:n||Te[W.UNKNOWN].message,status:t})}function vl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function Rw(e,t){let n=t?.headers,r=vl(n,"retry-after"),o=vl(n,"x-ratelimit-reset"),i=vl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+gs.RESET_BUFFER_SECONDS,0):void 0);return un({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),gr(W.RATE_LIMIT_PRIMARY,{error:e||Te[W.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Te[W.RATE_LIMIT_PRIMARY].suggestion})}function Sw(e,t){let n=t?.headers;if(kl.SECONDARY.test(e))return Pw(n);let r=n?.["x-ratelimit-remaining"],o=ww(t);return r!==void 0&&String(r)==="0"||o?Cw(n):xw(n)}function Pw(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?gs.SECONDARY_FALLBACK_SECONDS:t;return un({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),gr(W.RATE_LIMIT_SECONDARY,{error:Te[W.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Te[W.RATE_LIMIT_SECONDARY].suggestion})}function Cw(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)+gs.RESET_BUFFER_SECONDS,0):void 0,i=r?Te[W.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Te[W.RATE_LIMIT_PRIMARY].messageWithoutTime;return un({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),gr(W.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Te[W.RATE_LIMIT_PRIMARY].suggestion})}function xw(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Te[W.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=kw(String(t),String(n))),gr(W.FORBIDDEN_PERMISSIONS,{error:Te[W.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function ww(e){return e?.data?.errors?.some(n=>n.type===kl.GRAPHQL_TYPE)??!1}function Ew(e,t){let n=Te[e];return gr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function Tw(e){return Tl.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Te[W.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Te[W.NETWORK_CONNECTION_FAILED].suggestion}:Tl.TIMEOUT.some(t=>e.message.includes(t))?{error:Te[W.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Te[W.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function gr(e,t){return{type:"http",...t}}function kw(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?Te[W.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Te[W.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var yw,It=y(()=>{"use strict";Ol();vo();yw=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function Ow(e){return`user:${e}`}function Zm(e){return e.startsWith('"')||Lw.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function eg(e){return new Al().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function tg(e){return new Ll().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function ng(e){return new _l().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function rg(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 vw,Aw,Lw,Ao,Al,Ll,_l,Lo=y(()=>{"use strict";vw=/[@/]/,Aw=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Lw=/^[A-Za-z0-9_-]+$/;Ao=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(Ow(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=vw.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},Al=class extends Ao{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(Zm))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Aw):null;return o&&(r=o[1],n=n.slice(0,o.index)||void 0),this.addSimpleFilter(r,"filename"),this.addSimpleFilter(t.extension,"extension"),this.addQuotedFilter(n,"path"),t.language&&this.queryParts.push(`language:${t.language}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="file"?this.queryParts.push("in:file"):r==="path"&&this.queryParts.push("in:path")}),this}},Ll=class extends Ao{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Zm)),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}},_l=class extends Ao{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}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});import _w from"node-cache";import Iw from"crypto";function Dw(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Nw(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Gw(e){let t=Dw(e);if(!(!t||!Nw(t)))try{us(t,1)}catch{}}function Hw(){let e=Date.now();for(let[t,n]of hr.entries())e-n.startedAt>Mw&&hr.delete(t)}function Qw(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(zw.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Ue(e,t,n){let r=Il(Qw(t)),o=n?`${n}:${r}`:r,i=Iw.createHash("sha256").update(o).digest("hex");return`${Fw}-${e}:${i}`}function Il(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=>Il(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Il(i,t)}`}).join(",")}}`)}function Bw(e){return og[e]||og.default}function jw(e,t,n){try{return ft.set(e,t,n),Ge.sets++,Ge.totalKeys=ft.keys().length,!0}catch{try{let r=ft.keys();for(let o of r)ft.get(o);return ft.set(e,t,n),Ge.sets++,Ge.totalKeys=ft.keys().length,!0}catch{return!1}}}async function $e(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=ft.get(e);if(i!==void 0)return Ge.hits++,Gw(e),i}catch{}Hw();let r=hr.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Ge.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Bw(l)}jw(e,i,a)}return i}finally{hr.delete(e)}})();return hr.set(e,{promise:o,startedAt:Date.now()}),o}function iQ(){ft.flushAll(),hr.clear(),Ge.hits=0,Ge.misses=0,Ge.sets=0,Ge.totalKeys=0,Ge.lastReset=new Date}function pn(e){let t=ft.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||ft.del(r)>0&&n++}return n>0&&(Ge.totalKeys=ft.keys().length),n}function sQ(){return pn("local-")}function aQ(){return pn("lsp-")}function cQ(){let e=0;return e+=pn("gh-api-"),e+=pn("bb-api-"),e+=pn("gh-repo-"),e+=pn("bb-repo-"),e+=pn("github-user"),e+=pn("npm-search"),e}function lQ(){let e=Ge.hits+Ge.misses;return{...Ge,hitRate:e>0?Ge.hits/e*100:0,cacheSize:ft.keys().length}}var Fw,Mw,ft,Ge,og,hr,zw,qt=y(()=>{"use strict";$t();Fw="v1",Mw=300*1e3,ft=new _w({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Ge={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},og={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},hr=new Map;zw=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as fQ,DISCOVERY_IGNORED_FILE_NAMES as mQ,DISCOVERY_IGNORED_FOLDER_NAMES as gQ,getDiscoveryExtension as ig,shouldIgnoreDiscoveryDir as _o,shouldIgnoreDiscoveryFile as yr}from"@octocodeai/octocode-engine/security";var br=y(()=>{"use strict"});function j(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function ag(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function q(e,t){let n=typeof t=="number"?ag(t):j(t);if(n===void 0)return e;try{Object.defineProperty(e,sg,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function me(e){if(!(typeof e!="object"||e===null))return ag(e[sg])}var sg,ce=y(()=>{"use strict";sg=Symbol.for("octocode.rawResponseChars")});function hs(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var ys=y(()=>{"use strict"});import{ContentSanitizer as Uw}from"@octocodeai/octocode-engine/contentSanitizer";async function lg(e,t,n){let r=Ue("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await $e(r,async()=>await $w(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function $w(e,t){try{let n=await be(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(w=>w&&w.trim()).length===0)return{error:Xe.QUERY_EMPTY.message,type:"http",status:400};let r=eg(e);if(!r.trim())return{error:Xe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:cg,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 qw(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),p=Math.min(Math.ceil(d/o),10),f=Math.min(i,Math.max(1,p)),m=f<p,g=Math.min(d,p*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:f,totalPages:p,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:m,...m?{nextPage:f+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:hs(a.headers),rawResponseChars:j(a.data)}}catch(n){if(Ln(n)){let o=Math.min(typeof e.limit=="number"?e.limit:cg,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 ae(n)}}async function qw(e,t){let n=Ww(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!yr(f.path)),c=0,l=0,u=await Promise.allSettled(a.map(async f=>{s.add(f.path);let m=[],g=await Promise.allSettled((f.text_matches||[]).map(async A=>{let _=A.fragment,k=Uw.sanitizeContent(_||"",f.path);_=k.content,k.hasSecrets&&r.add(`Secrets detected in ${f.path}: ${k.secretsDetected.join(", ")}`),k.warnings.length>0&&k.warnings.forEach(x=>r.add(`${f.path}: ${x}`));try{let x=await M.minifyContent(_||"",f.path);_=x.content,x.failed?o=!0:x.type!=="failed"&&(m.push(x.type),i.push(x.type))}catch{o=!0}return{context:_||"",positions:A.matches?.map(x=>Array.isArray(x.indices)&&x.indices.length>=2?[x.indices[0],x.indices[1]]:[0,0])||[]}})),b=g.filter(A=>A.status==="fulfilled").map(A=>A.value),w=g.filter(A=>A.status==="rejected").length;w>0&&(l+=w);let S=f,T=Array.from(new Set(m));return{path:f.path,matches:b,url:f.html_url,repository:{nameWithOwner:f.repository.full_name,url:f.repository.url,pushedAt:f.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...T.length>0&&{minificationType:T.join(",")}}})),d=u.filter(f=>f.status==="fulfilled").map(f=>f.value);c=u.filter(f=>f.status==="rejected").length;let p={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let f=n.full_name.split("/");return f.length===2&&f[0]&&f[1]?{owner:f[0],repo:f[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(p.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&&(p.matchLocations=Array.from(r)),p.minified=!o,p.minificationFailed=o,i.length>0&&(p.minificationTypes=Array.from(new Set(i))),p}function Ww(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 cg,Fl=y(()=>{"use strict";we();je();It();Lo();qt();br();Pt();ce();ys();Se();cg=30});import{completeMetadata as Ml}from"@octocodeai/octocode-core";var v,Dl=y(()=>{"use strict";v=new Proxy({},{get(e,t){return Ml.toolNames[t]},ownKeys(){return Object.keys(Ml.toolNames)},getOwnPropertyDescriptor(e,t){let n=Ml.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as Vw}from"@octocodeai/octocode-core";var Nl,Gl=y(()=>{"use strict";Nl=new Proxy({},{get(e,t){return Vw.tools[t]?.description??""}})});import{completeMetadata as Kw}from"@octocodeai/octocode-core";function Hl(e){return Object.prototype.hasOwnProperty.call(Kw.tools,e)}var zl=y(()=>{"use strict"});import{completeMetadata as Yw}from"@octocodeai/octocode-core";function Ql(){return Yw.baseSchema}var Xw,Bl=y(()=>{"use strict";Xw=new Proxy({},{get(e,t){return Ql()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Ql())]))},getOwnPropertyDescriptor(e,t){let n=Ql();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var Re=y(()=>{"use strict";Dl();Gl();zl();Bl()});import{RequestError as ug}from"octokit";async function Jw(e,t,n,r,o,i,s,a){let c=await at(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=ae(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?`,p=await mg(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...fg(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function Zw(e,t,n,r,o,i){let s=ae(t),a=await mg(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...fg(o,a)]),s}async function dg(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:rn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:rn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:rn.DECODE_FAILED.message,type:"unknown",status:422}}}async function pg(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"?dg(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return ae(i)}}async function eE(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 at(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(p=>p.name===a&&p.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await pg(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 ae(s)}}async function bs(e,t){try{let n=await be(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof ug&&d.status===404)if(s){let p=await Jw(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await Zw(n,d,r,o,i,s);else{if(d instanceof ug&&d.status===413)return await eE(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:rn.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in u&&u.type==="file"){let d=typeof u.content=="string"?u.content:"",p=u.size??0,f;if(d.length>0)f=await dg(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await pg(n,r,o,u.sha,i);else return{error:rn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await at(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:j(u)}}return{error:rn.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return ae(n)}}function fg(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 mg(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(f=>f.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(f=>f.name===s?!1:!!f.name.startsWith(d+".")).forEach(f=>l.push(f.path)),l.length===0&&d.length>=3&&c.filter(m=>{let g=m.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(m=>l.push(m.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var Rs=y(()=>{"use strict";je();It();Re();Pt();ce()});import{existsSync as Do,readFileSync as tE,writeFileSync as nE,mkdirSync as rE,rmSync as Fo,readdirSync as oE,statSync as iE}from"node:fs";import{join as mt}from"node:path";import{createHash as sE}from"node:crypto";function tB(e){return jl(e)}function jl(e){return mt(e,"tmp","clone")}function yg(e){return mt(e,"tmp","tree")}function dE(e){return e?`__sp_${sE("sha256").update(e).digest("hex").substring(0,6)}`:""}function bg(e,t,n,r,o){let i=`${r}${dE(o)}`;return mt(jl(e),t,n,i)}function Ul(e,t,n,r){return mt(yg(e),t,n,r)}function pE(e){return typeof e=="object"&&e!==null}function fE(e){if(!pE(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 $l(e){let t=mt(e,hg);if(!Do(t))return null;try{return fE(JSON.parse(tE(t,"utf-8")))}catch{return null}}function No(e,t){try{nE(mt(e,hg),JSON.stringify(t,null,2),"utf-8")}catch{}}function Rg(e){return Date.now()<new Date(e.expiresAt).getTime()}function Go(e){let t=$l(e);return t?Rg(t)?Do(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function mE(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return aE}function gE(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return lE}function hE(){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 uE}function Ho(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+mE()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function In(e){let t=mt(e,"..");try{Do(t)||rE(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 Ps(e){try{Do(e)&&Fo(e,{recursive:!0,force:!0})}catch{}}function Io(e){try{return iE(e).isDirectory()}catch{return!1}}function _n(e){try{return oE(e)}catch{return[]}}function*Sg(e){for(let t of _n(e)){let n=mt(e,t);if(Io(n))for(let r of _n(n)){let o=mt(n,r);if(Io(o))for(let i of _n(o)){let s=mt(o,i);Io(s)&&(yield s)}}}}function gg(e){for(let t of[..._n(e)]){let n=mt(e,t);if(Io(n)){for(let r of[..._n(n)]){let o=mt(n,r);if(Io(o)&&_n(o).length===0)try{Fo(o,{recursive:!0,force:!0})}catch{}}if(_n(n).length===0)try{Fo(n,{recursive:!0,force:!0})}catch{}}}}function yE(e){let t=0;for(let n of Sg(e))try{let r=$l(n);(!r||!Rg(r))&&(Fo(n,{recursive:!0,force:!0}),t++)}catch{}return t}function bE(e){let t=[];for(let n of Sg(e)){let r=$l(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??Oo(n)})}return t}function RE(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{Fo(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Pg(e){if(!Do(e))return 0;let t=0;try{t+=yE(e)}catch{return t}gg(e);let n=RE(bE(e),gE(),hE());return t+=n,n>0&&gg(e),t}function Ss(e){return Pg(jl(e))}function Mo(e){return Pg(yg(e))}function nB(e){Rr||(Ss(e),Mo(e),Rr=setInterval(()=>{Ss(e),Mo(e)},cE),Rr.unref())}function rB(){Rr&&(clearInterval(Rr),Rr=null)}var aE,cE,lE,uE,hg,Rr,Cs=y(()=>{"use strict";$t();aE=1440*60*1e3,cE=600*1e3,lE=2*1024*1024*1024,uE=50,hg=".octocode-clone-meta.json",Rr=null});import{writeFileSync as Eg,mkdirSync as ql,existsSync as zo,rmSync as SE,readdirSync as PE,statSync as Tg}from"node:fs";import{join as xs,dirname as kg,resolve as Wl,sep as Vl}from"node:path";function xg(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function EE(e){return Object.values(e).every(t=>t===0)}function wg(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 Ag(e,t,n,r,o,i=!1){let s=ir(),a=Ul(s,e,t,r),c=Wl(xs(a,n));if(!c.startsWith(a+Vl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Go(a);if(l.hit&&!i&&zo(c)){let O=vE(c,a),B=xg();return{localPath:c,repoRoot:a,files:O.files,fileCount:O.fileCount,totalSize:O.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:O.fileCount,eligibleFileCount:O.fileCount,savedFileCount:O.fileCount,skipped:B,limits:Cg,warnings:wg(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await be(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:p}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(p))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=p,m=xg(),g=[];for(let O of f){if(O.type!=="file"){m.nonFile+=1;continue}if(!O.download_url){m.missingDownloadUrl+=1;continue}if(O.size>vg){m.oversized+=1;continue}let B=ig(O.name,{lowercase:!0,leadingDot:!0});if(wE.has(B)){m.binary+=1;continue}g.push(O)}m.fileLimit=Math.max(0,g.length-Kl);let b=g.slice(0,Kl),w=o?.token,S=await TE(b,CE,w);m.fetchFailed=b.length-S.length;let T=0,A=[];for(let O=0;O<S.length;O+=1){let{entry:B,content:G}=S[O];if(T+G.length>Og){m.totalSizeLimit=S.length-O;break}T+=G.length,A.push({entry:B,content:G})}Mo(s),In(a),zo(c)&&SE(c,{recursive:!0,force:!0}),ql(c,{recursive:!0,mode:448});let _=[];for(let{entry:O,content:B}of A){let G=Wl(xs(a,O.path));if(!G.startsWith(a+Vl)){m.pathTraversal+=1;continue}let X=kg(G);zo(X)||ql(X,{recursive:!0,mode:448}),Eg(G,B,"utf-8"),_.push({path:O.path,size:B.length,type:"file"})}let k=Ho(e,t,r,"treeFetch",void 0,void 0,d);No(a,k);let x=EE(m),N=x,F=m.nonFile>0;return{localPath:c,repoRoot:a,files:_,fileCount:_.length,totalSize:T,complete:x,verified:N,...d?{commitSha:d}:{},...F?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:g.length,savedFileCount:_.length,skipped:m,limits:Cg,warnings:wg(x,N),cached:!1,expiresAt:k.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function Lg(e,t,n,r,o,i=!1){let s=ir(),a=Ul(s,e,t,r),c=Wl(xs(a,n));if(!c.startsWith(a+Vl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Go(a);if(!i&&l.hit&&zo(c))return{localPath:c,repoRoot:a,path:n,size:AE(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await bs({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 m="error"in u?u.error:void 0;throw new Error(m||`Failed to fetch ${e}/${t}/${n}`)}Mo(s),In(a);let d=kg(c);zo(d)||ql(d,{recursive:!0,mode:448}),Eg(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=Ho(e,t,p,"treeFetch");return No(a,f),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:p}}async function TE(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 OE(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 OE(e,t){try{let o=new URL(e);if(!kE.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(),xE);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 vE(e,t){let n=[],r=0;function o(i){let s;try{s=PE(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=xs(i,a);try{let l=Tg(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 AE(e){try{return Tg(e).size}catch{return 0}}var Kl,Og,vg,CE,xE,wE,Cg,kE,Yl=y(()=>{"use strict";$t();je();Rs();Cs();br();Kl=50,Og=5*1024*1024,vg=300*1024,CE=5,xE=1e4,wE=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"]),Cg={maxDirectoryFiles:Kl,maxTotalSize:Og,maxFileSize:vg};kE=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function ct(){try{return De().output.pagination.defaultCharLength}catch{return Tn.pagination.defaultCharLength}}function mB(e){let t=Math.min(Math.max(ct(),1),_g),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,_g)}var _g,Sr=y(()=>{"use strict";ot();_g=1e5});function Qo(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Wt(e){return Qo(e).length}var Pr=y(()=>{"use strict"});function LE(e,t,n){return M.byteSliceContent(e,t,n)}function ws(e,t){return M.byteToCharOffset(e,t)}function Ig(e,t){return M.charToByteOffset(e,t)}function Fg(e){return M.charToByteOffset(e,e.length)}function bB(e,t,n){let r=LE(e,t,t+n);return{charOffset:ws(e,t),charLength:r.length,text:r}}function Xl(e,t,n,r){return M.sliceContent(e,t,n,r)}var Jl=y(()=>{"use strict";we()});function Cr(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Fg(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,p,f,m,g;if(o==="bytes"){let b=Math.min(t,s),w=Math.min(b+n,s);d=ws(e,b),p=ws(e,w),p<i&&Ig(e,p)<w&&(p+=1);let S=Xl(e,d,p-d);c=S.text,d=S.charOffset,p=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,f=u<s;let T=r.actualOffset??b;m=Math.floor(T/a)+1,g=Math.max(m,Math.ceil(s/a))}else{let b=Xl(e,t,n);c=b.text,d=b.charOffset,p=b.charOffset+b.charLength,l=b.byteOffset,u=b.byteOffset+b.byteLength,f=p<i;let w=r.actualOffset??d;m=Math.floor(w/a)+1,g=Math.max(m,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:f?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:f?p:void 0,hasMore:f,estimatedTokens:Math.ceil(c.length/4),currentPage:m,totalPages:g}}function PB(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function Zl(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 CB(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
|
|
11
12
|
`){let l=e.lastIndexOf(`
|
|
12
13
|
`,o-1);o=l===-1?0:l+1}let i=o,s=0;for(;i<r;){let l=e.indexOf(`
|
|
13
|
-
`,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
|
|
14
|
-
`,t);return n===-1?void 0:n+1}function
|
|
15
|
-
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function
|
|
16
|
-
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=
|
|
17
|
-
`)}function
|
|
18
|
-
`),
|
|
19
|
-
`);let
|
|
20
|
-
`)
|
|
14
|
+
`,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 Bo=y(()=>{"use strict";Jl()});function FE(e){return e&&e.trim().length>0?e:IE}function Mg(e,t){return M.getSemanticBoundaryOffsets(e,FE(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function ME(e,t){let n=e.indexOf(`
|
|
15
|
+
`,t);return n===-1?void 0:n+1}function jo(e){let t=e.trimEnd().split(`
|
|
16
|
+
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function Uo(e,t,n){let r=ME(e,Math.max(0,t));if(r!==void 0)return Mg(e,n).find(o=>o>=r&&o>t)}function EB(e,t,n,r,o){if(!jo(e))return;let i=Uo(t,n,o);if(i===void 0)return;let s=i-n,a=`Page cut mid-block at char ${n}. Next top-level definition at char ${i}. Re-request with charLength=${r+s} to extend this page to the next boundary, or use charOffset=${n} to continue page-by-page.`;return{nextBlockChar:i,hint:a}}function Es(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=Mg(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<=_E?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var _E,IE,Ts=y(()=>{"use strict";we();_E=8e3,IE="__octocode_generic__.unknown"});function ks(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(`
|
|
17
|
+
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=M.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 Os=y(()=>{"use strict";we()});function NE(e){return DE.test(e.split(/[?#]/,1)[0]??e)}function Dg(e,t){return NE(t)?HE(GE(e)):null}function vs(e,t){let n=Dg(e,t);if(n===null||n.length===0)return null;let r=[];return Gg(n,r),r.join(`
|
|
18
|
+
`)}function Ng(e,t){let n=Dg(e,t);return n===null?null:n.map(Hg)}function GE(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 HE(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 Gg(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}`),Gg(n.children,t)}}function Hg(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(Hg)}}var DE,As=y(()=>{"use strict";DE=/\.(?:md|markdown|mdx)$/i});import{ContentSanitizer as zg}from"@octocodeai/octocode-engine/contentSanitizer";function zE(){let e=ct();return Math.min(e,8e3)}function $o(e,t){return{sourceChars:e,sourceBytes:t}}function Qg(e,t,n){let r=e.content??"",o=n??zE();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=Es(r,t,o,i),c=Cr(r,t,s),l;if(c.hasMore&&a==="char-limit"&&jo(c.paginatedContent)){let u=c.charOffset+c.charLength;l=Uo(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 Bg(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function jg(e,t,n,r,o,i,s,a,c=5,l,u,d,p="standard"){let f=e.length,m=Buffer.byteLength(e,"utf-8"),g=p==="standard"||p==="symbols",b=g?"standard":"none",w;if(p==="symbols"){let X=M.extractSignatures(e,o);if(X===null){let $=vs(e,o);if($!==null)return{owner:t,repo:n,path:o,content:$,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Wt(e),...$o(f,m),isPartial:!1,signaturesExtracted:!0,hints:[M.SIGNATURES_ONLY_HINT]};w=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(X!==null){let $=zg.sanitizeContent(X,o),Ae=M.applyContentViewMinification($.content,o),Le=[M.SIGNATURES_ONLY_HINT];return l&&Le.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),$.hasSecrets&&Le.push(`Secrets detected and redacted: ${$.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Ae,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Wt(e),...$o(f,m),isPartial:!1,signaturesExtracted:!0,hints:Le}}}let S=new Set,T=e,A=T.split(`
|
|
19
|
+
`),_=Wt(T),k=e,x,N,F=!1,O;if(i)k=e;else if(l){let X=d===!0,$;try{$=ks(A,l,c,u??!1,X)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:_,...$o(f,m),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($.matchCount===0){let oe=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${X?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${X?" (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:_,...$o(f,m),matchNotFound:!0,searchedFor:l,hints:oe}}k=$.lines.join(`
|
|
20
|
+
`);let Ae=$.matchRanges[0],Le=$.matchRanges[$.matchRanges.length-1];s=Ae.start,a=Le.end,x=Ae.start,N=Le.end,F=!0,$.matchRanges.length>1&&(O=$.matchRanges);let tn=$.matchingLines.slice(0,5).join(", "),nn=$.matchingLines.length>5?` and ${$.matchingLines.length-5} more`:"";S.add($.matchCount>1?`Found ${$.matchCount} occurrences of "${l}" on lines ${tn}${nn} \u2014 all shown as ${$.matchRanges.length} slice${$.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${$.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let X=s||1,$=a||_;if(X<1||X>_)k=e;else if($<X)k=e;else{let Ae=Math.max(1,X),Le=Math.min(_,$),tn=A.slice(Ae-1,Le);x=Ae,N=Le,F=!0,k=tn.join(`
|
|
21
|
+
`),$>_&&S.add(`Requested endLine ${$} adjusted to ${_} (file end)`)}}let B=zg.sanitizeContent(k,o);if(k=g?M.applyContentViewMinification(B.content,o):B.content,B.hasSecrets&&S.add(`Secrets detected and redacted: ${B.secretsDetected.join(", ")}`),B.warnings.length>0&&B.warnings.forEach(X=>S.add(X)),_>2e3&&p!=="symbols"&&!l&&!s&&!a&&!i){let X=Math.max(1,_-200);S.add(`Large file (${_} lines) \u2014 minify:"symbols" for an export index, or startLine=${X} for the tail.`)}let G=Array.from(S);return{owner:t,repo:n,path:o,content:k,...b!=="standard"&&{contentView:b},branch:r,totalLines:_,...$o(f,m),...F&&{startLine:x,endLine:N,isPartial:F},...O&&{matchRanges:O},...G.length>0&&{matchLocations:G},...(G.length>0||w)&&{warnings:[...w?[w]:[],...G]}}}var eu=y(()=>{"use strict";Sr();Se();we();Pr();Bo();Ts();Os();As()});async function Ug(e,t,n){let r=Ue("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await $e(r,async()=>await bs(e,t),{shouldCache:m=>"data"in m&&!m.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await jg(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,l=e.charOffset??0,u=e.charLength,d=e.fullContent===!0&&l===0&&u===void 0,p=a||d?c:Qg(c,l,u),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let m=await be(t),g=await $e(Ue("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>Bg(m,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});g&&(p.lastModified=g.lastModified,p.lastModifiedBy=g.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:o.rawResponseChars}}var tu=y(()=>{"use strict";je();qt();Rs();eu()});function qo(e,t=BE){let n=e?Qo(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function $g(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return M.filterPatch(e,r)}function qg(e){return e?M.filterPatch(e,{trimContext:!0,contextLines:QE}):""}var QE,BE,Wo=y(()=>{"use strict";we();Pr();QE=2,BE=20});import{ContentSanitizer as Wg}from"@octocodeai/octocode-engine/contentSanitizer";function nu(e){let t=Wg.sanitizeContent(e.title??""),n=e.body?Wg.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 Kg(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 Vo(e,t={}){let n=t.charOffset??0,r=t.charLength??jE,o=t.charLength??UE,i=typeof e.body=="string"?M.minifyMarkdownCore(e.body):e.body,s=Kg(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((m,g)=>{let b=m.commentType==="review_inline"?0:1,w=g.commentType==="review_inline"?0:1;return b-w}),c=a.filter(m=>m.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Vg),d=u.map(m=>{let g=Kg(m.body,n,o,!t.includeFullCommentDetails);return{...m,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),p=!t.includeFullCommentDetails&&(a.length>u.length||d.some(m=>"body_pagination"in m)),f=[...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.`]:[],...p?[`PR comments are paginated/summarized to ${Vg} 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(m=>({id:0,name:m,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((m,g)=>m+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((m,g)=>m+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(m=>({filename:m.filename,status:m.status,additions:m.additions,deletions:m.deletions,patch:m.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,...p?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||f.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...f]}}}function Ko(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 Ls(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?$g(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?qg(a.patch):a.patch}))}var jE,UE,Vg,Yo=y(()=>{"use strict";Wo();we();Sr();jE=ct(),UE=Math.round(ct()/4),Vg=3});import{ContentSanitizer as ru}from"@octocodeai/octocode-engine/contentSanitizer";function _s(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Yg(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Xg(e){let t=Yg(e);return t?t.discussion!==!1:!1}function Jg(e){let t=Yg(e);return t?t.reviewInline!==!1:!1}function Zg(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function eh(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function th(e){return!!e.content?.comments?.includeBots}function nh(e){let t=e.toLowerCase();return t.endsWith("[bot]")||$E.has(t.replace(/\[bot\]$/,""))}function ou(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
22
|
|
|
22
|
-
`).trim()}async function sh(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=U(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!ih(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=F.minifyMarkdownCore(nu(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:tu.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"discussion"}}),p=[];return u>0&&p.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:j(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:j([],0)}}}async function ah(e,t,n,r){try{let{items:o,rawResponseChars:i}=await ru(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return j(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:tu.sanitizeContent(F.minifyMarkdownCore(nu(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return j([],0)}}async function ch(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=U(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!ih(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=F.minifyMarkdownCore(nu(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:tu.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"review_inline",path:f.path,line:f.line??f.original_line??void 0,...f.in_reply_to_id!=null?{in_reply_to_id:f.in_reply_to_id}:{}}}),p=[];return u>0&&p.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:j(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:j([],0)}}}async function lh(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=eu(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=jo(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=U(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,Ms(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Ms(t))){let p=await uh(l,u,e.number);p&&(s+=le(p)??0,p.files=Fs(p.files,t),o.file_changes=p)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=eh(t),c=th(t);if(a||c){let{owner:l,repo:u}=jo(t);if(l&&u){let d=oh(t),p=()=>Promise.resolve({comments:j([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([a?sh(n,l,u,e.number,d):p(),c?ch(n,l,u,e.number,d):p()]);o.comments=[...f,...g],s+=(le(f)??0)+(le(g)??0);let S=[m,b].filter(C=>typeof C=="string");S.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...S])}}if(rh(t))try{let{owner:l,repo:u}=jo(t);if(l&&u){let d=await ah(n,l,u,e.number);s+=le(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(nh(t))try{let{owner:l,repo:u}=jo(t);if(l&&u){let d=await dh(l,u,e.number,t);d&&(s+=le(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 j(o,s)}async function ru(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=U(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function uh(e,t,n,r){let o=await pe(r),{items:i,rawResponseChars:s}=await ru(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return j({total_count:i.length,files:i},s)}async function bT(e,t,n,r){let o=await pe(r),{items:i,rawResponseChars:s}=await ru(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return j(i,s)}async function RT(e,t,n,r){try{let i=await(await pe(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return j(i.data.files||[],i.data)}catch{return null}}async function dh(e,t,n,r,o){let i=await bT(e,t,n,o);if(!i)return null;let s=le(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 Promise.all(a.map(async l=>{let u=await RT(e,t,l.sha,o),d=[];return u&&(s+=le(u)??0,d=Fs(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return j(c,s)}async function Ds(e,t,n,r){let{prData:o,sanitizationWarnings:i}=eu(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,Ms(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ms(t))try{let d=await uh(a,c,e.number,r);d&&(s+=le(d)??0,d.files=Fs(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=eh(t),u=th(t);if(l||u){let d=oh(t),p=()=>Promise.resolve({comments:j([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([l?sh(n,a,c,e.number,d):p(),u?ch(n,a,c,e.number,d):p()]);o.comments=[...f,...g],s+=(le(f)??0)+(le(g)??0);let S=[m,b].filter(C=>typeof C=="string");S.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...S])}if(rh(t))try{let d=await ah(n,a,c,e.number);s+=le(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(nh(t))try{let d=await dh(a,c,e.number,t,r);d&&(s+=le(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 j(o,s)}var yT,Ns=y(()=>{"use strict";be();Ge();$o();oe();yT=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function ST(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 mQ(e,t,n){let r=He("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode},n);return await ze(r,async()=>await ou(e,t),{shouldCache:i=>!i.error})}async function ou(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:qe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:qe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await pe(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Ds(a,e,i,t);return{pull_requests:[Uo(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:U(s.data)+(le(c)??0)}}catch(i){let s=re(i);return ST(s,qe.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 iu=y(()=>{"use strict";ft();Ge();wt();Mt();$o();Ns();oe()});function ph(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 fh(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 CT(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}}async function mh(e,t,n){let r=He("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await ze(r,async()=>await PT(e,t,n),{shouldCache:i=>!i.error})}async function PT(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await ou(e,t);let r=await pe(t);if(!ig(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await xT(r,e);let i=await CT(r,e),s=og(i);if(!s)return{pull_requests:[],total_count:0,error:qe.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}),p=d.data.items?.filter(O=>!!O.pull_request)||[],f=await Promise.all(p.map(async O=>await lh(O,i,r))),m=f.reduce((O,w)=>O+(le(w)??0),0),g=f.map(O=>Uo(O,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,S=Math.min(b,1e3),C=Math.min(Math.ceil(S/c),10),k=Math.min(l,Math.max(1,C)),_=k<C,E=Math.min(S,C*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:k,totalPages:C,perPage:c,totalMatches:S,reportedTotalMatches:b,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:b>S,hasMore:_,..._?{nextPage:k+1}:{}},rawResponseChars:U(d.data)+m}}catch(r){if(Pn(r))return fh(e);let o=re(r);return ph(o,qe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function xT(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 p=>await Ds(p,t,e))),c=a.reduce((p,f)=>p+(le(f)??0),0),l=a.map(p=>Uo(p,{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:U(s.data)+c}}catch(n){if(Pn(n))return fh(t);let r=re(n);return ph(r,qe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var su=y(()=>{"use strict";me();ft();Ge();wt();Eo();Mt();oe();$o();Ns();iu()});function wT(e){return e?e.includes('rel="next"'):!1}function gh(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 hh(e,t){try{let n=await pe(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=wT(i),a=o.data.map(u=>{let d=u.commit.author,p=u.commit.committer,f=p?.date??d?.date??"",m=u.commit.message,g=m.split(`
|
|
23
|
-
`)[0]??m;return{sha:u.sha,date:f,message:m,messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...p?{committer:{name:p.name??"unknown",email:p.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 Promise.all(a.map(async(u,d)=>{try{let p=o.data[d]?.sha??u.sha,f=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:p});if(e.type==="file"&&e.path){let m=e.path,g=f.data.files?.find(b=>b.filename===m||b.previous_filename===m);if(g){let b=g.patch!==void 0?gh(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...b!==void 0?{patch:b.patch,...b.patchPagination?{patchPagination:b.patchPagination}:{},diff:Bo(b.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let m=e.path,g=(f.data.files??[]).filter(w=>!m||w.filename.startsWith(m)).map(w=>{let H=w.patch!==void 0?gh(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...H!==void 0?{patch:H.patch,...H.patchPagination?{patchPagination:H.patchPagination}:{},diff:Bo(H.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),S=Math.max(1,e.itemsPerPage??20),C=g.length,k=Math.max(1,Math.ceil(C/S)),_=Math.min(b,k),E=(_-1)*S,O=g.slice(E,E+S);return{...u,files:O,filesPagination:{currentPage:_,totalPages:k,itemsPerPage:S,totalFiles:C,hasMore:_<k,..._<k?{nextFilePage:_+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 au=y(()=>{"use strict";Ge();wt();Qo()});function bh(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 Rh(e,t,n){let r=He("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await ze(r,async()=>await ET(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function TT(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(f){if(f?.status!==404)return re(f);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(f=>{let g=f.full_name.split("/"),b=g[0]||"",S=g[1]||"";return{owner:b,repo:S,defaultBranch:f.default_branch,stars:f.stargazers_count||0,description:f.description?f.description:"No description",url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at,pushedAt:f.pushed_at,visibility:f.visibility,...f.topics&&f.topics.length>0&&{topics:f.topics},...f.forks_count&&f.forks_count>0&&{forksCount:f.forks_count},...f.open_issues_count&&f.open_issues_count>0&&{openIssuesCount:f.open_issues_count},...f.language&&{language:f.language},...bh(f)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),p=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:p,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:U(i)}}async function ET(e,t){try{let n=await pe(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 TT({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=rg(e);if(!i.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||yh,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(C=>{let _=C.full_name.split("/"),E=_[0]||"",O=_[1]||"";return{owner:E,repo:O,defaultBranch:C.default_branch,stars:C.stargazers_count||0,description:C.description?C.description:"No description",url:C.html_url,createdAt:C.created_at,updatedAt:C.updated_at,pushedAt:C.pushed_at,visibility:C.visibility,...C.topics&&C.topics.length>0&&{topics:C.topics},...C.forks_count&&C.forks_count>0&&{forksCount:C.forks_count},...C.open_issues_count&&C.open_issues_count>0&&{openIssuesCount:C.open_issues_count},...C.language&&{language:C.language},...bh(C)}}),p=u.data.total_count,f=Math.min(p,1e3),m=Math.min(Math.ceil(f/s),10),g=Math.min(a,Math.max(1,m)),b=g<m,S=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:S,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:g+1}:{}}},status:200,headers:Rs(u.headers),rawResponseChars:U(u.data)}}catch(n){if(Pn(n)){let r=Math.min(e.limit||yh,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 yh,cu=y(()=>{"use strict";Ge();wt();Eo();Mt();ft();oe();Ss();me();yh=30});var Tn,qo=y(()=>{"use strict";Tn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function kT(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 OT(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 QQ(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...kT(e.estimatedTokens,n)),o.push(...OT(e)),o}function Gs(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Hs=y(()=>{"use strict"});function Sh(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:I,...v}=e;return v}let r=t.itemsPerPage??Tn.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,p=I=>{let v=I;d&&I.startsWith(d)&&(v=I.slice(d.length),v.startsWith("/")&&(v=v.slice(1)));let D=v.lastIndexOf("/");return D===-1?".":v.slice(0,D)},f=I=>{let v=I.lastIndexOf("/");return v===-1?I:I.slice(v+1)};for(let I of l){let v=p(I.path);u[v]||(u[v]={files:[],folders:[]});let D=f(I.path);I.type==="file"?u[v].files.push(D):u[v].folders.push(D)}for(let I of Object.keys(u)){let v=u[I];v&&(v.files.sort(),v.folders.sort())}let m=Object.create(null),g=Object.keys(u).sort((I,v)=>I==="."?-1:v==="."?1:I.localeCompare(v));for(let I of g){let v=u[I];v&&(m[I]=v)}let b=l.filter(I=>I.type==="file").length,S=l.filter(I=>I.type==="dir").length,C=n.filter(I=>I.type==="file").length,k=n.filter(I=>I.type==="dir").length,_=o<s,E={currentPage:o,totalPages:s,hasMore:_,..._?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},O=Gs(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:S,allFiles:C,allFolders:k}),w,H=e._cachedFileSizeMap;if(H){let I=new Set(l.filter(Q=>Q.type==="file").map(Q=>Q.path)),v=e.path==="/"?"":e.path,D=Object.create(null);for(let[Q,ee]of Object.entries(H))for(let[B,Me]of Object.entries(ee)){let Ee=Q==="."?v?`${v}/${B}`:B:v?`${v}/${Q}/${B}`:`${Q}/${B}`;I.has(Ee)&&(D[Q]||(D[Q]=Object.create(null)),D[Q][B]=Me)}Object.keys(D).length>0&&(w=D)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:C,totalFolders:k,truncated:_,filtered:!0,originalCount:i},structure:m,...w!==void 0&&{fileSizeMap:w},...H!==void 0&&{_cachedFileSizeMap:H},pagination:E,hints:O,rawResponseChars:e.rawResponseChars}}var lu=y(()=>{"use strict";qo();Hs()});import{RequestError as vT}from"octokit";function Ch(e){return e instanceof vT&&AT.has(e.status)}function uu(e,t){try{Object.defineProperty(e,Ph,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function du(e){if(typeof e!="object"||e===null)return 0;let t=e[Ph];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function pu(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return uu(j([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(m){if(Ch(m))throw m;return uu(j([],0),1)}let l=U(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(m=>m.type==="file"||m.type==="dir").map(m=>({name:m.name,path:m.path,type:m.type,size:"size"in m?m.size:void 0,download_url:"download_url"in m?m.download_url:void 0,url:m.url,html_url:m.html_url,git_url:m.git_url,sha:m.sha})),p=[...d],f=0;if(i<s){let m=d.filter(b=>b.type==="dir"),g=3;for(let b=0;b<m.length;b+=g){let S=m.slice(b,b+g),C=await Promise.allSettled(S.map(k=>pu(e,t,n,r,k.path,i+1,s,a)));for(let k of C)if(k.status==="fulfilled"){let _=k.value;l+=le(_)??0,f+=du(_),p.push(..._)}else{if(Ch(k.reason))throw k.reason;f+=1}}}return uu(j(p,l),f)}var Ph,AT,fu=y(()=>{"use strict";oe();Ph=Symbol.for("octocode.recursiveFetchFailures"),AT=new Set([401,403,429])});import{RequestError as LT}from"octokit";async function _T(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await Ze(t,n,i),s=a)}catch(c){let l=re(c);return{error:Un.NOT_FOUND.message(t,n,l.error),status:l.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s,...a!==void 0?{repoDefaultBranch:a}:{}}}catch(c){if(!(c instanceof LT&&c.status===404)){let u=re(c);return{error:Un.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let l=re(c);return{error:Un.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function IT(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function FT(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 xh(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function wh(e,t,n){let r=He("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await ze(r,async()=>await MT({...e,itemsPerPage:e.itemsPerPage??Tn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Sh(o,e):o}async function MT(e,t){try{let n=await pe(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await _T(n,r,o,c,i,t);if("error"in l)return l;let{data:u,workingBranch:d,repoDefaultBranch:p}=l,f=U(u),m=Array.isArray(u)?u:[u],g=IT(m),b=0;if(a>1){let Y=await pu(n,r,o,d,c,1,a);b=du(Y),f+=le(Y)??0,g=[...g,...Y].filter((Di,Ni,fP)=>fP.findIndex(mP=>mP.path===Di.path)===Ni)}let S=g.filter(Y=>Y.type==="dir"?!ko(Y.name):!mr(Y.path));S.sort((Y,Kr)=>{if(Y.type!==Kr.type)return Y.type==="dir"?-1:1;let Di=Y.path.split("/").length,Ni=Kr.path.split("/").length;return Di!==Ni?Di-Ni:Y.path.localeCompare(Kr.path)});let C=e.itemsPerPage??Tn.ENTRIES_PER_PAGE,k=e.page??1,_=S.length,E=Math.max(1,Math.ceil(_/C)),O=(k-1)*C,w=Math.min(O+C,_),H=S.slice(O,w),I=FT(H,c),v=e.includeSizes===!0?xh(S,c):void 0,D=v!==void 0?xh(H,c):void 0,Q=H.filter(Y=>Y.type==="file").length,ee=H.filter(Y=>Y.type==="dir").length,B=S.filter(Y=>Y.type==="file").length,Me=S.filter(Y=>Y.type==="dir").length,Ee=k<E,Ct={currentPage:k,totalPages:E,hasMore:Ee,...Ee?{nextPage:k+1}:{},entriesPerPage:C,totalEntries:_},dn=Gs(Ct,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:Q,pageFolders:ee,allFiles:B,allFolders:Me});return b>0&&dn.unshift(`Partial tree: ${b} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...p!==void 0&&{defaultBranch:p},path:c||"/",apiSource:!0,summary:{totalFiles:B,totalFolders:Me,truncated:Ee,filtered:!0,originalCount:S.length},structure:I,...D!==void 0&&{fileSizeMap:D},...v!==void 0&&{_cachedFileSizeMap:v},pagination:Ct,hints:dn,rawResponseChars:f,_cachedItems:S.map(Y=>({path:Y.path,type:Y.type}))}}catch(n){let r=re(n);return{error:Un.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var mu=y(()=>{"use strict";qo();Ge();wt();Mt();Hs();gr();ft();oe();lu();fu()});var Th,gu=y(()=>{"use strict";Th={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});function En(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function DT(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function NT(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 Vo=y(()=>{"use strict"});function Ce(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function GT(e){if(e.rateLimitRemaining===void 0&&e.retryAfter===void 0&&e.rateLimitReset===void 0)return;let t=e.rateLimitReset,n=t&&!isNaN(t)?Math.floor(t/1e3):Math.floor(Date.now()/1e3)+(e.retryAfter??3600);return{remaining:e.rateLimitRemaining??0,reset:n,retryAfter:e.retryAfter}}function Nt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:GT(e)}}function zs(e){return HT(e)?Nt({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function HT(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||zT(n)}function zT(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var gt=y(()=>{"use strict"});function Eh(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function BT(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,...Eh(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function QT(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,...Eh(e.pagination)},nonExistentScope:e.nonExistentScope}}async function kh(e,t,n=Ce){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await dg(s,t);return En(a)?Nt(a):a.data?{data:BT(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??U(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Oh(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 Rh(n,t);return"error"in r?zs(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:QT(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??U(r.data)}}var hu=y(()=>{"use strict";Il();cu();Vo();oe();gt();gt()});function jT(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:$T(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function $T(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 vh(e,t,n=Ce){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Vg(i,t);if(En(s))return Nt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:jT(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??U(s.data),...a?.length?{hints:a}:{}}}var yu=y(()=>{"use strict";Zl();Vo();oe();gt();gt()});function VT(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function WT(e,t,n=Ce){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...VT(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Ah(e,t,n=Ce){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await mh(s,t);return a.error?Nt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:WT(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??U(a)}}var bu=y(()=>{"use strict";su();oe();gt();gt()});function YT(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 Lh(e,t,n=Ce){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await wh(i,t);return"error"in s?zs(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:YT(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??U(s)}}var Ru=y(()=>{"use strict";mu();oe();gt();gt()});var Bs,Su=y(()=>{"use strict";hu();yu();bu();Ru();wt();Ge();gu();gt();Bs=class{type="github";capabilities=Th.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await kh(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await vh(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Oh(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Ah(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Lh(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Ce(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ze(n,r,this.authInfo)}handleError(t){let n=re(t);return Nt(n)}}});import{createHash as JT}from"crypto";function _h(e){return Date.now()-e.createdAt<ZT}function eE(){for(let[e,t]of ht.entries())_h(t)||ht.delete(e);if(ht.size>Cu){let e=[...ht.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=ht.size-Cu;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&ht.delete(r[0])}}}function tE(e){return e?JT("sha256").update(e).digest("hex").slice(0,16):"default"}function nE(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 rE(e,t){let n=nE(t?.baseUrl||"default"),r=tE(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Pu(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=rE(e,t),r=ht.get(n);if(r&&_h(r))return r.lastAccessedAt=Date.now(),r.provider;r&&ht.delete(n),ht.size>=Cu&&eE();let o=new Bs({...t,type:e}),i=Date.now();return ht.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function NU(){ht.clear()}async function Ih(){try{return Pu("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
|
|
24
|
-
`),[{provider:"github",ok:!1,error:t}]}}var
|
|
25
|
-
`}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:
|
|
26
|
-
${n.warnings.map(c=>`- ${c}`).join(`
|
|
27
|
-
`)}`),n.hints?.length&&a.push(`Hints:
|
|
28
|
-
${n.hints.map(c=>`- ${c}`).join(`
|
|
29
|
-
`)}`),a.length>0&&t.push(Us.system(a.join(`
|
|
23
|
+
`).trim()}async function rh(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=j(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!nh(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=M.minifyMarkdownCore(ou(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:ru.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"discussion"}}),p=[];return u>0&&p.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:q(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:q([],0)}}}async function oh(e,t,n,r){try{let{items:o,rawResponseChars:i}=await iu(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return q(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:ru.sanitizeContent(M.minifyMarkdownCore(ou(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return q([],0)}}async function ih(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=j(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!nh(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=M.minifyMarkdownCore(ou(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:ru.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"review_inline",path:f.path,line:f.line??f.original_line??void 0,...f.in_reply_to_id!=null?{in_reply_to_id:f.in_reply_to_id}:{}}}),p=[];return u>0&&p.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:q(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:q([],0)}}}async function sh(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=nu(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=Ko(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=j(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,_s(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),_s(t))){let p=await ah(l,u,e.number);p&&(s+=me(p)??0,p.files=Ls(p.files,t),o.file_changes=p)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=Xg(t),c=Jg(t);if(a||c){let{owner:l,repo:u}=Ko(t);if(l&&u){let d=th(t),p=()=>Promise.resolve({comments:q([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([a?rh(n,l,u,e.number,d):p(),c?ih(n,l,u,e.number,d):p()]);o.comments=[...f,...g],s+=(me(f)??0)+(me(g)??0);let w=[m,b].filter(S=>typeof S=="string");w.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...w])}}if(eh(t))try{let{owner:l,repo:u}=Ko(t);if(l&&u){let d=await oh(n,l,u,e.number);s+=me(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(Zg(t))try{let{owner:l,repo:u}=Ko(t);if(l&&u){let d=await ch(l,u,e.number,t);d&&(s+=me(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 q(o,s)}async function iu(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=j(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function ah(e,t,n,r){let o=await be(r),{items:i,rawResponseChars:s}=await iu(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return q({total_count:i.length,files:i},s)}async function qE(e,t,n,r){let o=await be(r),{items:i,rawResponseChars:s}=await iu(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return q(i,s)}async function WE(e,t,n,r){try{let i=await(await be(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return q(i.data.files||[],i.data)}catch{return null}}async function ch(e,t,n,r,o){let i=await qE(e,t,n,o);if(!i)return null;let s=me(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 Promise.all(a.map(async l=>{let u=await WE(e,t,l.sha,o),d=[];return u&&(s+=me(u)??0,d=Ls(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return q(c,s)}async function Is(e,t,n,r){let{prData:o,sanitizationWarnings:i}=nu(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,_s(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),_s(t))try{let d=await ah(a,c,e.number,r);d&&(s+=me(d)??0,d.files=Ls(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=Xg(t),u=Jg(t);if(l||u){let d=th(t),p=()=>Promise.resolve({comments:q([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([l?rh(n,a,c,e.number,d):p(),u?ih(n,a,c,e.number,d):p()]);o.comments=[...f,...g],s+=(me(f)??0)+(me(g)??0);let w=[m,b].filter(S=>typeof S=="string");w.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...w])}if(eh(t))try{let d=await oh(n,a,c,e.number);s+=me(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(Zg(t))try{let d=await ch(a,c,e.number,t,r);d&&(s+=me(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 q(o,s)}var $E,Fs=y(()=>{"use strict";we();je();Yo();ce();$E=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function VE(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 fj(e,t,n){let r=Ue("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode},n);return await $e(r,async()=>await su(e,t),{shouldCache:i=>!i.error})}async function su(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:Xe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:Xe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await be(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Is(a,e,i,t);return{pull_requests:[Vo(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:j(s.data)+(me(c)??0)}}catch(i){let s=ae(i);return VE(s,Xe.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 au=y(()=>{"use strict";Pt();je();It();qt();Yo();Fs();ce()});function lh(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 uh(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 KE(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 YE(e,t){return Ue("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},t)}async function dh(e,t,n){let r=YE(e,n);return await $e(r,async()=>await XE(e,t,n),{shouldCache:i=>!i.error})}async function XE(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await su(e,t);let r=await be(t);if(!rg(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await JE(r,e);let i=await KE(r,e),s=ng(i);if(!s)return{pull_requests:[],total_count:0,error:Xe.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}),p=d.data.items?.filter(k=>!!k.pull_request)||[],f=await Promise.all(p.map(async k=>await sh(k,i,r))),m=f.reduce((k,x)=>k+(me(x)??0),0),g=f.map(k=>Vo(k,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,w=Math.min(b,1e3),S=Math.min(Math.ceil(w/c),10),T=Math.min(l,Math.max(1,S)),A=T<S,_=Math.min(w,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:T,totalPages:S,perPage:c,totalMatches:w,reportedTotalMatches:b,reachableTotalMatches:_,totalMatchesKind:"reported",totalMatchesCapped:b>w,hasMore:A,...A?{nextPage:T+1}:{}},rawResponseChars:j(d.data)+m}}catch(r){if(Ln(r))return uh(e);let o=ae(r);return lh(o,Xe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function JE(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 p=>await Is(p,t,e))),c=a.reduce((p,f)=>p+(me(f)??0),0),l=a.map(p=>Vo(p,{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:j(s.data)+c}}catch(n){if(Ln(n))return uh(t);let r=ae(n);return lh(r,Xe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var cu=y(()=>{"use strict";Se();Pt();je();It();Lo();qt();ce();Yo();Fs();au()});function ZE(e){return e?e.includes('rel="next"'):!1}function ph(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 fh(e,t){try{let n=await be(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=ZE(i),a=o.data.map(u=>{let d=u.commit.author,p=u.commit.committer,f=p?.date??d?.date??"",m=u.commit.message,g=m.split(`
|
|
24
|
+
`)[0]??m;return{sha:u.sha,date:f,message:m,messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...p?{committer:{name:p.name??"unknown",email:p.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 Promise.all(a.map(async(u,d)=>{try{let p=o.data[d]?.sha??u.sha,f=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:p});if(e.type==="file"&&e.path){let m=e.path,g=f.data.files?.find(b=>b.filename===m||b.previous_filename===m);if(g){let b=g.patch!==void 0?ph(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...b!==void 0?{patch:b.patch,...b.patchPagination?{patchPagination:b.patchPagination}:{},diff:qo(b.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let m=e.path,g=(f.data.files??[]).filter(x=>!m||x.filename.startsWith(m)).map(x=>{let N=x.patch!==void 0?ph(x.patch,e.charOffset,e.charLength):void 0;return{filename:x.filename,status:x.status,additions:x.additions,deletions:x.deletions,...N!==void 0?{patch:N.patch,...N.patchPagination?{patchPagination:N.patchPagination}:{},diff:qo(N.patch)}:{},...x.previous_filename?{previousFilename:x.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),w=Math.max(1,e.itemsPerPage??20),S=g.length,T=Math.max(1,Math.ceil(S/w)),A=Math.min(b,T),_=(A-1)*w,k=g.slice(_,_+w);return{...u,files:k,filesPagination:{currentPage:A,totalPages:T,itemsPerPage:w,totalFiles:S,hasMore:A<T,...A<T?{nextFilePage:A+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 ae(n)}}var lu=y(()=>{"use strict";je();It();Wo()});function gh(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 hh(e,t,n){let r=Ue("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await $e(r,async()=>await tT(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function eT(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(f){if(f?.status!==404)return ae(f);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return ae(g)}}let a=i.map(f=>{let g=f.full_name.split("/"),b=g[0]||"",w=g[1]||"";return{owner:b,repo:w,defaultBranch:f.default_branch,stars:f.stargazers_count||0,description:f.description?f.description:"No description",url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at,pushedAt:f.pushed_at,visibility:f.visibility,...f.topics&&f.topics.length>0&&{topics:f.topics},...f.forks_count&&f.forks_count>0&&{forksCount:f.forks_count},...f.open_issues_count&&f.open_issues_count>0&&{openIssuesCount:f.open_issues_count},...f.language&&{language:f.language},...gh(f)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),p=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:p,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:j(i)}}async function tT(e,t){try{let n=await be(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 eT({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=tg(e);if(!i.trim())return{error:Xe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||mh,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 A=S.full_name.split("/"),_=A[0]||"",k=A[1]||"";return{owner:_,repo:k,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},...gh(S)}}),p=u.data.total_count,f=Math.min(p,1e3),m=Math.min(Math.ceil(f/s),10),g=Math.min(a,Math.max(1,m)),b=g<m,w=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:w,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:g+1}:{}}},status:200,headers:hs(u.headers),rawResponseChars:j(u.data)}}catch(n){if(Ln(n)){let r=Math.min(e.limit||mh,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 ae(n)}}var mh,uu=y(()=>{"use strict";je();It();Lo();qt();Pt();ce();ys();Se();mh=30});var Fn,Xo=y(()=>{"use strict";Fn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function nT(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 rT(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 Qj(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...nT(e.estimatedTokens,n)),o.push(...rT(e)),o}function Ms(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Ds=y(()=>{"use strict"});function yh(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:F,...O}=e;return O}let r=t.itemsPerPage??Fn.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,p=F=>{let O=F;d&&F.startsWith(d)&&(O=F.slice(d.length),O.startsWith("/")&&(O=O.slice(1)));let B=O.lastIndexOf("/");return B===-1?".":O.slice(0,B)},f=F=>{let O=F.lastIndexOf("/");return O===-1?F:F.slice(O+1)};for(let F of l){let O=p(F.path);u[O]||(u[O]={files:[],folders:[]});let B=f(F.path);F.type==="file"?u[O].files.push(B):u[O].folders.push(B)}for(let F of Object.keys(u)){let O=u[F];O&&(O.files.sort(),O.folders.sort())}let m=Object.create(null),g=Object.keys(u).sort((F,O)=>F==="."?-1:O==="."?1:F.localeCompare(O));for(let F of g){let O=u[F];O&&(m[F]=O)}let b=l.filter(F=>F.type==="file").length,w=l.filter(F=>F.type==="dir").length,S=n.filter(F=>F.type==="file").length,T=n.filter(F=>F.type==="dir").length,A=o<s,_={currentPage:o,totalPages:s,hasMore:A,...A?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},k=Ms(_,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:w,allFiles:S,allFolders:T}),x,N=e._cachedFileSizeMap;if(N){let F=new Set(l.filter(G=>G.type==="file").map(G=>G.path)),O=e.path==="/"?"":e.path,B=Object.create(null);for(let[G,X]of Object.entries(N))for(let[$,Ae]of Object.entries(X)){let Le=G==="."?O?`${O}/${$}`:$:O?`${O}/${G}/${$}`:`${G}/${$}`;F.has(Le)&&(B[G]||(B[G]=Object.create(null)),B[G][$]=Ae)}Object.keys(B).length>0&&(x=B)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:T,truncated:A,filtered:!0,originalCount:i},structure:m,...x!==void 0&&{fileSizeMap:x},...N!==void 0&&{_cachedFileSizeMap:N},pagination:_,hints:k,rawResponseChars:e.rawResponseChars}}var du=y(()=>{"use strict";Xo();Ds()});import{RequestError as oT}from"octokit";function bh(e){return e instanceof oT&&iT.has(e.status)}function pu(e,t){try{Object.defineProperty(e,Rh,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function fu(e){if(typeof e!="object"||e===null)return 0;let t=e[Rh];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function mu(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return pu(q([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(m){if(bh(m))throw m;return pu(q([],0),1)}let l=j(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(m=>m.type==="file"||m.type==="dir").map(m=>({name:m.name,path:m.path,type:m.type,size:"size"in m?m.size:void 0,download_url:"download_url"in m?m.download_url:void 0,url:m.url,html_url:m.html_url,git_url:m.git_url,sha:m.sha})),p=[...d],f=0;if(i<s){let m=d.filter(b=>b.type==="dir"),g=3;for(let b=0;b<m.length;b+=g){let w=m.slice(b,b+g),S=await Promise.allSettled(w.map(T=>mu(e,t,n,r,T.path,i+1,s,a)));for(let T of S)if(T.status==="fulfilled"){let A=T.value;l+=me(A)??0,f+=fu(A),p.push(...A)}else{if(bh(T.reason))throw T.reason;f+=1}}}return pu(q(p,l),f)}var Rh,iT,gu=y(()=>{"use strict";ce();Rh=Symbol.for("octocode.recursiveFetchFailures"),iT=new Set([401,403,429])});import{RequestError as sT}from"octokit";async function aT(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await at(t,n,i),s=a)}catch(c){let l=ae(c);return{error:Zn.NOT_FOUND.message(t,n,l.error),status:l.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s,...a!==void 0?{repoDefaultBranch:a}:{}}}catch(c){if(!(c instanceof sT&&c.status===404)){let u=ae(c);return{error:Zn.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let l=ae(c);return{error:Zn.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function cT(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function lT(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 Sh(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function Ph(e,t,n){let r=Ue("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await $e(r,async()=>await uT({...e,itemsPerPage:e.itemsPerPage??Fn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?yh(o,e):o}async function uT(e,t){try{let n=await be(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await aT(n,r,o,c,i,t);if("error"in l)return l;let{data:u,workingBranch:d,repoDefaultBranch:p}=l,f=j(u),m=Array.isArray(u)?u:[u],g=cT(m),b=0;if(a>1){let oe=await mu(n,r,o,d,c,1,a);b=fu(oe),f+=me(oe)??0,g=[...g,...oe].filter((oo,zi,EC)=>EC.findIndex(TC=>TC.path===oo.path)===zi)}let w=g.filter(oe=>oe.type==="dir"?!_o(oe.name):!yr(oe.path));w.sort((oe,vt)=>{if(oe.type!==vt.type)return oe.type==="dir"?-1:1;let oo=oe.path.split("/").length,zi=vt.path.split("/").length;return oo!==zi?oo-zi:oe.path.localeCompare(vt.path)});let S=e.itemsPerPage??Fn.ENTRIES_PER_PAGE,T=e.page??1,A=w.length,_=Math.max(1,Math.ceil(A/S)),k=(T-1)*S,x=Math.min(k+S,A),N=w.slice(k,x),F=lT(N,c),O=e.includeSizes===!0?Sh(w,c):void 0,B=O!==void 0?Sh(N,c):void 0,G=N.filter(oe=>oe.type==="file").length,X=N.filter(oe=>oe.type==="dir").length,$=w.filter(oe=>oe.type==="file").length,Ae=w.filter(oe=>oe.type==="dir").length,Le=T<_,tn={currentPage:T,totalPages:_,hasMore:Le,...Le?{nextPage:T+1}:{},entriesPerPage:S,totalEntries:A},nn=Ms(tn,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:G,pageFolders:X,allFiles:$,allFolders:Ae});return b>0&&nn.unshift(`Partial tree: ${b} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...p!==void 0&&{defaultBranch:p},path:c||"/",apiSource:!0,summary:{totalFiles:$,totalFolders:Ae,truncated:Le,filtered:!0,originalCount:w.length},structure:F,...B!==void 0&&{fileSizeMap:B},...O!==void 0&&{_cachedFileSizeMap:O},pagination:tn,hints:nn,rawResponseChars:f,_cachedItems:w.map(oe=>({path:oe.path,type:oe.type}))}}catch(n){let r=ae(n);return{error:Zn.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var hu=y(()=>{"use strict";Xo();je();It();qt();Ds();br();Pt();ce();du();gu()});var Ch,yu=y(()=>{"use strict";Ch={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});function Mn(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function dT(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function pT(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 Jo=y(()=>{"use strict"});function ke(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function fT(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 Vt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:fT(e)}}function Ns(e){return mT(e)?Vt({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 mT(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||gT(n)}function gT(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var xt=y(()=>{"use strict"});function xh(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function hT(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,...xh(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function yT(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,...xh(e.pagination)},nonExistentScope:e.nonExistentScope}}async function wh(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await lg(s,t);return Mn(a)?Vt(a):a.data?{data:hT(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Eh(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 hh(n,t);return"error"in r?Ns(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:yT(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??j(r.data)}}var bu=y(()=>{"use strict";Fl();uu();Jo();ce();xt();xt()});function RT(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:ST(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function ST(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 Th(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ug(i,t);if(Mn(s))return Vt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:RT(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s.data),...a?.length?{hints:a}:{}}}var Ru=y(()=>{"use strict";tu();Jo();ce();xt();xt()});function CT(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function xT(e,t,n=ke){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,...CT(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function kh(e,t,n=ke){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 dh(s,t);return a.error?Vt({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:xT(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a)}}var Su=y(()=>{"use strict";cu();ce();xt();xt()});function ET(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 Oh(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ph(i,t);return"error"in s?Ns(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:ET(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s)}}var Pu=y(()=>{"use strict";hu();ce();xt();xt()});var Gs,Cu=y(()=>{"use strict";bu();Ru();Su();Pu();It();je();yu();xt();Gs=class{type="github";capabilities=Ch.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await wh(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Th(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Eh(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await kh(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Oh(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=ke(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return at(n,r,this.authInfo)}handleError(t){let n=ae(t);return Vt(n)}}});import{createHash as kT}from"crypto";function vh(e){return Date.now()-e.createdAt<OT}function vT(){for(let[e,t]of wt.entries())vh(t)||wt.delete(e);if(wt.size>xu){let e=[...wt.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=wt.size-xu;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&wt.delete(r[0])}}}function AT(e){return e?kT("sha256").update(e).digest("hex").slice(0,16):"default"}function LT(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 _T(e,t){let n=LT(t?.baseUrl||"default"),r=AT(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function wu(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=_T(e,t),r=wt.get(n);if(r&&vh(r))return r.lastAccessedAt=Date.now(),r.provider;r&&wt.delete(n),wt.size>=xu&&vT();let o=new Gs({...t,type:e}),i=Date.now();return wt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function DU(){wt.clear()}async function Ah(){try{return wu("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 OT,xu,wt,Hs=y(()=>{"use strict";Cu();OT=3600*1e3,xu=20,wt=new Map});import{ContentSanitizer as IT}from"@octocodeai/octocode-engine/contentSanitizer";function FT(){try{return De().output.format}catch{return"yaml"}}function QU(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 Et(e){if(e==null)return e;if(typeof e=="string")return IT.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Et(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Et(r);return t}return e}function BU(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(`
|
|
30
27
|
|
|
31
|
-
`)))}if(t.push(Us.assistant(r.summary)),r.details){let a=r.format==="json"||r.format==="yaml"?r.format:void 0;t.push(Us.data(r.details,a))}if(o){let a=o.emoji?`${o.emoji} ${o.message}`:o.message;t.push(Us.user(a))}return{content:t,structuredContent:iE(i),isError:!!s}}function iE(e){if(e==null)return;let t=Sr(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Tt(t):Tt({data:t})}function sE(e){return e==null||typeof e!="string"?"":wu.sanitizeContent(e).content}function Tt(e){if(e==null)return e;if(typeof e=="string")return wu.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Tt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Tt(r);return t}return e}function $U(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
|
|
32
|
-
|
|
33
|
-
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Wo(e,t){let n=Sr(e)??{},r=Fh(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;return r==="json"?i=JSON.stringify(qs(n,t||o),null,2):i=F.jsonToYamlString(n,{keysPriority:t||o}),wu.sanitizeContent(i).content}function qs(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>qs(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=qs(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=qs(n[o],t));return r}function cE(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=>aE.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Sr(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=>Sr(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(cE(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Sr(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 Us,js,jU,aE,Ko=y(()=>{"use strict";Ae();be();xu();Us={system(e,t=1){return{type:"text",text:e,annotations:{audience:["assistant"],priority:t,role:"system"}}},assistant(e,t=.8){return{type:"text",text:e,annotations:{audience:["assistant","user"],priority:t,role:"assistant"}}},user(e,t=.6){return{type:"text",text:e,annotations:{audience:["user"],priority:t,role:"user"}}},data(e,t){let n=t??Fh(),r;try{r=n==="yaml"?F.jsonToYamlString(Sr(e)):JSON.stringify(Sr(e),null,2)}catch{r=`error: "Data serialization failed"
|
|
34
|
-
`}return{type:"text",text:sE(r),annotations:{audience:["assistant"],priority:.3,role:"assistant"}}}},js={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}"};jU={success(e,t,n){return $s({system:n?{hints:n}:void 0,assistant:{summary:e},user:{message:"Operation completed",emoji:js.success},data:t})},empty(e,t){return $s({system:{hints:t||["Try broader search terms","Check spelling"]},assistant:{summary:e},user:{message:"No results found",emoji:js.empty},data:{status:"empty",results:[]}})},error(e,t){return $s({system:{instructions:"Tool execution failed. Error details provided for self-correction."},assistant:{summary:`Error: ${e}`},user:{message:"An error occurred",emoji:js.error},data:{status:"error",error:e,details:t},isError:!0})},paginated(e,t,n,r){return $s({system:{pagination:{currentPage:n.page,totalPages:n.total,hasMore:n.hasMore},hints:r},assistant:{summary:e},user:{message:`Page ${n.page} of ${n.total}`,emoji:n.hasMore?"\u{1F4C4}":js.success},data:t})}};aE=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"])});import{z as Vs}from"zod";function G(e,t){return Vs.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Vs.number().int().min(e).max(t))}function ie(e,t={}){let{maxQueries:n=5}=t;return Vs.object({queries:Vs.array(e).min(1).max(n).describe("Parallel queries."),...lE}).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 ae,Cr,Pr,lE,Be=y(()=>{"use strict";me();ae=G(1,1e3).optional().default(1),Cr=G(0,100).optional(),Pr=G(1,1e9).optional(),lE={responseCharOffset:G(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:G(1,5e4).optional().describe("Full-response char window.")}});import{z as Oe}from"zod";function JU(e){return e.extend(Qe)}var uE,Qe,Gt=y(()=>{"use strict";uE=Oe.object({currentPage:Oe.number(),totalPages:Oe.number(),hasMore:Oe.boolean(),charOffset:Oe.number(),charLength:Oe.number(),totalChars:Oe.number(),nextCharOffset:Oe.number().optional()}).optional(),Qe={hints:Oe.array(Oe.string()).optional(),base:Oe.string().optional(),shared:Oe.record(Oe.string(),Oe.union([Oe.string(),Oe.number(),Oe.boolean()])).optional(),responsePagination:uE}});function dE(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function M(e,t,n={}){let{extra:r}=n,o={status:"error"};if(dE(e))o.error=e;else if(Ac(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Cf(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:j(o,n.rawResponse)}function Ue(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:M(i,t,{toolName:n.toolName})}}var Ws=y(()=>{"use strict";Bi();oe()});async function ij(e,t,n){if(e)try{await e(t,n)}catch{return}}function _e(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:j(s,o.rawResponse)}function Ks(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 M(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Ie(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return M(i,t)}var Fe=y(()=>{"use strict";Ws();oe()});async function Ve({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Ie(o,t,r,e)}}var Ht=y(()=>{"use strict";Fe()});import{spawn as Tu}from"child_process";function ku(e={},t=Ys){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function kn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Ys,maxOutputSize:a=pE}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),p={cwd:o,env:ku(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=Tu(e,t,p)}catch(C){c({stdout:"",stderr:"",exitCode:null,success:!1,error:C instanceof Error?C:new Error(`Failed to spawn command '${e}'`)});return}let m,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{f.kill("SIGTERM")}catch{}m=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},Eu),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),b=()=>{clearTimeout(g),m!==void 0&&(clearTimeout(m),m=void 0)},S=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{f.kill("SIGKILL")}catch{}b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};f.stdout?.on("data",C=>{if(l.killed)return;let k=C.toString();l.totalOutputSize+=Buffer.byteLength(k),!S()&&l.stdoutChunks.push(k)}),f.stderr?.on("data",C=>{if(l.killed)return;let k=C.toString();l.totalOutputSize+=Buffer.byteLength(k),!S()&&l.stderrChunks.push(k)}),f.on("close",C=>{l.killed||(b(),c({stdout:u(),stderr:d(),exitCode:C,success:C===0}))}),f.on("error",C=>{l.killed||(l.killed=!0,b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:C}))})})}function Dh(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Ys}=r,a;try{a=Tu(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:ku({},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{}},Eu),o(!1)}},n);a.on("close",d=>{l(),i||o(d===0)}),a.on("error",()=>{l(),i||o(!1)})})}function fj(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=Yo,maxOutputSize:l=fE}=r,u;try{u=Tu(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:ku({},c)})}catch{o(null);return}let d,p=()=>{clearTimeout(f),d!==void 0&&(clearTimeout(d),d=void 0)};u.stdout?.on("data",m=>{if(i)return;let g=m.toString();if(a+=Buffer.byteLength(g),a>l){if(!i){i=!0;try{u.kill("SIGKILL")}catch{}p(),o(null)}return}s.push(g)}),u.stderr?.on("data",()=>{});let f=setTimeout(()=>{if(!i){i=!0;try{u.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},Eu),o(null)}},n);u.on("close",m=>{if(p(),!i)if(m===0){let g=s.join("").trim();o(g||null)}else o(null)}),u.on("error",()=>{p(),i||o(null)})})}function Xs(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 pj,Ys,Yo,Mh,pE,Eu,fE,Xo=y(()=>{"use strict";pj=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Ys=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Yo=[...Ys,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Mh=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],pE=10*1024*1024,Eu=5e3;fE=1*1024*1024});import{existsSync as mE,mkdirSync as Ou,renameSync as gE,rmSync as hE}from"fs";import{join as Jo}from"path";import{createHash as yE}from"crypto";async function zh(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await AE();let a=e.branch??await Ze(r,o,t),c=Rn(),l=Sg(c,r,o,a,i);return PE(c,l,async()=>{let u=Io(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};xs(c),wn(l);let d=vE(t,n),p=wE(c,l);ws(p);try{if(i){if(await OE(r,o,a,p,i,d),!mE(Jo(p,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 kE(r,o,a,p,d);let f=Fo(r,o,a,"clone",i);return _o(p,f),TE(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw ws(p),f}})}async function PE(e,t,n){wn(t);let r=xE(e,t);Ou(Jo(e,"tmp",Gh),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Ou(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>RE)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await EE(SE)}try{return await n()}finally{hE(r,{recursive:!0,force:!0})}}function Bh(e){return yE("sha256").update(e).digest("hex").slice(0,16)}function xE(e,t){return Jo(e,"tmp",Gh,Bh(t))}function wE(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Jo(e,"tmp",CE);return Ou(r,{recursive:!0,mode:448}),Jo(r,`${Bh(t)}-${n}`)}function TE(e,t){ws(t),wn(t),gE(e,t)}function EE(e){return new Promise(t=>setTimeout(t,e))}async function kE(e,t,n,r,o){let i=Uh(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Qh(e,t),r),await vu(i,Nh,`full clone of ${e}/${t}`,o)}async function OE(e,t,n,r,o,i){let s=Uh(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Qh(e,t),r),await vu(s,Nh,`sparse clone of ${e}/${t}`,i),await vu(["-C",r,"sparse-checkout","set","--skip-checks","--",o],bE,`sparse-checkout set ${o}`,void 0)}function Qh(e,t){return`https://github.com/${e}/${t}.git`}function Uh(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function vE(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function AE(){try{if(!(await kn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Hh,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 LE(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 vu(e,t,n,r){let o=await kn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Hh,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=LE(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var Nh,bE,RE,SE,Gh,CE,Hh,Au=y(()=>{"use strict";Ae();Ge();Xo();Ts();Nh=120*1e3,bE=30*1e3,RE=300*1e3,SE=100,Gh="clone-locks",CE="clone-tmp",Hh=[...Yo,"GIT_TERMINAL_PROMPT"]});async function jh(e,t={}){if(!Array.isArray(e))throw new Error(Yr.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(Yr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(Yr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Jr.NOT_A_FUNCTION.message(l))));if(r<i.length)return _E(i,r,n,o);let s=i.map((c,l)=>$h(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 $h(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(Jr.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 _E(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(Jr.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await $h(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 Lu=y(()=>{"use strict";ft()});function IE(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 _u(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)_u(o,t,n+1);return}let r=e;for(let o of Iu){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))qh.has(o)||i&&typeof i=="object"&&_u(i,t,n+1)}function Vh(e){let t=[];for(let i of e)_u(i?.data,t,0);if(t.length===0)return;let n=IE(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 FE(e,r),n}function FE(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(qh.has(s))continue;let a=i[s];typeof a=="string"?!Iu.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function ME(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 DE(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function Wh(e){let t=ME(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(NE.has(i))continue;let s=n[i];DE(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 Iu,qh,NE,Fu=y(()=>{"use strict";Iu=["path","uri"],qh=new Set(["next","location"]);NE=new Set([...Iu,"owner","repo","name","id"])});function BE(e,t,n){if(e<=1)return Kh;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(HE/o),s=Math.max(zE,Math.min(i,Kh));return n?Math.max(s,n):s}async function se(e,t,n,r){let o=n.concurrency??GE,{results:i,errors:s}=await $E(e,t,o,n.minQueryTimeoutMs);return QE(n,i,s,e,r)}function QE(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let b=g.result.status;c[g.queryIndex]={id:Zh(g.originalQuery,g.queryIndex),...b!==void 0?{status:b}:{},data:qE(g.result)}}),n.forEach(g=>{let b=r[g.queryIndex];b&&(c[g.queryIndex]={id:Zh(b,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),b=Yh(g.text,o),S=Xh(g.structuredContent,b.pagination);return Jh(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:S,isError:g.isError??(l.length>0&&l.every(k=>k.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let g=Vh(u.results);g&&(u.base=g);let b=Wh(u.results);b&&(u.shared=b)}let d=Wo(u,a),p=Yh(d,o),f=Xh(Tt(u),p.pagination);return Jh(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(g=>g.status==="error")}}function Mu(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
|
|
35
|
-
`,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function UE(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Mu(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function jE(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Mu(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 Yh(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=Mu(e,s,i),c=a<o,l=UE(e,s,i),u=jE(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
|
|
28
|
+
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function fn(e,t){let n=Dn(e)??{},r=Et(n),o=FT(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(zs(r,t||i),null,2):M.jsonToYamlString(r,{keysPriority:t||i})}function zs(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>zs(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=zs(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=zs(n[o],t));return r}function NT(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=>MT.has(r))||DT.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 Dn(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=>Dn(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(NT(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Dn(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 MT,DT,xr=y(()=>{"use strict";ot();we();MT=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"]),DT=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});import{z as Qs}from"zod";function H(e,t){return Qs.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Qs.number().int().min(e).max(t))}function le(e,t={}){let{maxQueries:n=5}=t;return Qs.object({queries:Qs.array(e).min(1).max(n).describe("Parallel queries."),...GT}).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,wr,Er,GT,qe=y(()=>{"use strict";Se();pe=H(1,1e3).optional().default(1),wr=H(0,100).optional(),Er=H(1,1e9).optional(),GT={responseCharOffset:H(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:H(1,5e4).optional().describe("Full-response char window.")}});import{z as ie}from"zod";var Oe,Bs,Zo,Lh,Tt=y(()=>{"use strict";Oe=ie.object({currentPage:ie.number(),totalPages:ie.number(),hasMore:ie.boolean(),nextPage:ie.number().optional(),pageSize:ie.number().optional(),totalItems:ie.number().optional()}),Bs=ie.object({charOffset:ie.number(),charLength:ie.number(),totalChars:ie.number(),hasMore:ie.boolean(),nextCharOffset:ie.number().optional(),currentPage:ie.number().optional(),totalPages:ie.number().optional(),chunkMode:ie.enum(["semantic","char-limit"]).optional()}),Zo=ie.object({tool:ie.string(),query:ie.record(ie.string(),ie.unknown()),why:ie.string().optional(),confidence:ie.enum(["exact","heuristic"]).optional()}),Lh=ie.object({level:ie.enum(["info","warning","error"]),message:ie.string(),field:ie.string().optional(),code:ie.string().optional()})});import{z as ee}from"zod";function XU(e){return e.extend(We)}function HT(e){return ee.object({id:ee.string(),status:ee.enum(["empty","error"]).optional(),data:e,diagnostics:ee.array(Lh).optional(),next:ee.record(ee.string(),Zo).optional()})}var _h,We,JU,Ft,Je=y(()=>{"use strict";Tt();_h=ee.object({currentPage:ee.number(),totalPages:ee.number(),hasMore:ee.boolean(),charOffset:ee.number(),charLength:ee.number(),totalChars:ee.number(),nextCharOffset:ee.number().optional()}).optional(),We={base:ee.string().optional(),shared:ee.record(ee.string(),ee.union([ee.string(),ee.number(),ee.boolean()])).optional(),responsePagination:_h};JU=HT(ee.record(ee.string(),ee.unknown()).optional()),Ft={base:ee.string().optional(),shared:ee.record(ee.string(),ee.union([ee.string(),ee.number(),ee.boolean()])).optional(),responsePagination:_h}});function zT(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function D(e,t,n={}){let{extra:r}=n,o={status:"error"};if(zT(e))o.error=e;else if(Ac(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=xf(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:q(o,n.rawResponse)}function Ve(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:D(i,t,{toolName:n.toolName})}}var js=y(()=>{"use strict";co();ce()});async function i$(e,t,n){if(e)try{await e(t,n)}catch{return}}function He(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:q(s,o.rawResponse)}function Us(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 D(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ze(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return D(i,t,{toolName:r})}var Qe=y(()=>{"use strict";js();ce()});async function Ze({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ze(o,t,r,e)}}var Kt=y(()=>{"use strict";Qe()});import{spawn as Eu}from"child_process";function ku(e={},t=$s){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function Yt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=$s,maxOutputSize:a=QT}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),p={cwd:o,env:ku(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=Eu(e,t,p)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let m,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{f.kill("SIGTERM")}catch{}m=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},Tu),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),b=()=>{clearTimeout(g),m!==void 0&&(clearTimeout(m),m=void 0)},w=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{f.kill("SIGKILL")}catch{}b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};f.stdout?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!w()&&l.stdoutChunks.push(T)}),f.stderr?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!w()&&l.stderrChunks.push(T)}),f.on("close",S=>{l.killed||(b(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),f.on("error",S=>{l.killed||(l.killed=!0,b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function Fh(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=$s}=r,a;try{a=Eu(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:ku({},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{}},Tu),o(!1)}},n);a.on("close",d=>{l(),i||o(d===0)}),a.on("error",()=>{l(),i||o(!1)})})}function f$(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=ei,maxOutputSize:l=BT}=r,u;try{u=Eu(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:ku({},c)})}catch{o(null);return}let d,p=()=>{clearTimeout(f),d!==void 0&&(clearTimeout(d),d=void 0)};u.stdout?.on("data",m=>{if(i)return;let g=m.toString();if(a+=Buffer.byteLength(g),a>l){if(!i){i=!0;try{u.kill("SIGKILL")}catch{}p(),o(null)}return}s.push(g)}),u.stderr?.on("data",()=>{});let f=setTimeout(()=>{if(!i){i=!0;try{u.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},Tu),o(null)}},n);u.on("close",m=>{if(p(),!i)if(m===0){let g=s.join("").trim();o(g||null)}else o(null)}),u.on("error",()=>{p(),i||o(null)})})}function qs(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 p$,$s,ei,Ih,QT,Tu,BT,Tr=y(()=>{"use strict";p$=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],$s=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],ei=[...$s,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Ih=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],QT=10*1024*1024,Tu=5e3;BT=1*1024*1024});import{existsSync as jT,mkdirSync as Ou,renameSync as UT,rmSync as $T}from"fs";import{join as ti}from"path";import{createHash as qT}from"crypto";async function Gh(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await ik();let a=e.branch??await at(r,o,t),c=ir(),l=bg(c,r,o,a,i);return XT(c,l,async()=>{let u=Go(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Ss(c),In(l);let d=ok(t,n),p=ZT(c,l);Ps(p);try{if(i){if(await rk(r,o,a,p,i,d),!jT(ti(p,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 nk(r,o,a,p,d);let f=Ho(r,o,a,"clone",i);return No(p,f),ek(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw Ps(p),f}})}async function XT(e,t,n){In(t);let r=JT(e,t);Ou(ti(e,"tmp",Dh),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Ou(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>VT)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await tk(KT)}try{return await n()}finally{$T(r,{recursive:!0,force:!0})}}function Hh(e){return qT("sha256").update(e).digest("hex").slice(0,16)}function JT(e,t){return ti(e,"tmp",Dh,Hh(t))}function ZT(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=ti(e,"tmp",YT);return Ou(r,{recursive:!0,mode:448}),ti(r,`${Hh(t)}-${n}`)}function ek(e,t){Ps(t),In(t),UT(e,t)}function tk(e){return new Promise(t=>setTimeout(t,e))}async function nk(e,t,n,r,o){let i=Qh(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",zh(e,t),r),await vu(i,Mh,`full clone of ${e}/${t}`,o)}async function rk(e,t,n,r,o,i){let s=Qh(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",zh(e,t),r),await vu(s,Mh,`sparse clone of ${e}/${t}`,i),await vu(["-C",r,"sparse-checkout","set","--skip-checks","--",o],WT,`sparse-checkout set ${o}`,void 0)}function zh(e,t){return`https://github.com/${e}/${t}.git`}function Qh(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function ok(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function ik(){try{if(!(await Yt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Nh,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 sk(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 vu(e,t,n,r){let o=await Yt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Nh,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=sk(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var Mh,WT,VT,KT,Dh,YT,Nh,Au=y(()=>{"use strict";$t();je();Tr();Cs();Mh=120*1e3,WT=30*1e3,VT=300*1e3,KT=100,Dh="clone-locks",YT="clone-tmp",Nh=[...ei,"GIT_TERMINAL_PROMPT"]});async function Bh(e,t={}){if(!Array.isArray(e))throw new Error(io.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(io.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(io.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(ao.NOT_A_FUNCTION.message(l))));if(r<i.length)return ak(i,r,n,o);let s=i.map((c,l)=>jh(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 jh(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(ao.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 ak(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(ao.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await jh(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 Lu=y(()=>{"use strict";Pt()});function ck(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 _u(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)_u(o,t,n+1);return}let r=e;for(let o of Iu){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))Uh.has(o)||i&&typeof i=="object"&&_u(i,t,n+1)}function Ws(e){let t=[];for(let i of e)_u(i?.data,t,0);if(t.length===0)return;let n=ck(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 lk(e,r),n}function lk(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(Uh.has(s))continue;let a=i[s];typeof a=="string"?!Iu.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function uk(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 dk(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function Vs(e){let t=uk(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(pk.has(i))continue;let s=n[i];dk(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 Iu,Uh,pk,Ks=y(()=>{"use strict";Iu=["path","uri"],Uh=new Set(["next","location"]);pk=new Set([...Iu,"owner","repo","name","id"])});function hk(e,t,n){if(e<=1)return $h;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(mk/o),s=Math.max(gk,Math.min(i,$h));return n?Math.max(s,n):s}async function ue(e,t,n,r){let o=n.concurrency??fk,{results:i,errors:s}=await Sk(e,t,o,n.minQueryTimeoutMs);return yk(n,i,s,e,r)}function yk(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let b=g.result.status;c[g.queryIndex]={id:Ys(g.originalQuery,g.queryIndex),...b!==void 0?{status:b}:{},data:Pk(g.result)}}),n.forEach(g=>{let b=r[g.queryIndex];b&&(c[g.queryIndex]={id:Ys(b,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),b=qh(g.text,o),w=Wh(g.structuredContent,b.pagination);return Vh(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:w,isError:g.isError??(l.length>0&&l.every(T=>T.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let g=Ws(u.results);g&&(u.base=g);let b=Vs(u.results);b&&(u.shared=b)}let d=fn(u,a),p=qh(d,o),f=Wh(Et(Dn(u)??{}),p.pagination);return Vh(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(g=>g.status==="error")}}function Fu(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 bk(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Fu(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function Rk(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Fu(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 qh(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=Fu(e,s,i),c=a<o,l=bk(e,s,i),u=Rk(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
|
|
36
30
|
`:`# Response page ${l}/${u}.
|
|
37
|
-
`}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Xh(e,t){return t?{...e,responsePagination:t}:e}function Jh(e,t,n,r){let o=t.reduce((i,s)=>i+(le(s.result)??U(s.result)),0)+n.reduce((i,s)=>i+U(s),0);try{ss(e,o,r)}catch{}}async function $E(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 jh(s,{timeout:BE(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data&&o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}),{results:o,errors:i}}function qE(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function Zh(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var GE,Kh,HE,zE,je=y(()=>{"use strict";Ae();Lu();Ko();oe();Fu();GE=3,Kh=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,HE=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,zE=5e3});function Js(e){return e.data!==void 0&&!e.error}function VE(e){return e.error!==void 0}var Du=y(()=>{"use strict"});import{maskSensitiveData as ey}from"@octocodeai/octocode-engine/mask";function WE(){return Cl().provider??Sl()}function KE(e){let t=Cl(),n=t.provider??Sl(),{baseUrl:r,token:o}=t;try{let i=Pu(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=ey(s);throw new Nu(n,`Failed to initialize ${n} provider: ${a}`)}}function ct(e){let t;return()=>t??=KE(e)}function Zs(e,t){return e.capabilities[t]}async function Zt(e,t){let n=await t();return Js(n)?{ok:!0,response:n}:{ok:!1,result:Ks(n,e)}}async function ty(e,t){let n=t??WE(),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:ey(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Js(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Nu,en=y(()=>{"use strict";Qs();Du();lr();Fe();Nu=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});async function ny(e){let{queries:t,authInfo:n}=e,r=ct(n);return se(t,async(o,i)=>Ve({toolName:A.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Zs(s,"cloneRepo"))return Ie(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",A.GITHUB_CLONE_REPO);let a;try{a=await zh(o,n,s.token)}catch(p){let f=p instanceof Error?p.message:String(p);return M(`Clone failed for ${o.owner}/${o.repo}: ${f}`,o)}let c=xo(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={localSearch:{tool:"localSearchCode",query:{path:a.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return _e(o,d,!0,A.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:A.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}var Gu=y(()=>{"use strict";Ae();fe();je();Fe();Ht();en();Au()});import{z as ry}from"zod";function YE(e,t){return e?.description&&!t.description?t.describe(e.description):t}function oy(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=YE(e.shape[r],o);return n}function XE(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function iy(e,t){if(!t?.length)return e;let n=new Set(t);return ry.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function ue(e,t={},n={}){let r=iy(e,n.omit),o=XE(r,oy(r,t));return n.strict?o.strict():o}function he(e,t={},n={}){let r=iy(e,n.omit),o=ry.object({...r.shape,...oy(r,t)});return n.strict?o.strict():o}var tt=y(()=>{"use strict"});import{CloneRepoQuerySchema as JE}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as ZE}from"@octocodeai/octocode-core/schemas/outputs";var Zo,ea,e$,ta=y(()=>{"use strict";Be();tt();Gt();Zo=ue(JE),ea=ie(Zo),e$=ZE.extend(Qe)});import{z as T}from"zod";import{FileContentQuerySchema as cy}from"@octocodeai/octocode-core/schemas";var ek,tk,sy,ay,ly,nk,xr,na,c$,ei=y(()=>{"use strict";me();Be();tt();Gt();ek=T.enum(["none","standard","symbols"]).optional().default("standard"),tk=T.object({currentPage:T.number(),totalPages:T.number(),hasMore:T.boolean(),nextPage:T.number().optional(),nextMatchPage:T.number().optional(),charOffset:T.number().optional(),charLength:T.number().optional(),totalChars:T.number().optional(),nextCharOffset:T.number().optional(),filesPerPage:T.number().optional(),totalFiles:T.number().optional(),entriesPerPage:T.number().optional(),totalEntries:T.number().optional(),matchesPerPage:T.number().optional(),totalMatches:T.number().optional()}),sy=T.object({path:T.string(),content:T.string(),localPath:T.string().optional(),repoRoot:T.string().optional(),contentView:T.enum(["none","standard","symbols"]).optional(),isSkeleton:T.boolean().optional(),totalLines:T.number().optional(),sourceChars:T.number().optional(),sourceBytes:T.number().optional(),resolvedBranch:T.string().optional(),pagination:tk.optional(),isPartial:T.boolean().optional(),startLine:T.number().optional(),endLine:T.number().optional(),matchRanges:T.array(T.object({start:T.number(),end:T.number()})).optional(),lastModified:T.string().optional(),lastModifiedBy:T.string().optional(),warnings:T.array(T.string()).optional(),matchNotFound:T.boolean().optional(),searchedFor:T.string().optional(),cached:T.boolean().optional()}),ay=T.object({path:T.string(),localPath:T.string(),repoRoot:T.string().optional(),fileCount:T.number(),totalSize:T.number(),complete:T.boolean().optional(),directoryEntryCount:T.number().optional(),eligibleFileCount:T.number().optional(),savedFileCount:T.number().optional(),skipped:T.object({nonFile:T.number(),missingDownloadUrl:T.number(),oversized:T.number(),binary:T.number(),fileLimit:T.number(),fetchFailed:T.number(),totalSizeLimit:T.number(),pathTraversal:T.number()}).optional(),limits:T.object({maxDirectoryFiles:T.number(),maxTotalSize:T.number(),maxFileSize:T.number()}).optional(),warnings:T.array(T.string()).optional(),files:T.array(T.object({path:T.string(),size:T.number(),type:T.string()})).optional(),cached:T.boolean().optional(),resolvedBranch:T.string().optional()}),ly={startLine:Pr,endLine:Pr,contextLines:Cr,charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:ek},nk=he(cy,ly),xr=ue(cy,ly),na=ie(nk),c$=T.object({base:T.string().optional(),shared:T.record(T.string(),T.union([T.string(),T.number(),T.boolean()])).optional(),responsePagination:Qe.responsePagination,results:T.array(T.object({id:T.string(),owner:T.string(),repo:T.string(),files:T.array(sy).optional(),directories:T.array(ay).optional(),data:T.object({owner:T.string(),repo:T.string(),files:T.array(sy).optional(),directories:T.array(ay).optional()}).optional()})),errors:T.array(T.object({id:T.string(),owner:T.string().optional(),repo:T.string().optional(),path:T.string().optional(),error:T.string()})).optional()})});function rk(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 uy(e,t){return e&&t?`${e}/${t}`:void 0}function p$(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,l=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${l} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function dy(e){return{keywords:e.keywords??[],projectId:uy(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 py(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function ok(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function fy(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}=ok(a),u=`${c}/${l}`,d=s,p=o.get(u);if(p||(p={id:u,owner:c,repo:l,matches:[]},o.set(u,p)),n||!s.matches?.length){p.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let f=!0,m=!1;for(let g of s.matches){if(!g.context)continue;let b={path:s.path,value:rk(g.context)};g.positions?.length>0&&(b.matchIndices=g.positions.map(([S,C])=>({start:S,end:C,lineOffset:(g.context??"").substring(0,S).split(`
|
|
38
|
-
`).length-1}))),r&&f&&d.url&&(b.url=d.url,f=!1),p.matches.push(b),m=!0}m||p.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,...py(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function my(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 gy(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function ik(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function hy(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(ik),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:uy(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 sk(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function ak(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function ck(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:ak(e)}}function yy(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=sk(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=ck(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(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}:{},...py(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function by(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 Ry(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function Sy(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??Tn.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 Cy(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[p])=>d==="."?-1:p==="."?1:d.localeCompare(p)).map(([d,p])=>({dir:d,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[d,p]of Object.entries(c))if(n[d]){let f=new Set(n[d].files);for(let[m,g]of Object.entries(p))f.has(m)&&(l[m]=g)}}let u={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(u.resolvedBranch=i),s&&(u.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)&&(u.pagination=e.pagination),u}var On=y(()=>{"use strict";me();qo()});function lk(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function ra(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=lk(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function oa(e,t,n){let r=Wo(e,[...t]);return{structuredContent:Tt(e),text:r,isError:n}}var ia=y(()=>{"use strict";Ko()});function sa(e){return typeof e=="object"&&e!==null}function lt(e){return typeof e=="string"&&e.length>0?e:void 0}function We(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Py(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function yt(e,t){return We(e[t])??0}function uk(e){if(sa(e))return{nonFile:yt(e,"nonFile"),missingDownloadUrl:yt(e,"missingDownloadUrl"),oversized:yt(e,"oversized"),binary:yt(e,"binary"),fileLimit:yt(e,"fileLimit"),fetchFailed:yt(e,"fetchFailed"),totalSizeLimit:yt(e,"totalSizeLimit"),pathTraversal:yt(e,"pathTraversal")}}function dk(e){if(sa(e))return{maxDirectoryFiles:yt(e,"maxDirectoryFiles"),maxTotalSize:yt(e,"maxTotalSize"),maxFileSize:yt(e,"maxFileSize")}}function fk(e){if(!sa(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 pk){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function mk(e,t){return`${e}/${t}`}function gk(e,t,n){let r=mk(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 hk(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function yk(e,t){let n=fk(e.pagination),r=hk(n,t);return{path:lt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:lt(e.localPath),repoRoot:lt(e.repoRoot),...We(e.fileSize)!==void 0?{fileSize:We(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:We(e.totalLines),sourceChars:We(e.sourceChars),sourceBytes:We(e.sourceBytes),resolvedBranch:lt(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:We(e.startLine),endLine:We(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:lt(e.lastModified),lastModifiedBy:lt(e.lastModifiedBy),warnings:Py(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:lt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function bk(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(sa).map(c=>({path:lt(c.path)??"",size:We(c.size)??0,type:lt(c.type)??"file"})),o=uk(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:lt(e.localPath)??"",repoRoot:lt(e.repoRoot),fileCount:We(e.fileCount)??r.length,totalSize:We(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:We(e.directoryEntryCount),eligibleFileCount:We(e.eligibleFileCount),savedFileCount:We(e.savedFileCount),skipped:o,limits:dk(e.limits),warnings:Py(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:lt(e.resolvedBranch)}}function Rk(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=gk(n,s,a),l=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(bk(l,i)),c.directories=d;return}let u=c.files??[];u.push(yk(l,i)),c.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{...r,data:o}})}function Sk(e,t){return ra(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error}})}function xy(){return({queries:e,results:t})=>{let n=Rk(t,e),r=Sk(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),oa(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}var pk,Hu=y(()=>{"use strict";ia();pk=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function wy(e){let{queries:t,authInfo:n}=e,r=ct(n);return se(t,async(o,i)=>{try{let s=Ue(xr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?Ck(a,n,c):Pk(a,n,c)}catch(s){return Ie(s,o,void 0,A.GITHUB_FETCH_CONTENT)}},{toolName:A.GITHUB_FETCH_CONTENT,finalize:xy()},e)}async function Ck(e,t,n){let r=ge();if(!(r.local.enabled&&r.local.enableClone))return M("Directory fetch requires local clone support. Set ENABLE_LOCAL=true and ENABLE_CLONE=true.",e);if(!Zs(n,"fetchDirectoryToDisk"))return Ie(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",A.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return M("Directory fetch requires both owner and repo.",e,{rawResponse:0});let o=e.branch??await Ze(e.owner,e.repo,t),i=await _g(e.owner,e.repo,String(e.path),o,t,!!e.forceRefresh),s=(i.skipped?.nonFile??0)>0,a=i.skipped?Object.fromEntries(Object.entries(i.skipped).filter(([,d])=>d>0)):void 0,c={kind:"directory",localPath:i.localPath,repoRoot:i.repoRoot,source:"treeFetch",cached:i.cached,complete:i.complete,verified:i.verified,...i.commitSha?{commitSha:i.commitSha}:{},...s?{hasSubdirectories:!0}:{},...a&&Object.keys(a).length>0?{skippedSummary:a}:{},owner:e.owner,repo:e.repo},l={localSearch:{tool:"localSearchCode",query:{path:i.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:i.localPath}},...s?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:i.localPath,repoRoot:i.repoRoot,fileCount:i.fileCount,totalSize:i.totalSize,complete:i.complete,verified:i.verified,...i.commitSha?{commitSha:i.commitSha}:{},directoryEntryCount:i.directoryEntryCount,eligibleFileCount:i.eligibleFileCount,savedFileCount:i.savedFileCount,skipped:i.skipped,limits:i.limits,...i.warnings?{warnings:i.warnings}:{},files:i.files,...i.cached?{cached:!0}:{},...e.branch!==i.branch?{resolvedBranch:i.branch}:{},location:c,next:l};return _e(e,u,!0,A.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??U(i)})}async function Pk(e,t,n){let r=await Zt(e,()=>n.provider.getFileContent(by(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await xk(e,t):void 0,i={...Ry(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return _e(e,i,s,A.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function xk(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ze(e.owner,e.repo,t);return Ig(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var zu=y(()=>{"use strict";fe();je();Fe();ei();Kl();Ge();oe();On();en();Hu();Ae()});function wk(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function Tk(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 Ek(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function Ty(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function kk(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:Ty(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:Ty(r.get(i)),...s?{pagination:s}:{}}}})}function Ok(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vk(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${Ok(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function Ak(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?Ek(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:vk(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:Lk(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function Lk(e,t){return{...e,matches:t}}function Ey(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=wk(p);m.incompleteResults&&(i=!0),m.results.reduce((S,C)=>S+C.matches.length,0)===0&&o.push({id:p.id,...m.nonExistentScope?{nonExistentScope:!0}:{},...m.incompleteResults?{incompleteResults:!0}:{}});let b=m.results;n.push({id:p.id,groups:b}),m.pagination&&r.set(p.id,m.pagination)});let s=Array.from(new Set(e.flatMap(p=>{let f=p.keywords;return Array.isArray(f)?f.filter(m=>typeof m=="string"):[]}))),a=Ak(Tk(n),s),c=ra(t),l=e.some(p=>p.concise===!0),u=kk(e,a,r);if(l)for(let p of u)p.data.files=p.data.files.map(f=>`${f.owner}/${f.repo}:${f.path}`);let d={results:u};return o.length>0&&(d.emptyQueries=o.map(({id:p,nonExistentScope:f,incompleteResults:m})=>({id:p,...f?{nonExistentScope:f}:{},...m?{incompleteResults:m}:{}}))),c.length>0&&(d.errors=c),i&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),oa(d,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],a.length===0&&c.length>0)}}var Bu=y(()=>{"use strict";ia()});function _k(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function Ik(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 ky(e){let{queries:t}=e,n=ct(e.authInfo);return se(t,async(r,o)=>{try{let i=Ik(r);if(i)return M(i.error,r);if(!_k(r))return M("At least one search term or scope filter is required.",r);let s=n(),a=await Zt(r,()=>s.provider.searchCode(dy(r)));if(a.ok===!1)return a.result;let c=fy(a.response.data,r);return _e(r,c,c.results.length>0,A.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Ie(i,r,void 0,A.GITHUB_SEARCH_CODE)}},{toolName:A.GITHUB_SEARCH_CODE,finalize:Ey()},e)}var Qu=y(()=>{"use strict";fe();je();Fe();On();en();Bu()});import{z as N}from"zod";import{GitHubCodeSearchQuerySchema as Oy}from"@octocodeai/octocode-core/schemas";var vy,aa,ca,q$,la=y(()=>{"use strict";me();Be();tt();Gt();vy={limit:G(1,100).optional(),page:ae.default(1)},aa=ue(Oy,vy),ca=ie(he(Oy,vy)),q$=N.object({base:N.string().optional(),shared:N.record(N.string(),N.union([N.string(),N.number(),N.boolean()])).optional(),responsePagination:Qe.responsePagination,results:N.array(N.object({id:N.string(),data:N.object({files:N.array(N.object({owner:N.string(),repo:N.string(),path:N.string(),queryId:N.string().optional(),matches:N.array(N.object({value:N.string().optional(),pathOnly:N.boolean().optional(),matchIndices:N.array(N.object({start:N.number(),end:N.number(),lineOffset:N.number()})).optional(),url:N.string().optional()}))})),pagination:N.object({currentPage:N.number(),totalPages:N.number(),perPage:N.number(),totalMatches:N.number(),reportedTotalMatches:N.number().optional(),reachableTotalMatches:N.number().optional(),totalMatchesKind:N.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:N.boolean().optional(),hasMore:N.boolean(),nextPage:N.number().optional(),uniqueFileCount:N.number().optional()}).optional()})})),emptyQueries:N.array(N.object({id:N.string(),nonExistentScope:N.literal(!0).optional(),incompleteResults:N.literal(!0).optional()})).optional(),warnings:N.array(N.string()).optional(),errors:N.array(N.object({id:N.string(),error:N.string()})).optional()})});function Fk(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 Mk(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 Dk(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Ay(e){let{content:t,reviewMode:n}=e,r=Fk(t,n),o=Mk(t,n),i=Dk(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 W$(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}var Uu=y(()=>{"use strict"});function qu(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function da(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Vu(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 fa(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 _y(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Iy(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function Nk(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function pa(e,t,n){return Nk({...Iy(e,t),...n})}function Ly(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return pa(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function ju(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return pa(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Gk(e,t,n){return{target:Iy(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function ua(e){return String(e.path??e.filename??"")}function Hk(e,t){return{path:ua(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function zk(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 Bk(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=zk(r,n.comments),i=qu(t),s=i?o.filter(l=>da(l.body,i)):o,{items:a,pagination:c}=Vu(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=fa(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:_y(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function Qk(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=qu(t);return{reviews:(o?r.filter(s=>da(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=fa(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 Uk(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Vu(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function jk(e){return e.split(`
|
|
31
|
+
`}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Wh(e,t){return t?{...e,responsePagination:t}:e}function Vh(e,t,n,r){let o=t.reduce((i,s)=>i+(me(s.result)??j(s.result)),0)+n.reduce((i,s)=>i+j(s),0);try{ls(e,o,r)}catch{}}async function Sk(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 Bh(s,{timeout:hk(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 Pk(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function Ys(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var fk,$h,mk,gk,Be=y(()=>{"use strict";$t();Lu();xr();ce();Ks();fk=3,$h=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,mk=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,gk=5e3});function Xs(e){return e.data!==void 0&&!e.error}function Ck(e){return e.error!==void 0}var Mu=y(()=>{"use strict"});import{maskSensitiveData as Kh}from"@octocodeai/octocode-engine/mask";function xk(){return xl().provider??Cl()}function wk(e){let t=xl(),n=t.provider??Cl(),{baseUrl:r,token:o}=t;try{let i=wu(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=Kh(s);throw new Du(n,`Failed to initialize ${n} provider: ${a}`)}}function gt(e){let t;return()=>t??=wk(e)}function Js(e,t){return e.capabilities[t]}async function mn(e,t){let n=await t();return Xs(n)?{ok:!0,response:n}:{ok:!1,result:Us(n,e)}}async function Yh(e,t){let n=t??xk(),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:Kh(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Xs(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Du,gn=y(()=>{"use strict";Hs();Mu();fr();Qe();Du=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});async function Xh(e){let{queries:t,authInfo:n}=e,r=gt(n);return ue(t,async(o,i)=>Ze({toolName:v.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Js(s,"cloneRepo"))return ze(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",v.GITHUB_CLONE_REPO);let a;try{a=await Gh(o,n,s.token)}catch(p){let f=p instanceof Error?p.message:String(p);return D(`Clone failed for ${o.owner}/${o.repo}: ${f}`,o)}let c=Oo(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={localSearch:{tool:"localSearchCode",query:{path:a.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return He(o,d,!0,v.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:v.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}var Nu=y(()=>{"use strict";$t();Re();Be();Qe();Kt();gn();Au()});import{z as Jh}from"zod";function Ek(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Zh(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=Ek(e.shape[r],o);return n}function Tk(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function ey(e,t){if(!t?.length)return e;let n=new Set(t);return Jh.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function ge(e,t={},n={}){let r=ey(e,n.omit),o=Tk(r,Zh(r,t));return n.strict?o.strict():o}function Pe(e,t={},n={}){let r=ey(e,n.omit),o=Jh.object({...r.shape,...Zh(r,t)});return n.strict?o.strict():o}var lt=y(()=>{"use strict"});import{CloneRepoQuerySchema as kk}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as Ok}from"@octocodeai/octocode-core/schemas/outputs";var ni,Zs,e1,ea=y(()=>{"use strict";qe();lt();Je();ni=ge(kk),Zs=le(ni),e1=Ok.extend(We)});import{z as E}from"zod";import{FileContentQuerySchema as ty}from"@octocodeai/octocode-core/schemas";var vk,Ak,Lk,_k,Ik,ny,Fk,kr,ta,c1,ri=y(()=>{"use strict";Se();qe();lt();Je();vk=E.enum(["none","standard","symbols"]).optional().default("standard"),Ak=E.object({currentPage:E.number(),totalPages:E.number(),hasMore:E.boolean(),nextPage:E.number().optional(),charOffset:E.number().optional(),charLength:E.number().optional(),totalChars:E.number().optional(),nextCharOffset:E.number().optional()}),Lk=E.object({continueChars:E.object({tool:E.literal("ghGetFileContent"),query:E.record(E.string(),E.unknown())}).optional()}),_k=E.object({path:E.string(),content:E.string(),localPath:E.string().optional(),repoRoot:E.string().optional(),contentView:E.enum(["none","standard","symbols"]).optional(),isSkeleton:E.boolean().optional(),totalLines:E.number().optional(),sourceChars:E.number().optional(),sourceBytes:E.number().optional(),resolvedBranch:E.string().optional(),pagination:Ak.optional(),next:Lk.optional(),isPartial:E.boolean().optional(),startLine:E.number().optional(),endLine:E.number().optional(),matchRanges:E.array(E.object({start:E.number(),end:E.number()})).optional(),lastModified:E.string().optional(),lastModifiedBy:E.string().optional(),warnings:E.array(E.string()).optional(),matchNotFound:E.boolean().optional(),searchedFor:E.string().optional(),cached:E.boolean().optional()}),Ik=E.object({path:E.string(),localPath:E.string(),repoRoot:E.string().optional(),fileCount:E.number(),totalSize:E.number(),complete:E.boolean().optional(),directoryEntryCount:E.number().optional(),eligibleFileCount:E.number().optional(),savedFileCount:E.number().optional(),skipped:E.object({nonFile:E.number(),missingDownloadUrl:E.number(),oversized:E.number(),binary:E.number(),fileLimit:E.number(),fetchFailed:E.number(),totalSizeLimit:E.number(),pathTraversal:E.number()}).optional(),limits:E.object({maxDirectoryFiles:E.number(),maxTotalSize:E.number(),maxFileSize:E.number()}).optional(),warnings:E.array(E.string()).optional(),files:E.array(E.object({path:E.string(),size:E.number(),type:E.string()})).optional(),cached:E.boolean().optional(),resolvedBranch:E.string().optional()}),ny={startLine:Er,endLine:Er,contextLines:wr,charOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional(),minify:vk},Fk=Pe(ty,ny),kr=ge(ty,ny),ta=le(Fk),c1=E.object({base:E.string().optional(),shared:E.record(E.string(),E.union([E.string(),E.number(),E.boolean()])).optional(),responsePagination:We.responsePagination,results:E.array(E.object({id:E.string(),data:E.object({owner:E.string(),repo:E.string(),files:E.array(_k).optional(),directories:E.array(Ik).optional()}).optional()})),errors:E.array(E.object({id:E.string(),owner:E.string().optional(),repo:E.string().optional(),path:E.string().optional(),error:E.string()})).optional()})});function Mk(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 ry(e,t){return e&&t?`${e}/${t}`:void 0}function p1(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,l=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${l} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function oy(e){return{keywords:e.keywords??[],projectId:ry(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 iy(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function sy(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function ay(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}=sy(a),u=`${c}/${l}`,d=s,p=o.get(u);if(p||(p={id:u,owner:c,repo:l,matches:[]},o.set(u,p)),n||!s.matches?.length){p.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let f=!0,m=!1;for(let g of s.matches){if(!g.context)continue;let b={path:s.path,value:Mk(g.context)};g.positions?.length>0&&(b.matchIndices=g.positions.map(([w,S])=>({start:w,end:S,lineOffset:(g.context??"").substring(0,w).split(`
|
|
32
|
+
`).length-1}))),r&&f&&d.url&&(b.url=d.url,f=!1),p.matches.push(b),m=!0}m||p.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,...iy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function cy(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 ly(e){return e.map(t=>{let{owner:n,repo:r}=sy(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function Dk(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function uy(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Dk),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ry(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 Nk(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function Gk(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:Nk(e)}}function dy(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=Gk(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(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}:{},...iy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function py(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 fy(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function my(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??Fn.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 gy(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([p],[f])=>p==="."?-1:f==="."?1:p.localeCompare(f)).map(([p,f])=>({dir:p,files:f.files,folders:f.folders})),c=e.fileSizeMap,l={};if(c){for(let[p,f]of Object.entries(c))if(n[p]){let m=new Set(n[p].files);for(let[g,b]of Object.entries(f))if(m.has(g)){let w=p==="."?g:`${p}/${g}`;l[w]=b}}}let u=Object.values(n).reduce((p,f)=>(p.totalFiles+=f.files.length,p.totalFolders+=f.folders.length,p),{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 Nn=y(()=>{"use strict";Se();Xo()});function na(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Hk(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:na(t.status),retryAfterSeconds:na(t.retryAfter),rateLimitRemaining:na(t.rateLimitRemaining),rateLimitReset:na(t.rateLimitReset)}}return{message:"Provider error"}}function ra(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=Hk(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 oa(e,t,n){let r=fn(e,[...t]);return{structuredContent:Et(Dn(e)??{}),text:r,isError:n}}var ia=y(()=>{"use strict";xr()});function sa(e){return typeof e=="object"&&e!==null}function ht(e){return typeof e=="string"&&e.length>0?e:void 0}function et(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function hy(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function kt(e,t){return et(e[t])??0}function zk(e){if(sa(e))return{nonFile:kt(e,"nonFile"),missingDownloadUrl:kt(e,"missingDownloadUrl"),oversized:kt(e,"oversized"),binary:kt(e,"binary"),fileLimit:kt(e,"fileLimit"),fetchFailed:kt(e,"fetchFailed"),totalSizeLimit:kt(e,"totalSizeLimit"),pathTraversal:kt(e,"pathTraversal")}}function Qk(e){if(sa(e))return{maxDirectoryFiles:kt(e,"maxDirectoryFiles"),maxTotalSize:kt(e,"maxTotalSize"),maxFileSize:kt(e,"maxFileSize")}}function jk(e){if(!sa(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 Bk){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Uk(e,t){return`${e}/${t}`}function $k(e,t,n){let r=Uk(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 qk(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function Wk(e,t){let n=jk(e.pagination),r=qk(n,t);return{path:ht(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:ht(e.localPath),repoRoot:ht(e.repoRoot),...et(e.fileSize)!==void 0?{fileSize:et(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:et(e.totalLines),sourceChars:et(e.sourceChars),sourceBytes:et(e.sourceBytes),resolvedBranch:ht(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:et(e.startLine),endLine:et(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:ht(e.lastModified),lastModifiedBy:ht(e.lastModifiedBy),warnings:hy(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:ht(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function Vk(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(sa).map(c=>({path:ht(c.path)??"",size:et(c.size)??0,type:ht(c.type)??"file"})),o=zk(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:ht(e.localPath)??"",repoRoot:ht(e.repoRoot),fileCount:et(e.fileCount)??r.length,totalSize:et(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:et(e.directoryEntryCount),eligibleFileCount:et(e.eligibleFileCount),savedFileCount:et(e.savedFileCount),skipped:o,limits:Qk(e.limits),warnings:hy(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:ht(e.resolvedBranch)}}function Kk(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=$k(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(Vk(c,o)),a.directories=u;return}let l=a.files??[];l.push(Wk(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 Yk(e,t){return ra(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 yy(){return({queries:e,results:t})=>{let n=new Map;e.forEach((s,a)=>{n.set(Ys(s,a),s)});let r=Kk(t,n),o=Yk(t,n),i={results:r};return o&&o.length>0&&(i.errors=o),oa(i,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],r.length===0&&!!(o&&o.length>0))}}var Bk,Gu=y(()=>{"use strict";ia();Be();Bk=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function by(e){let{queries:t,authInfo:n}=e,r=gt(n);return ue(t,async(o,i)=>{try{let s=Ve(kr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?Xk(a,n,c):Jk(a,n,c)}catch(s){return ze(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:yy()},e)}async function Xk(e,t,n){if(!Js(n,"fetchDirectoryToDisk"))return ze(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 D("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await at(e.owner,e.repo,t),o=await Ag(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,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 He(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??j(o)})}async function Jk(e,t,n){let r=await mn(e,()=>n.provider.getFileContent(py(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await Zk(e,t):void 0,i={...fy(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return He(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function Zk(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await at(e.owner,e.repo,t);return Lg(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var Hu=y(()=>{"use strict";Re();Be();Qe();ri();Yl();je();ce();Nn();gn();Gu()});function eO(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function tO(e,t){let n=eO(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function nO(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function rO(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 oO(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function Ry(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 iO(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:Ry(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:Ry(r.get(i)),...s?{pagination:s}:{}}}})}function sO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function aO(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${sO(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function cO(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?oO(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:aO(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:lO(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function lO(e,t){return{...e,matches:t}}function Sy(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=nO(p);m.incompleteResults&&(i=!0),m.results.reduce((w,S)=>w+S.matches.length,0)===0&&o.push({id:p.id,...m.nonExistentScope?{nonExistentScope:!0}:{},...m.incompleteResults?{incompleteResults:!0}:{}});let b=m.results;n.push({id:p.id,groups:b}),m.pagination&&r.set(p.id,m.pagination)});let s=Array.from(new Set(e.flatMap(p=>{let f=p.keywords;return Array.isArray(f)?f.filter(m=>typeof m=="string"):[]}))),a=cO(rO(n),s),c=ra(t),l=e.some(p=>p.concise===!0),u=iO(e,a,r);if(l)for(let p of u)p.data.files=p.data.files.map(f=>`${f.owner}/${f.repo}:${f.path}`);let d={results:u};return o.length>0&&(d.emptyQueries=o.map(({id:p,nonExistentScope:f,incompleteResults:m})=>({id:p,...f?{nonExistentScope:f}:{},...m?{incompleteResults:m}:{}}))),c.length>0&&(d.errors=c),i&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),o.length>0&&tO(o,e)&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"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."]),oa(d,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],a.length===0&&c.length>0)}}var zu=y(()=>{"use strict";ia()});function uO(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function dO(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 Py(e){let{queries:t}=e,n=gt(e.authInfo);return ue(t,async(r,o)=>{try{let i=dO(r);if(i)return D(i.error,r);if(!uO(r))return D("At least one search term or scope filter is required.",r);let s=n(),a=await mn(r,()=>s.provider.searchCode(oy(r)));if(a.ok===!1)return a.result;let c=ay(a.response.data,r);return He(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ze(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:Sy()},e)}var Qu=y(()=>{"use strict";Re();Be();Qe();Nn();gn();zu()});import{z as U}from"zod";import{GitHubCodeSearchQuerySchema as Cy}from"@octocodeai/octocode-core/schemas";var xy,aa,ca,pO,W1,la=y(()=>{"use strict";Se();qe();lt();Je();Tt();xy={limit:H(1,100).optional(),page:pe.default(1)},aa=ge(Cy,xy),ca=le(Pe(Cy,xy)),pO=Oe.extend({totalMatchesKind:U.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:U.boolean().optional(),uniqueFileCount:U.number().optional()}),W1=U.object({base:U.string().optional(),shared:U.record(U.string(),U.union([U.string(),U.number(),U.boolean()])).optional(),responsePagination:We.responsePagination,results:U.array(U.object({id:U.string(),data:U.object({files:U.array(U.object({owner:U.string(),repo:U.string(),path:U.string(),queryId:U.string().optional(),matches:U.array(U.object({value:U.string().optional(),pathOnly:U.boolean().optional(),matchIndices:U.array(U.object({start:U.number(),end:U.number(),lineOffset:U.number()})).optional(),url:U.string().optional()}))})),pagination:pO.optional()})})),emptyQueries:U.array(U.object({id:U.string(),nonExistentScope:U.literal(!0).optional(),incompleteResults:U.literal(!0).optional()})).optional(),warnings:U.array(U.string()).optional(),errors:U.array(U.object({id:U.string(),error:U.string()})).optional()})});function fO(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 mO(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 gO(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function wy(e){let{content:t,reviewMode:n}=e,r=fO(t,n),o=mO(t,n),i=gO(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 K1(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}var Bu=y(()=>{"use strict"});function $u(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function da(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function qu(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 fa(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 Ty(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function ky(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function hO(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function pa(e,t,n){return hO({...ky(e,t),...n})}function Ey(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return pa(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function ju(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return pa(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function yO(e,t,n){return{target:ky(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function ua(e){return String(e.path??e.filename??"")}function bO(e,t){return{path:ua(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function RO(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 SO(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=RO(r,n.comments),i=$u(t),s=i?o.filter(l=>da(l.body,i)):o,{items:a,pagination:c}=qu(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=fa(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:Ty(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function PO(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=$u(t);return{reviews:(o?r.filter(s=>da(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=fa(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 CO(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=qu(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function xO(e){return e.split(`
|
|
39
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(`
|
|
40
|
-
`)}function
|
|
34
|
+
`)}function wO(e){return e.replace(/\n{3,}/g,`
|
|
41
35
|
|
|
42
|
-
`)}function qk(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(f=>i.includes(ua(f))):o,a=qu(t),c=a?s.filter(f=>da(ua(f),a)||da(f.patch,a)):s,{items:l,pagination:u}=Vu(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=Hk(f,!1);if(!d||typeof f.patch!="string")return m;let g=r&&!a?jk(f.patch):f.patch,b=fa(g,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:Bo(b?.content),...b?{patchPagination:b.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(ua).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function ti(e){return typeof e=="object"&&e!==null}function $u(e){if(ti(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Wu(e){if(ti(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function Vk(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function Wk(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!ti(n))continue;let r=Wu(n.patchPagination);if(r?.hasMore)return r}}function Kk(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!ti(n))continue;let r=Wu(n.bodyPagination);if(r?.hasMore)return r}}function Yk(e,t,n,r){let o={},i=Wu(e.bodyPagination),s=$u(e.filePagination),a=$u(e.commentPagination),c=$u(e.commitPagination),l=Wk(e),u=Kk(e),d=Vk(n);i&&(o.body={...i,nextQuery:Ly(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:ju(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:ju(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:pa(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:ju(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Ly(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return ti(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?pa(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function Xk(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Fy(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?$k(s):s,c=n.body?fa(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,p=t.prNumber!==void 0||t.verbose===!0,m={...{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,...p?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...p?{updatedAt:e.updatedAt}:{},...p||!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}:{},...p&&!c?{bodyPreview:_y(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:Gk(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...qk(e,t,n,r),...Bk(e,t,n),...Qk(e,t,n),...Uk(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=Yk(m,t,n,i);return Xk(m),g&&(m.contentPagination=g),m}var Ku=y(()=>{"use strict";me();Qo()});import{z as vn}from"zod";import{GitHubPullRequestSearchQuerySchema as My}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Jk}from"@octocodeai/octocode-core/schemas/outputs";var Dy,Zk,wr,ma,s1,ni=y(()=>{"use strict";me();Be();tt();Gt();Dy={perPage:G(1,100).optional().default(30),prNumber:G(1,1e9).optional(),limit:G(1,100).optional().default(30),page:ae.default(1),filePage:ae.optional(),commentPage:ae.optional(),commitPage:ae.optional(),itemsPerPage:G(1,100).optional().default(20),charOffset:G(0,1e8).optional(),commentBodyOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional()},Zk=he(My,Dy),wr=ue(My,Dy),ma=ie(Zk),s1=Jk.extend({results:vn.array(vn.object({id:vn.string().optional(),status:vn.string().optional(),data:vn.object({pull_requests:vn.array(vn.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Qe})});async function Ny(e){let{queries:t,authInfo:n}=e,r=ct(n);return se(t,async(o,i)=>{try{let s=Ue(wr,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let O=s.data;if(!O.owner||!O.repo)return M("owner and repo are required for commits mode.",o);let w=O.path,H=w&&!w.endsWith("/")?"file":"repo";if(H==="file"&&!w)return M("path is required when querying a specific file in commits mode.",o);let I=await hh({type:H,owner:O.owner,repo:O.repo,path:w,branch:O.branch,since:O.since,until:O.until,author:O.author,page:Number(O.page)||1,perPage:Number(O.perPage)||30,filePage:typeof O.filePage=="number"?O.filePage:void 0,itemsPerPage:typeof O.itemsPerPage=="number"?O.itemsPerPage:void 0,includeDiff:!!O.includeDiff,charOffset:typeof O.charOffset=="number"?O.charOffset:void 0,charLength:typeof O.charLength=="number"?O.charLength:void 0},n);if(En(I))return M(I,o,{toolName:A.GITHUB_SEARCH_PULL_REQUESTS});let{commits:v}=I.data,D=v.length>0;return _e(o,I.data,D,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:I.rawResponseChars})}let a=r(),c={...s.data},l=Ay(c),u=c.prNumber!==void 0;if(u||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return M("At least one valid search parameter, filter, or PR number is required.",o);let p=await Zt(c,()=>a.provider.searchPullRequests(hy(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:g}=yy(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete g.pagination;let b=!u&&(!!o.content||!!o.reviewMode),S={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},C=c.minify==="standard",k=u,_=m.map(O=>Fy(O,c,b?S:l,C,k));g.pull_requests=_,!u&&c.concise===!0&&(g.pull_requests=_.map(O=>{let w=O;return`#${w.number} ${w.title}`}));let E=_.length>0;return _e(c,g,E,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return Ie(s,o,void 0,A.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:A.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var Yu=y(()=>{"use strict";ni();fe();je();Fe();On();en();Uu();Ku();au();Vo()});function Gy(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 Xu=y(()=>{"use strict"});function eO(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function x1(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 tO(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(eO)}}}function By(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function Qy(e){return!!(e.keywords&&e.keywords.length>0)}function nO(e){return!!(Qy(e)||By(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 Hy(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function rO(e){let t=By(e),n=Qy(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:Hy(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:Hy(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function oO(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 iO(e,t){return[...e].sort((n,r)=>{let o=sO(n,r,t.sort);if(o!==0)return o;let i=zy(r,t)-zy(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Ju(n).localeCompare(Ju(r))})}function sO(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 Gy(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function zy(e,t){let n=aO(t),r=Ju(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 aO(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Ju(e){return`${e.owner}/${e.repo}`}function cO(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function lO(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function uO(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??U(n.response.data??n.response)),0)}async function Uy(e){let{queries:t,authInfo:n}=e,r=ct(n);return se(t,async(o,i)=>{try{if(!nO(o))return M("At least one repository search term or filter is required.",o);let s=r(),a=rO(o),{successes:c,failures:l}=await ty(a.map(E=>({meta:{label:E.label,query:E.query},operation:()=>s.provider.searchRepos(my(E.query))}))),u=c.map(E=>({label:E.meta.label,query:E.meta.query,response:E.response})),d=l.map(E=>({label:E.meta.label,query:E.meta.query,response:E.response}));if(u.length===0){let E=d[0];return E?Ks(E.response,o):Ie(new Error("Repository search produced no provider results"),o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=iO(oO(u.flatMap(E=>gy(E.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,g=u.length===1?u[0]:void 0,S=u.length>1?lO(u):g?.response.data.pagination,C=S?cO(S):void 0,k=m.length>0,_=tO({repositories:m,pagination:C},o);return _e(o,_.data,k,A.GITHUB_SEARCH_REPOSITORIES,{rawResponse:uO([...u,...d])})}catch(s){return Ie(s,o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}},{toolName:A.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var Zu=y(()=>{"use strict";fe();je();Xu();Fe();On();en();oe()});import{z as W}from"zod";import{GitHubReposSearchSingleQuerySchema as jy}from"@octocodeai/octocode-core/schemas";var $y,ga,ha,dO,pO,fO,M1,ya=y(()=>{"use strict";me();Be();tt();Gt();$y={limit:G(1,100).optional(),page:ae.default(1)},ga=ue(jy,$y),ha=ie(he(jy,$y)),dO=W.object({owner:W.string(),repo:W.string(),stars:W.number().optional(),forks:W.number().optional(),openIssuesCount:W.number().optional(),language:W.string().optional(),license:W.string().optional(),description:W.string().optional(),homepage:W.string().optional(),pushedAt:W.string().optional(),createdAt:W.string().optional(),defaultBranch:W.string().optional(),topics:W.array(W.string()).optional(),visibility:W.string().optional(),url:W.string().optional(),updatedAt:W.string().optional()}),pO=W.object({currentPage:W.number(),totalPages:W.number(),hasMore:W.boolean(),perPage:W.number().optional(),totalMatches:W.number().optional(),reportedTotalMatches:W.number().optional(),reachableTotalMatches:W.number().optional(),totalMatchesKind:W.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:W.boolean().optional(),nextPage:W.number().optional()}).optional(),fO=W.object({repositories:W.array(W.union([W.string(),dO])).optional(),pagination:pO}).passthrough(),M1=W.object({results:W.array(W.object({id:W.string().optional(),status:W.string().optional(),data:fO.optional()}).passthrough()).optional()}).extend(Qe)});function mO(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 gO(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&ko(o))continue;let i=r.files.filter(a=>!mr(a)),s=r.folders.filter(a=>!ko(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function qy(e){let{queries:t,authInfo:n}=e,r=ct(n);return se(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await Zt(o,()=>s.provider.getRepoStructure(Sy(o,c)));if(l.ok===!1)return mO(l.result,o);let u=gO(l.response.data.structure),d=Object.keys(u).length>0,p=Cy(l.response.data,o,u,c);return _e(o,p,d,A.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return Ie(s,o,"Failed to explore repository structure",A.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:A.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var ed=y(()=>{"use strict";fe();je();gr();Fe();On();en()});import{GitHubViewRepoStructureQuerySchema as Vy}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as hO}from"@octocodeai/octocode-core/schemas/outputs";var Wy,ba,Ra,X1,Sa=y(()=>{"use strict";me();me();Be();tt();Gt();Wy={maxDepth:G(0,20).optional(),page:ae.default(1),itemsPerPage:G(1,200).optional()},ba=ue(Vy,Wy),Ra=ie(he(Vy,Wy)),X1=hO.extend(Qe)});import{z as Ky}from"zod";import{LocalBinaryInspectQuerySchema as yO}from"@octocodeai/octocode-core/schemas";var bO,Yy,Tr,Ca,ri=y(()=>{"use strict";Be();bO={entryPageNumber:ae.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:G(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:G(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:ae.default(1).describe("1-based page for paginated entry/content listings."),detailed:Ky.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Yy=Ky.object({...yO.shape,...bO}),Tr=Yy.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),Ca=ie(Yy,{maxQueries:5})});import Xy from"path";import{pathValidator as RO}from"@octocodeai/octocode-engine/pathValidator";function Ke(e,t){if(!e.path?.trim()){let s=Xe.pathValidationFailed("","path is required");return{isValid:!1,errorResult:M(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||ge().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Xy.isAbsolute(r)?r:Xy.resolve(n,r),i=RO.validate(o);if(!i.isValid){let s=Xe.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:M(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function cq(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:Xe.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 Et=y(()=>{"use strict";eo();Ws();Ae()});import{validateCommand as SO}from"@octocodeai/octocode-engine/commandValidator";async function Er(e,t=[],n={}){let r=SO(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Xs(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 kn(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}}var Pa=y(()=>{"use strict";Xo()});function bt(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function CO(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},u={command:"7z",args:i},d={command:"7zz",args:i},p={command:"aa",args:s};return bt(Jy,e)?[p]:bt(rd,e)?[u,d,l,c,a]:bt(nd,e)?[l,u,d,c,a]:bt(td,e)?[a,c,l,u,d]:[c,a,l,u,d]}function PO(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return bt(rd,e)?[s,a,o,r,n]:bt(nd,e)?[o,s,a,r,n]:bt(td,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function od(e){let t=[];for(let n of e){let r=await Er(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function xO(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
|
|
36
|
+
`)}function EO(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(f=>i.includes(ua(f))):o,a=$u(t),c=a?s.filter(f=>da(ua(f),a)||da(f.patch,a)):s,{items:l,pagination:u}=qu(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=bO(f,!1);if(!d||typeof f.patch!="string")return m;let g=r&&!a?xO(f.patch):f.patch,b=fa(g,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:qo(b?.content),...b?{patchPagination:b.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(ua).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function oi(e){return typeof e=="object"&&e!==null}function Uu(e){if(oi(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Wu(e){if(oi(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function TO(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function kO(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!oi(n))continue;let r=Wu(n.patchPagination);if(r?.hasMore)return r}}function OO(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!oi(n))continue;let r=Wu(n.bodyPagination);if(r?.hasMore)return r}}function vO(e,t,n,r){let o={},i=Wu(e.bodyPagination),s=Uu(e.filePagination),a=Uu(e.commentPagination),c=Uu(e.commitPagination),l=kO(e),u=OO(e),d=TO(n);i&&(o.body={...i,nextQuery:Ey(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:ju(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:ju(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:pa(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:ju(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Ey(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return oi(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?pa(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function AO(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Oy(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?wO(s):s,c=n.body?fa(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,p=t.prNumber!==void 0||t.verbose===!0,m={...{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,...p?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...p?{updatedAt:e.updatedAt}:{},...p||!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}:{},...p&&!c?{bodyPreview:Ty(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:yO(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...EO(e,t,n,r),...SO(e,t,n),...PO(e,t,n),...CO(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=vO(m,t,n,i);return AO(m),g&&(m.contentPagination=g),m}var Vu=y(()=>{"use strict";Se();Wo()});import{z as Gn}from"zod";import{GitHubPullRequestSearchQuerySchema as vy}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as LO}from"@octocodeai/octocode-core/schemas/outputs";var Ay,_O,Or,ma,aq,ii=y(()=>{"use strict";Se();qe();lt();Je();Ay={perPage:H(1,100).optional().default(30),prNumber:H(1,1e9).optional(),limit:H(1,100).optional().default(30),page:pe.default(1),filePage:pe.optional(),commentPage:pe.optional(),commitPage:pe.optional(),itemsPerPage:H(1,100).optional().default(20),charOffset:H(0,1e8).optional(),commentBodyOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional()},_O=Pe(vy,Ay),Or=ge(vy,Ay),ma=le(_O),aq=LO.extend({results:Gn.array(Gn.object({id:Gn.string().optional(),status:Gn.string().optional(),data:Gn.object({pull_requests:Gn.array(Gn.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...We})});async function Ly(e){let{queries:t,authInfo:n}=e,r=gt(n);return ue(t,async(o,i)=>{try{let s=Ve(Or,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let k=s.data;if(!k.owner||!k.repo)return D("owner and repo are required for commits mode.",o);let x=k.path,N=x&&!x.endsWith("/")?"file":"repo";if(N==="file"&&!x)return D("path is required when querying a specific file in commits mode.",o);let F=await fh({type:N,owner:k.owner,repo:k.repo,path:x,branch:k.branch,since:k.since,until:k.until,author:k.author,page:Number(k.page)||1,perPage:Number(k.perPage)||30,filePage:typeof k.filePage=="number"?k.filePage:void 0,itemsPerPage:typeof k.itemsPerPage=="number"?k.itemsPerPage:void 0,includeDiff:!!k.includeDiff,charOffset:typeof k.charOffset=="number"?k.charOffset:void 0,charLength:typeof k.charLength=="number"?k.charLength:void 0},n);if(Mn(F))return D(F,o,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:O}=F.data,B=O.length>0;return He(o,F.data,B,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:F.rawResponseChars})}let a=r(),c={...s.data},l=wy(c),u=c.prNumber!==void 0;if(u||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return D("At least one valid search parameter, filter, or PR number is required.",o);let p=await mn(c,()=>a.provider.searchPullRequests(uy(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:g}=dy(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete g.pagination;let b=!u&&(!!o.content||!!o.reviewMode),w={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},S=c.minify==="standard",T=u,A=m.map(k=>Oy(k,c,b?w:l,S,T));g.pull_requests=A,!u&&c.concise===!0&&(g.pull_requests=A.map(k=>{let x=k;return`#${x.number} ${x.title}`}));let _=A.length>0;return He(c,g,_,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var Ku=y(()=>{"use strict";ii();Re();Be();Qe();Nn();gn();Bu();Vu();lu();Jo()});function _y(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 Yu=y(()=>{"use strict"});function IO(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function wq(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 FO(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(IO)}}}function My(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function Dy(e){return!!(e.keywords&&e.keywords.length>0)}function MO(e){return!!(Dy(e)||My(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 Iy(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function DO(e){let t=My(e),n=Dy(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:Iy(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:Iy(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function NO(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 GO(e,t){return[...e].sort((n,r)=>{let o=HO(n,r,t.sort);if(o!==0)return o;let i=Fy(r,t)-Fy(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Xu(n).localeCompare(Xu(r))})}function HO(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 _y(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function Fy(e,t){let n=zO(t),r=Xu(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 zO(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Xu(e){return`${e.owner}/${e.repo}`}function QO(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 BO(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 jO(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 UO(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??j(n.response.data??n.response)),0)}async function Ny(e){let{queries:t,authInfo:n}=e,r=gt(n);return ue(t,async(o,i)=>{try{if(!MO(o))return D("At least one repository search term or filter is required.",o);let s=r(),a=DO(o),{successes:c,failures:l}=await Yh(a.map(x=>({meta:{label:x.label,query:x.query},operation:()=>s.provider.searchRepos(cy(x.query))}))),u=c.map(x=>({label:x.meta.label,query:x.meta.query,response:x.response})),d=l.map(x=>({label:x.meta.label,query:x.meta.query,response:x.response}));if(u.length===0){let x=d[0];return x?Us(x.response,o):ze(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=GO(NO(u.flatMap(x=>ly(x.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,g=u.length===1?u[0]:void 0,w=u.length>1?jO(u,f.length):g?.response.data.pagination,S=w?QO(w):void 0,T=m.length>0,A=FO({repositories:m,pagination:S},o),_=BO(d),k=_?{...A.data,warnings:_}:A.data;return He(o,k,T,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:UO([...u,...d])})}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var Ju=y(()=>{"use strict";Re();Be();Yu();Qe();Nn();gn();ce()});import{z as re}from"zod";import{GitHubReposSearchSingleQuerySchema as Gy}from"@octocodeai/octocode-core/schemas";var Hy,ga,ha,$O,qO,WO,Nq,ya=y(()=>{"use strict";Se();qe();lt();Je();Tt();Hy={limit:H(1,100).optional(),page:pe.default(1)},ga=ge(Gy,Hy),ha=le(Pe(Gy,Hy)),$O=re.object({owner:re.string(),repo:re.string(),stars:re.number().optional(),forks:re.number().optional(),openIssuesCount:re.number().optional(),language:re.string().optional(),license:re.string().optional(),description:re.string().optional(),homepage:re.string().optional(),pushedAt:re.string().optional(),createdAt:re.string().optional(),defaultBranch:re.string().optional(),topics:re.array(re.string()).optional(),visibility:re.string().optional(),url:re.string().optional(),updatedAt:re.string().optional()}),qO=Oe.extend({totalMatchesKind:re.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:re.boolean().optional()}).optional(),WO=re.object({repositories:re.array(re.union([re.string(),$O])).optional(),pagination:qO}).passthrough(),Nq=re.object({results:re.array(re.object({id:re.string().optional(),status:re.string().optional(),data:WO.optional()}).passthrough()).optional()}).extend(We)});function VO(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 KO(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&_o(o))continue;let i=r.files.filter(a=>!yr(a)),s=r.folders.filter(a=>!_o(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function zy(e){let{queries:t,authInfo:n}=e,r=gt(n);return ue(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await mn(o,()=>s.provider.getRepoStructure(my(o,c)));if(l.ok===!1)return VO(l.result,o);let u=KO(l.response.data.structure),d=Object.keys(u).length>0,p=gy(l.response.data,o,u,c);return He(o,p,d,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return ze(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 Zu=y(()=>{"use strict";Re();Be();br();Qe();Nn();gn()});import{GitHubViewRepoStructureQuerySchema as Qy}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as YO}from"@octocodeai/octocode-core/schemas/outputs";var By,ba,Ra,Zq,Sa=y(()=>{"use strict";Se();Se();qe();lt();Je();By={maxDepth:H(0,20).optional(),page:pe.default(1),itemsPerPage:H(1,200).optional()},ba=ge(Qy,By),Ra=le(Pe(Qy,By)),Zq=YO.extend(We)});import{z as I}from"zod";import{LocalBinaryInspectQuerySchema as XO}from"@octocodeai/octocode-core/schemas";var JO,jy,vr,Pa,ZO,ev,tv,nv,rv,ov,iv,sW,si=y(()=>{"use strict";qe();Je();Tt();JO={entryPageNumber:pe.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:H(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:H(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:pe.default(1).describe("1-based page for paginated entry/content listings."),detailed:I.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},jy=I.object({...XO.shape,...JO}),vr=jy.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),Pa=le(jy,{maxQueries:5}),ZO=I.object({path:I.string(),mode:I.literal("inspect"),format:I.string().optional(),size:I.number().optional(),isText:I.boolean().optional(),encoding:I.string().optional(),symbols:I.array(I.string()).optional(),imports:I.array(I.string()).optional(),exports:I.array(I.string()).optional(),sections:I.array(I.string()).optional(),warnings:I.array(I.string()).optional()}),ev=I.object({name:I.string(),size:I.number().optional(),compressedSize:I.number().optional(),isDir:I.boolean().optional(),modified:I.string().optional()}),tv=I.object({path:I.string(),mode:I.literal("list"),entries:I.array(ev).optional(),pagination:Oe.optional(),warnings:I.array(I.string()).optional()}),nv=I.object({path:I.string(),mode:I.enum(["extract","decompress"]),archiveFile:I.string().optional(),content:I.string().optional(),isPartial:I.boolean().optional(),pagination:Bs.optional(),warnings:I.array(I.string()).optional()}),rv=I.object({path:I.string(),mode:I.literal("strings"),strings:I.array(I.object({value:I.string(),offset:I.number().optional()})).optional(),content:I.string().optional(),totalStrings:I.number().optional(),scanOffset:I.number().optional(),nextScanOffset:I.number().optional(),hasMore:I.boolean().optional(),warnings:I.array(I.string()).optional()}),ov=I.object({path:I.string(),mode:I.literal("unpack"),localPath:I.string().optional(),fileCount:I.number().optional(),totalSize:I.number().optional(),warnings:I.array(I.string()).optional()}),iv=I.union([ZO,tv,nv,rv,ov]),sW=I.object({results:I.array(I.object({id:I.string(),status:I.enum(["empty","error","success"]).optional(),data:iv}))}).extend(Ft)});import Uy from"path";import{pathValidator as sv}from"@octocodeai/octocode-engine/pathValidator";function tt(e,t){if(!e.path?.trim()){let s=rt.pathValidationFailed("","path is required");return{isValid:!1,errorResult:D(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||De().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Uy.isAbsolute(r)?r:Uy.resolve(n,r),i=sv.validate(o);if(!i.isValid){let s=rt.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:D(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function fW(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:rt.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 Mt=y(()=>{"use strict";uo();js();ot()});import{validateCommand as av}from"@octocodeai/octocode-engine/commandValidator";async function Ar(e,t=[],n={}){let r=av(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=qs(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 Yt(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}}var Ca=y(()=>{"use strict";Tr()});function Ot(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function cv(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},u={command:"7z",args:i},d={command:"7zz",args:i},p={command:"aa",args:s};return Ot($y,e)?[p]:Ot(nd,e)?[u,d,l,c,a]:Ot(td,e)?[l,u,d,c,a]:Ot(ed,e)?[a,c,l,u,d]:[c,a,l,u,d]}function lv(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return Ot(nd,e)?[s,a,o,r,n]:Ot(td,e)?[o,s,a,r,n]:Ot(ed,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function rd(e){let t=[];for(let n of e){let r=await Ar(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function uv(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
|
|
43
37
|
`).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
|
|
44
|
-
`)}async function
|
|
45
|
-
`).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function
|
|
46
|
-
`):null}function
|
|
47
|
-
`),a=s?await
|
|
48
|
-
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let p=r.matchRanges[0],f=r.matchRanges[r.matchRanges.length-1];p&&f&&(l=p.start,u=f.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function
|
|
49
|
-
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function
|
|
50
|
-
`),o=Dt(t);return e.matchString?av(e,r,o):cv(e)?lv(e,r,o):{resultContent:t,isPartial:!1}}function dv(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?F.applyContentViewMinification(t.resultContent,c):t.resultContent,u=e.charLength,d=e.charOffset??0,p=u,f=!1,m=d;p===void 0&&l.length>o&&(p=o,f=!0,a.push(`Auto-paginated: Content (${l.length} chars) exceeds ${o} char limit`));let g="char-limit",b=p;if(p!==void 0){let E=Os(l,m,p,c);g=E.chunkMode,b=E.length}let S=Rr(l,m,b,p!==void 0?{pageSize:p}:void 0),C=t.isPartial||S.hasMore,k;if(S.hasMore&&g==="char-limit"&&Go(S.paginatedContent)){let E=S.charOffset+S.charLength;k=Ho(l,E,c)}let _=S.hasMore&&S.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:S.nextCharOffset,charLength:p??S.charLength,minify:e.minify}}}:void 0;return{path:c,content:S.paginatedContent,...s!=="standard"&&{contentView:s},...C&&{isPartial:C},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()},...(p!==void 0||d>0||f)&&{pagination:{...Ng(S),chunkMode:g,...k!==void 0&&{nextBlockChar:k}}},..._?{next:_}:{},...a.length>0&&{warnings:a}}}function pv(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function wa(e){let t=et();try{let n=Ke(e,A.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=ZO(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await ev(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await ov(o))return j(rv(e,o),c);if(tv(e,l))return j(nv(e,o,l),c);let{content:u,errorResult:d}=await iv(e,o);if(d||u===void 0)return d;let p=JO.sanitizeContent(u,i),f=p.content,m=f.length,g=Buffer.byteLength(f,"utf-8"),b=p.hasSecrets?`Secrets detected and redacted: ${p.secretsDetected.join(", ")}`:void 0,S=e.minify,C=S==="standard"||S==="symbols",k=C?"standard":"none",_;if(S==="symbols"){let I=F.extractSignatures(f,i);if(I===null){let v=_s(f,i);if(v!==null)return j({path:e.path,content:v,contentView:"symbols",isSkeleton:!0,totalLines:Dt(f),...dd(m,g),...b?{warnings:[b]}:{}},m);_=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(I!==null){let v=Dt(f),D=F.applyContentViewMinification(I,i);return j({path:e.path,content:D,contentView:"symbols",isSkeleton:!0,totalLines:v,...dd(m,g),...b?{warnings:[b]}:{}},m)}}let E=Dt(f),O=uv(e,f,t),w=I=>{let v=[..._?[_]:[],...b?[b]:[]];if(v.length===0)return I;let D=I.warnings??[];return{...I,warnings:[...D,...v]}};if(O.earlyResult){let I=O.earlyResult.content,v=C&&typeof I=="string"?{...O.earlyResult,content:F.applyContentViewMinification(I,i)}:O.earlyResult;return j(gb(w(pd(pv(v,k),e,E)),m,g),m)}let H=dv(e,O,s,E,t,C,k);return j(gb(w(pd(H,e,E)),m,g),m)}catch(n){return M(n,e,{toolName:A.LOCAL_FETCH_CONTENT})}}function pd(e,t,n){return e}var oi=y(()=>{"use strict";Ls();be();No();vs();Or();br();yr();fe();Et();eo();jn();ud();oe();Is()});import{z as fv}from"zod";import{FetchContentQuerySchema as hb}from"@octocodeai/octocode-core/schemas";var mv,yb,gv,vr,Ta,ii=y(()=>{"use strict";me();Be();tt();mv=fv.enum(["none","standard","symbols"]).optional().default("standard"),yb={startLine:Pr,endLine:Pr,contextLines:Cr.default(5),charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:mv},gv=he(hb,yb),vr=ue(hb,yb),Ta=ie(gv,{maxQueries:5})});async function bb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Ue(vr,n);return r.ok===!1?r.error:await wa(r.data)}}),{toolName:A.LOCAL_FETCH_CONTENT},e)}var fd=y(()=>{"use strict";fe();je();oi();ii();Fe();Ht();oi()});import{z as hv}from"zod";import{FindFilesQuerySchema as yv}from"@octocodeai/octocode-core/schemas";function bv(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 Rb,Sb,Rv,Ar,Ea,si=y(()=>{"use strict";me();Be();tt();Rb={maxDepth:G(0,100).optional(),minDepth:G(0,100).optional(),limit:G(1,1e4).optional(),page:ae.default(1),itemsPerPage:G(1,50).optional()},Sb=hv.object(Object.fromEntries(Object.entries(yv.shape).filter(([e])=>e!=="regexType")));Rv=he(Sb,Rb),Ar=ue(Sb,Rb).superRefine(bv),Ea=ie(Rv,{maxQueries:5})});function Lr(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 ai(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 ci=y(()=>{"use strict"});function Cv(e,t){let n=t??Sv,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function _r(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Ke(e,A.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:Cv(i.path,i.excludeDir)},a=Ev(s),c=e.limit??1e4,l=F.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),u=l.totalDiscovered,d=l.wasCapped,p=l.entries.map(v=>Pv(v,r)),f=e.sortBy||"modified";xv(p,f,r);let m=wv(p,t,n),g=m.length,b=e.itemsPerPage||20,S=e.page||1,C=Math.max(1,Math.ceil(g/b)),k=(S-1)*b,_=Math.min(k+b,g),O=m.slice(k,_),w=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],H=[...a,...w],I={...g===0?{status:"empty"}:{},path:i.path,files:O,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:g,hasMore:S<C,...S<C?{nextPage:S+1}:{},...d?{totalFilesFound:u}:{}},...H.length>0&&{warnings:H}};return j(Cb(I,e,{totalFiles:g}),l.entries.reduce((v,D)=>v+D.path.length,0))}catch(o){return M(o,e,{toolName:A.LOCAL_FIND_FILES})}}function Pv(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 Cb(e,t,n){return e}function xv(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 wv(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=Lr(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function Ev(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!Tv.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}var Sv,Tv,li=y(()=>{"use strict";Et();ci();be();fe();me();oe();Sv=[];Tv=/^\d+[hdwm]$/});async function Pb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Ue(Ar,n);return r.ok===!1?r.error:await _r(r.data)}}),{toolName:A.LOCAL_FIND_FILES},e)}var md=y(()=>{"use strict";si();fe();je();li();Fe();Ht();li()});import{z as Ir}from"zod";import{RipgrepQuerySchema as xb}from"@octocodeai/octocode-core/schemas";var kv,Ov,wb,vv,Av,Lv,tn,ka,Fr=y(()=>{"use strict";me();Be();tt();kv=["paginated","discovery","detailed","structural"],Ov=["semanticRanking"],wb={mode:Ir.enum(kv).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.'),pattern:Ir.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:Ir.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:Cr,matchContentLength:G(1,1e5).optional().default(500),maxMatchesPerFile:G(1,1e5).optional(),maxFiles:G(1,1e5).optional(),matchPage:ae.optional(),itemsPerPage:G(1,1e3).optional(),page:ae.default(1),unique:Ir.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:Ir.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},vv={...wb,semanticRanking:Ir.never().optional()},Av=he(xb,vv),Lv=ue(xb,wb,{strict:!0,omit:Ov}),tn=Lv.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"]})}),ka=ie(Av,{maxQueries:5})});function yd(e){return Ob.exec(e)?.[1]?.toLowerCase()??""}function Qv(e){let t=yd(e);if(!t)return!1;for(let n of Bv)if(ui[n].extensions.includes(t))return!0;return!1}function Uv(e,t,n){if(n&&n!=="auto")return ui[n];let r=yd(e),o=(t??"").toLowerCase();for(let i of Tb){let s=ui[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Tb){let s=ui[i];if(i!=="generic"&&s.extensions.includes(r))return s}return ui.generic}function vb(e){return Mv.test(e)?"generated":Nv.test(e)?"fixture":Dv.test(e)?"test":Hv.test(e)?"config":Gv.test(e)?"docs":!hd.test(e)&&(zv.test(e)||Qv(e))?"source":"unknown"}function jv(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function $v(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 qv(e,t,n,r,o){if(!e||e.length===0)return 0;let i=rA(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=oA(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${Lb(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=ce.exactWholeWord,p.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=ce.exactCaseInsensitive,p.push("case-insensitive match")):u.includes(r)&&(d+=ce.substring,p.push("substring match")));let f=c.kind;if(f)d+=Vv(f,p);else{let m=iA(u,r,t.id,n.caseSensitive);m!=="code"?(d+=ce.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(gd(t.declaration,u)&&(d+=ce.declarationLine,p.push("declaration line")),gd(t.export,u)&&(d+=ce.exportLine,p.push("export/public line")),gd(t.import,u)&&(d+=ce.importLine,p.push("import line")),t.id==="markdown"&&Fv.test(u)&&(d+=ce.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&Wv(u,r)&&(d+=ce.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function Vv(e,t){switch(e){case"declaration":return t.push("AST: declaration"),ce.declarationLine;case"export":return t.push("AST: export/public"),ce.exportLine;case"configKey":return t.push("AST: config key"),ce.configKeyLine;case"heading":return t.push("AST: heading"),ce.headingLine;case"import":return t.push("AST: import"),ce.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),ce.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function Wv(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 Kv(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(Ob,"").includes(l))&&(s+=ce.pathSegmentToken,i.push("query token in path"))}let a=yd(e);return r.extensions.includes(a)&&t.langType&&(s+=ce.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=ce.sourceDir,i.push("source file")),s}function Yv(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),ce.lowSignalPathPenalty):0}function Xv(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*ce.matchCountScale,r=Math.min(n,ce.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function Jv(e,t){let n=$v(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=>Zv(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 Zv(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Lb(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function eA(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*ce.rareQueryTokenScale,ce.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 tA(e,t,n){let r=Uv(e.path,t.langType,t.profileOverride),o=vb(e.path),i=jv(t.keyword),s=[],a=0;return a+=qv(e.matches,r,t,i,s),a+=Kv(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=ce.pathUnderQuery,s.push("under requested subtree")),a+=Yv(o,t,s),hd.test(e.path)&&!t.explicitLowSignal&&(a+=ce.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=Xv(e.matchCount??0,s),a+=eA(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Ab(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(kb),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,p)=>d.path.localeCompare(p.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??_v,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(kb);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=Jv(i,n),l=i.map(d=>{try{return{file:d,s:tA(d,n,c)}}catch{return{file:d,s:nA()}}});l.sort((d,p)=>{if(p.s.score!==d.s.score)return p.s.score-d.s.score;let f=(p.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(p.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 nA(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function kb(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function gd(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Lb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rA(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function oA(e,t,n){if(e.indexOf(`
|
|
38
|
+
`)}async function qy(e,t){let n=await rd(cv(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?uv(n.stdout,n.commandUsed):n.stdout).split(`
|
|
39
|
+
`).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function Wy(e,t){return rd(lv(e,t))}function dv(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return Ot($y,e)?[c]:Ot(nd,e)?[s,a,o,n,r]:Ot(td,e)?[o,s,a,n,r]:Ot(ed,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Vy(e,t){return rd(dv(e,t))}var ed,td,nd,$y,Ky=y(()=>{"use strict";Ca();ed=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],td=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],nd=[".dmg",".rar",".cpgz"],$y=[".aar",".yaa"]});function gv(e){let t=e.toLowerCase();for(let{ext:n,format:r}of fv)if(t.endsWith(n))return r}async function hv(e){let t=await Ar("file",["--mime-type","-b",e]);if(t.success)return mv[t.stdout.trim().toLowerCase()]}async function yv(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await Ar(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await Ar(r.command,r.args)).stderr,commandUsed:r.command}}async function Yy(e,t){let n;if(t!=="auto"?n=t:n=gv(e)??await hv(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=pv[n],o=await yv(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}var pv,fv,mv,Xy=y(()=>{"use strict";Ca();pv={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},fv=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],mv={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"}});function Jy(e){try{return{success:!0,info:M.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function Zy(e,t,n,r=0){try{let o=M.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var eb=y(()=>{"use strict";we()});import{promises as Lr}from"fs";import{join as od,basename as xa,dirname as bv,resolve as tb,sep as Rv}from"node:path";import{securityRegistry as Sv}from"@octocodeai/octocode-engine/registry";function rb(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function xv(e){return od(ye.unzip,`${xa(e)}-${rb()}`)}function wv(e,t){return od(ye.binary,`${xa(e)}-${t}-${rb()}`)}function Ev(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function id(e,t,n,r){let o=tb(wv(e,t)),i=tb(od(o,Ev(n)));if(!i.startsWith(o+Rv)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await Lr.mkdir(bv(i),{recursive:!0}),await Lr.writeFile(i,r,"utf-8"),i}function kv(){if(!nb){try{Sv.addAllowedCommands(Tv)}catch{}nb=!0}}function sd(e,t,n){let r=M.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
|
|
40
|
+
`):null}function ad(e,t,n,r){let s=Cr(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function Av(e,t){let n=Jy(e);if(!n.success||!n.info)return D(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function Lv(e,t){let n=t.verbose??!1,r=await qy(e,n);if(!r.success)return D(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??Ov,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,u=a?Math.ceil(s.length/a):1,d=a?c<u:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:u,hasMore:d,entriesPerPage:a}}}}async function _v(e,t){let n=t.archiveFile,r=await Wy(e,n);if(!r.success)return D(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return D("Entry is empty",t);let i=await id(e,"extract",n,o);if(t.matchString){let c=sd(o,t.matchString,t.matchStringContextLines??3);if(!c)return D(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=ct(),a=ad(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function Iv(e,t){let n=await Yy(e,t.format??"auto");if(!n.success)return D(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return D("Decompressed file is empty",t);let o=await id(e,"decompress",`${xa(e)}.decompressed.txt`,r);if(t.matchString){let a=sd(r,t.matchString,t.matchStringContextLines??3);if(!a)return D(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=ct(),s=ad(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function Fv(e,t){let n=t.minLength??vv,r=t.includeOffsets??!1,o=t.scanOffset??0,i=Zy(e,n,r,o);if(!i.success)return D(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
|
|
41
|
+
`),a=s?await id(e,"strings",`${xa(e)}.strings.txt`,s):void 0;if(t.matchString){let d=sd(s,t.matchString,t.matchStringContextLines??3);if(!d)return D(`No lines match "${t.matchString}" in extracted strings`,t);s=d}let l=!!a&&t.charOffset===void 0&&t.charLength===void 0&&!t.matchString?Math.min(Cv,ct()):ct(),u=ad(s,t.charOffset,t.charLength,l);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function Mv(e,t){try{await Lr.stat(e)}catch{return D(`File not found: ${e}`,t)}let n=xv(e);await Lr.mkdir(n,{recursive:!0});let r=await Vy(e,n);if(!r.success)return D(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await Lr.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function ob(e){kv();let t=tt(e,Pv);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await Lr.stat(n)).isFile())return D(`Path is not a regular file: ${n}`,e)}catch{return D(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return Av(n,e);case"list":return Lv(n,e);case"extract":return _v(n,e);case"decompress":return Iv(n,e);case"strings":return Fv(n,e);case"unpack":return Mv(n,e);default:return D(`Unknown mode: ${String(e.mode)}`,e)}}var Pv,Cv,Tv,nb,Ov,vv,ib=y(()=>{"use strict";Re();sr();Mt();we();Bo();Sr();Ky();Xy();eb();Pv=v.LOCAL_BINARY_INSPECT,Cv=4e3;Tv=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],nb=!1;Ov=1e3,vv=8});async function sb(e){let{queries:t}=e;return ue(t||[],async n=>Ze({toolName:v.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Ve(vr,n);if(r.ok===!1)return r.error;let o=await ob(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return q(o,s),o}}),{toolName:v.LOCAL_BINARY_INSPECT},e)}var cd=y(()=>{"use strict";si();Re();Be();Qe();ce();Kt();ib()});var $W,Dt,_r=y(()=>{"use strict";$W={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},Dt={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 WW(e){return t=>{}}function ab(e,t){return n=>t}var ld=y(()=>{"use strict"});import{open as Dv,readFile as Nv,stat as Gv}from"fs/promises";import{ContentSanitizer as Hv}from"@octocodeai/octocode-engine/contentSanitizer";function ub(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function cb(e,t,n){return{...e,...ub(t,n)}}function zv(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 Qv(e,t){try{return{fileStats:await Gv(t)}}catch(n){let r=rt.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:D(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Bv(e,t){return t>Dt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function jv(e,t,n){let r=rt.fileTooLarge(e.path,n,Dt.LARGE_FILE_THRESHOLD_KB);return D(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function Uv(e,t){let n=rt.binaryFileUnsupported(e.path);return D(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function $v(e){let n=Buffer.alloc(8192),r;try{r=await Dv(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(ab("binary sample handle close",void 0))}}async function qv(e,t){try{return{content:await Nv(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?rt.fileAccessFailed(e.path,r):rt.fileReadFailed(e.path,r);return{errorResult:D(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Wv(e,t){return{status:"empty",errorCode:Q.NO_MATCHES,totalLines:t}}function Vv(e,t,n){let r=ks(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Wv(e,n)};let o=r.lines.join(`
|
|
42
|
+
`),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 p=r.matchRanges[0],f=r.matchRanges[r.matchRanges.length-1];p&&f&&(l=p.start,u=f.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function Kv(e){return e.startLine!==void 0&&e.endLine!==void 0}function Yv(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(`
|
|
43
|
+
`),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function Xv(e,t,n){let r=t.split(`
|
|
44
|
+
`),o=Wt(t);return e.matchString?Vv(e,r,o):Kv(e)?Yv(e,r,o):{resultContent:t,isPartial:!1}}function db(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=Es(e,l,s,r);u=g.chunkMode,d=g.length}let p=Cr(e,l,d,s!==void 0?{pageSize:s}:void 0),f;if(p.hasMore&&u==="char-limit"&&jo(p.paginatedContent)){let g=p.charOffset+p.charLength;f=Uo(e,g,r)}let m=p.hasMore&&p.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:r,charOffset:p.nextCharOffset,charLength:s??p.charLength,minify:t.minify}}}:void 0;return{windowedContent:p.paginatedContent,pagination:p,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:f,next:m,showPagination:s!==void 0||i>0||a}}function Jv(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?M.applyContentViewMinification(t.resultContent,c):t.resultContent,u=db(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,...s!=="standard"&&{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:{...Zl(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}function lb(e,t,n,r,o,i,s){let a=db(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",isSkeleton:!0,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...ub(r,o),...a.showPagination&&{pagination:{...Zl(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function Zv(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function wa(e){let t=ct();try{let n=tt(e,v.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=zv(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await Qv(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await $v(o))return q(Uv(e,o),c);if(Bv(e,l))return q(jv(e,o,l),c);let{content:u,errorResult:d}=await qv(e,o);if(d||u===void 0)return d;let p=Hv.sanitizeContent(u,i),f=p.content,m=f.length,g=Buffer.byteLength(f,"utf-8"),b=p.hasSecrets?`Secrets detected and redacted: ${p.secretsDetected.join(", ")}`:void 0,w=e.minify,S=w==="standard"||w==="symbols",T=S?"standard":"none",A;if(w==="symbols"){let F=M.extractSignatures(f,i);if(F===null){let O=vs(f,i);if(O!==null)return q(lb(e,O,Wt(f),m,g,b,t),m);A=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(F!==null){let O=Wt(f),B=M.applyContentViewMinification(F,i);return q(lb(e,B,O,m,g,b,t),m)}}let _=Wt(f),k=Xv(e,f,t),x=F=>{let O=[...A?[A]:[],...b?[b]:[]];if(O.length===0)return F;let B=F.warnings??[];return{...F,warnings:[...B,...O]}};if(k.earlyResult){let F=k.earlyResult.content,O=S&&typeof F=="string"?{...k.earlyResult,content:M.applyContentViewMinification(F,i)}:k.earlyResult;return q(cb(x(ud(Zv(O,T),e,_)),m,g),m)}let N=Jv(e,k,s,_,t,S,T);return q(cb(x(ud(N,e,_)),m,g),m)}catch(n){return D(n,e,{toolName:v.LOCAL_FETCH_CONTENT})}}function ud(e,t,n){return e}var ai=y(()=>{"use strict";Os();we();Bo();Ts();_r();Pr();Sr();Re();Mt();uo();wn();ld();ce();As()});import{z as se}from"zod";import{FetchContentQuerySchema as pb}from"@octocodeai/octocode-core/schemas";var eA,fb,tA,Ir,Ea,nA,rA,RV,ci=y(()=>{"use strict";Se();qe();lt();Je();Tt();eA=se.enum(["none","standard","symbols"]).optional().default("standard"),fb={startLine:Er,endLine:Er,contextLines:wr.default(5),charOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional(),minify:eA},tA=Pe(pb,fb),Ir=ge(pb,fb),Ea=le(tA,{maxQueries:5}),nA=se.object({start:se.number(),end:se.number()}),rA=se.object({path:se.string().optional(),content:se.string().optional(),contentView:se.enum(["none","standard","symbols"]).optional(),isSkeleton:se.boolean().optional(),totalLines:se.number().optional(),sourceChars:se.number().optional(),startLine:se.number().optional(),endLine:se.number().optional(),isPartial:se.boolean().optional(),matchRanges:se.array(nA).optional(),pagination:se.union([Bs,Oe]).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()}),RV=se.object({results:se.array(se.object({id:se.string(),status:se.enum(["empty","error"]).optional(),data:rA}))}).extend(Ft)});async function mb(e){let{queries:t}=e;return ue(t||[],async n=>Ze({toolName:v.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Ve(Ir,n);return r.ok===!1?r.error:await wa(r.data)}}),{toolName:v.LOCAL_FETCH_CONTENT,finalize:oA()},e)}function oA(){return({results:e})=>{let t={results:iA(e)},n=Ws(t.results);n&&(t.base=n);let r=Vs(t.results);return r&&(t.shared=r),{structuredContent:Et(t),text:sA(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function iA(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function sA(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(`
|
|
45
|
+
`).trimEnd()+`
|
|
46
|
+
`}var dd=y(()=>{"use strict";Re();Be();xr();Ks();ai();ci();Qe();Kt();ai()});import{z as Ce}from"zod";import{FindFilesQuerySchema as aA}from"@octocodeai/octocode-core/schemas";function cA(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 gb,hb,lA,Fr,Ta,uA,dA,GV,li=y(()=>{"use strict";Se();qe();lt();Je();Tt();gb={maxDepth:H(0,100).optional(),minDepth:H(0,100).optional(),limit:H(1,1e4).optional(),page:pe.default(1),itemsPerPage:H(1,50).optional()},hb=Ce.object(Object.fromEntries(Object.entries(aA.shape).filter(([e])=>e!=="regexType")));lA=Pe(hb,gb),Fr=ge(hb,gb).superRefine(cA),Ta=le(lA,{maxQueries:5}),uA=Ce.object({name:Ce.string().optional(),path:Ce.string().optional(),type:Ce.enum(["file","dir","directory","link","symlink"]).optional(),size:Ce.union([Ce.number(),Ce.string()]).optional(),modified:Ce.string().optional(),accessed:Ce.string().optional(),created:Ce.string().optional(),permissions:Ce.string().optional()}),dA=Ce.object({files:Ce.array(uA).optional(),summary:Ce.string().optional(),pagination:Oe.optional(),warnings:Ce.array(Ce.string()).optional()}),GV=Ce.object({results:Ce.array(Ce.object({id:Ce.string(),status:Ce.enum(["empty","error"]).optional(),data:dA}))}).extend(Ft)});function Mr(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 ui(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 di=y(()=>{"use strict"});function fA(e,t){let n=t??pA,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Dr(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=tt(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:fA(i.path,i.excludeDir)},{warnings:a,query:c}=bA(s),l=e.limit??1e4,u=M.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,p=u.wasCapped,f=u.entries.map(G=>mA(G,r)),m=e.sortBy||"modified";gA(f,m,r);let g=f.slice(0,l),b=hA(g,t,n),w=b.length,S=e.itemsPerPage||20,T=e.page||1,A=Math.max(1,Math.ceil(w/S)),_=(T-1)*S,k=Math.min(_+S,w),N=b.slice(_,k),F=[...u.warnings,...u.skipped>0?[`${u.skipped} entr${u.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],O=[...a,...F],B={...w===0?{status:"empty"}:{},path:i.path,files:N,pagination:{currentPage:T,totalPages:A,filesPerPage:S,totalFiles:w,hasMore:T<A,...T<A?{nextPage:T+1}:{},...p||d>w?{totalFilesFound:d}:{}},...O.length>0&&{warnings:O}};return q(yb(B,e,{totalFiles:w}),u.entries.reduce((G,X)=>G+X.path.length,0))}catch(o){return D(o,e,{toolName:v.LOCAL_FIND_FILES})}}function mA(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 yb(e,t,n){return e}function gA(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 hA(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=Mr(r.size),t&&(o.size=r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function bA(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&&!yA.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 pA,yA,pi=y(()=>{"use strict";Mt();di();we();Re();Se();ce();pA=[];yA=/^\d+[hdwm]$/});async function bb(e){let{queries:t}=e;return ue(t||[],async n=>Ze({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Ve(Fr,n);return r.ok===!1?r.error:await Dr(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var pd=y(()=>{"use strict";li();Re();Be();pi();Qe();Kt();pi()});import{z as K}from"zod";import{RipgrepQuerySchema as Rb}from"@octocodeai/octocode-core/schemas";var RA,SA,Sb,PA,CA,xA,hn,ka,wA,EA,TA,lK,Nr=y(()=>{"use strict";Se();qe();lt();Je();Tt();RA=["paginated","discovery","detailed","structural"],SA=["semanticRanking"],Sb={mode:K.enum(RA).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.'),pattern:K.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:K.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:wr,matchContentLength:H(1,1e5).optional().default(500),maxMatchesPerFile:H(1,1e5).optional(),maxFiles:H(1,1e5).optional(),matchPage:pe.optional(),itemsPerPage:H(1,1e3).optional(),page:pe.default(1),unique:K.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:K.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},PA={...Sb,semanticRanking:K.never().optional()},CA=Pe(Rb,PA),xA=ge(Rb,Sb,{strict:!0,omit:SA}),hn=xA.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"]})}),ka=le(CA,{maxQueries:5}),wA=K.object({line:K.number(),endLine:K.number().optional(),value:K.string().optional(),column:K.number().optional(),count:K.number().optional(),metavars:K.record(K.string(),K.array(K.string())).optional()}),EA=K.object({path:K.string(),matches:K.array(wA).optional(),totalOccurrences:K.number().optional(),totalMatchedLines:K.number().optional(),totalMatchRows:K.number().optional(),returnedMatchRows:K.number().optional(),matchPagination:Oe.optional(),next:K.record(K.string(),Zo).optional()}),TA=K.object({files:K.array(EA).optional(),summary:K.string().optional(),searchEngine:K.string().optional(),pagination:Oe.optional(),next:K.record(K.string(),Zo).optional(),warnings:K.array(K.string()).optional()}),lK=K.object({results:K.array(K.object({id:K.string(),status:K.enum(["empty","error"]).optional(),data:TA}))}).extend(Ft)});function gd(e){return wb.exec(e)?.[1]?.toLowerCase()??""}function NA(e){let t=gd(e);if(!t)return!1;for(let n of DA)if(fi[n].extensions.includes(t))return!0;return!1}function GA(e,t,n){if(n&&n!=="auto")return fi[n];let r=gd(e),o=(t??"").toLowerCase();for(let i of Pb){let s=fi[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Pb){let s=fi[i];if(i!=="generic"&&s.extensions.includes(r))return s}return fi.generic}function Eb(e){return AA.test(e)?"generated":_A.test(e)?"fixture":LA.test(e)?"test":FA.test(e)?"config":IA.test(e)?"docs":!md.test(e)&&(MA.test(e)||NA(e))?"source":"unknown"}function HA(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function zA(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 QA(e,t,n,r,o){if(!e||e.length===0)return 0;let i=JA(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=ZA(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${kb(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=fe.exactWholeWord,p.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=fe.exactCaseInsensitive,p.push("case-insensitive match")):u.includes(r)&&(d+=fe.substring,p.push("substring match")));let f=c.kind;if(f)d+=BA(f,p);else{let m=eL(u,r,t.id,n.caseSensitive);m!=="code"?(d+=fe.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(fd(t.declaration,u)&&(d+=fe.declarationLine,p.push("declaration line")),fd(t.export,u)&&(d+=fe.exportLine,p.push("export/public line")),fd(t.import,u)&&(d+=fe.importLine,p.push("import line")),t.id==="markdown"&&vA.test(u)&&(d+=fe.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&jA(u,r)&&(d+=fe.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function BA(e,t){switch(e){case"declaration":return t.push("AST: declaration"),fe.declarationLine;case"export":return t.push("AST: export/public"),fe.exportLine;case"configKey":return t.push("AST: config key"),fe.configKeyLine;case"heading":return t.push("AST: heading"),fe.headingLine;case"import":return t.push("AST: import"),fe.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),fe.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function jA(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 UA(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(wb,"").includes(l))&&(s+=fe.pathSegmentToken,i.push("query token in path"))}let a=gd(e);return r.extensions.includes(a)&&t.langType&&(s+=fe.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=fe.sourceDir,i.push("source file")),s}function $A(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),fe.lowSignalPathPenalty):0}function qA(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*fe.matchCountScale,r=Math.min(n,fe.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function WA(e,t){let n=zA(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=>VA(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 VA(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${kb(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function KA(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*fe.rareQueryTokenScale,fe.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 YA(e,t,n){let r=GA(e.path,t.langType,t.profileOverride),o=Eb(e.path),i=HA(t.keyword),s=[],a=0;return a+=QA(e.matches,r,t,i,s),a+=UA(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=fe.pathUnderQuery,s.push("under requested subtree")),a+=$A(o,t,s),md.test(e.path)&&!t.explicitLowSignal&&(a+=fe.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=qA(e.matchCount??0,s),a+=KA(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Tb(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(xb),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,p)=>d.path.localeCompare(p.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??kA,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(xb);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=WA(i,n),l=i.map(d=>{try{return{file:d,s:YA(d,n,c)}}catch{return{file:d,s:XA()}}});l.sort((d,p)=>{if(p.s.score!==d.s.score)return p.s.score-d.s.score;let f=(p.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(p.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 XA(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function xb(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function fd(e,t){for(let n of e)if(n.test(t))return!0;return!1}function kb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function JA(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function ZA(e,t,n){if(e.indexOf(`
|
|
51
47
|
`)<0)return e;let o=e.split(`
|
|
52
|
-
`);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function iA(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Iv.test(e))return"comment";let o=sA(e,t,r);if(o<0)return"code";let i=aA(e);return i>=0&&o>i?"comment":cA(e,o)?"string":"code"}function sA(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function aA(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 cA(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function _b(e){if(!e)return!1;if(hd.test(e))return!0;let t=vb(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Tb,ce,_v,Iv,Eb,ui,Fv,hd,Mv,Dv,Nv,Gv,Hv,zv,Bv,Ob,Ib=y(()=>{"use strict";Tb=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],ce={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},_v=2e3,Iv=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Eb={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+['"]/]},ui={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Eb},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Eb},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/]}},Fv=/^\s*#{1,6}\s/,hd=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,Mv=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,Dv=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,Nv=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,Gv=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,Hv=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,zv=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,Bv=new Set(["typescript","javascript","rust","python","go","java","scala"]),Ob=/\.([a-z0-9]+)$/i});async function va(e,t,n,r,o){let i=t.sort??"relevance",s;try{s=Ab(e,i,gA(t),{debug:!!t.debugRanking})}catch{s={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let a=s.files,c=s.debug,l=a.length,u=!!(t.filesOnly||t.filesWithoutMatch),d=!!(t.countLinesPerFile||t.countMatchesPerFile),p=u||d,f=a.reduce((D,Q)=>D+(Q.matchCount??0),0),m=p?o?.totalOccurrences??o?.totalStructuralMatches??f:f,g=t,b=Math.min(g.itemsPerPage||kt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=g.page||1,C=Math.max(1,Math.ceil(l/b)),k=(S-1)*b,_=Math.min(k+b,l),E=a.slice(k,_),O=g.maxMatchesPerFile||kt.DEFAULT_MATCHES_PER_PAGE,w=E.map(D=>{let Q=D.matches?.length??0,ee=Math.ceil(Q/O),B=Math.max(1,g.matchPage||1),Me=(B-1)*O,Ee=Math.min(Me+O,Q),Ct=p?void 0:D.matches?.slice(Me,Ee),dn=Ct?.length,Y=c?.get(D.path);return{path:D.path,...u?{}:t.countLinesPerFile?{totalMatchedLines:D.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:D.matchCount||1}:{totalMatchRows:Q,...dn!==void 0?{returnedMatchRows:dn}:{}},...Ct!==void 0&&{matches:Ct},...Y?{ranking:{score:Y.score,profile:Y.profile,pathRole:Y.pathRole,reasons:Y.reasons}}:{},pagination:!p&&Q>O?{currentPage:B,totalPages:ee,matchesPerPage:O,totalMatches:Q,hasMore:B<ee,...B<ee?{nextMatchPage:B+1}:{}}:void 0}}),H=w.filter(D=>D.pagination?.hasMore),I=dA(w,t,n,{isFileListMode:p,currentPage:S,totalFilePages:C,matchPage:g.matchPage||1,matchesPerPage:O,hasFileWithMoreMatches:H.length>0}),v={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:l,...u?{}:{totalMatches:m},hasMore:S<C,...S<C?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(I).length>0?{next:I}:{}};return Mb(v,t,{totalMatches:m,totalFiles:l})}function Mb(e,t,n){return e}function dA(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=pA(i);s.fetchExact={tool:"localGetFileContent",query:Oa({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:Oa({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=fA(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Oa({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Oa({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function pA(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-Fb),endLine:n+Fb}}function fA(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return mA(e?.metavars);if(!t.matchWindow)return t.onlyMatching?bd(e?.value):bd(t.keywords)}}function mA(e){if(e)for(let t of Object.values(e))for(let n of t){let r=bd(n);if(r)return r}}function bd(e){if(typeof e!="string")return;let t=e.trim();if(uA.test(t)&&!lA.has(t))return t}function Oa(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function gA(e){let t=e.rankingProfile,n=!!(e.include?.length||_b(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var Fb,lA,uA,di=y(()=>{"use strict";Or();Ib();Fb=8,lA=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"]),uA=/^[A-Za-z_$][A-Za-z0-9_$]*$/});function Db(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=F.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&hA(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&yA(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function hA(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function yA(e){return/\(\?[=!<]/.test(e)}var Rd=y(()=>{"use strict";be()});import{validateRipgrepQuery as bA}from"@octocodeai/octocode-core/schemas/runtime";function RA(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function SA(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:RA(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 CA(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 Nb(e){let t=[],n=bA(e);if(!n.isValid)return M(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:A.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=tn.safeParse(e);if(!r.success){let g=r.error.issues.map(b=>b.message);return M(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:A.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return M(new Error("Path is required for search"),o,{toolName:A.LOCAL_RIPGREP,extra:{warnings:t}});let s=Ke(o,A.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Db({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return M(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:A.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await F.searchRipgrep(SA(a))}catch(g){return M(g instanceof Error?g:new Error(String(g)),o,{toolName:A.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(b=>{let S={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(S.count=b.count),b.kind!==void 0&&(S.kind=b.kind),b.scoreHint!==void 0&&(S.scoreHint=b.scoreHint),S})})),p=CA(d),f={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 j({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>kt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await va(d,o,"rg",[...t,...l],f);return j(m,p)}var Sd=y(()=>{"use strict";Et();Fr();Or();fe();di();Rd();oe();be()});function wA(e){return e.trim().replace(/^\./,"").toLowerCase()}function Mr(e){if(!e?.trim())return;let t=wA(e),n=PA[t]??xA[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function TA(e){return[...e??[]].map(t=>`**/*.${t}`)}function Cd(e){return[...e??[]].map(t=>`*.${t}`)}function Aa(e){let t=Mr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Pd(e){let t=Mr(e);return t?t.kind==="extension"&&t.extension?{include:TA([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function xd(e){let t=Mr(e);return t?t.kind==="extension"&&t.extension?Cd([t.extension]):t.kind==="language"?Cd(t.extensions):t.normalized?Cd([t.normalized]):[]:[]}function Gb(e){let t=Mr(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 wd(e){return Mr(e)?.canonicalLanguage}var PA,xA,Td=y(()=>{"use strict";PA={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"]}},xA={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"]}}});import{readFile as EA,stat as kA}from"node:fs/promises";function LA(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function zb(e){return e.include?.length?e.include:Gb(e.langType)}async function _A(e){try{return(await kA(e)).isFile()}catch{return!1}}async function IA(e,t){let n=await EA(e,"utf8"),r=F.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Bb(e){let t=Ke(e,A.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await _A(t.sanitizedPath)?await IA(t.sanitizedPath,e):F.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...zb(e)?{include:zb(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Hb.length?{excludeDir:Hb}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??OA,maxFileBytes:vA})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return M(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:A.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.split(`
|
|
53
|
-
`,1)[0],column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(AA+LA(e.pattern)),await va(r,e,"structural",i,o)}var Hb,OA,vA,AA,Qb=y(()=>{"use strict";be();Et();fe();Td();di();Hb=[],OA=2e3,vA=1e6,AA="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 FA(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 nn(e){let t=FA(e);if(t.mode==="structural")return await Bb(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Nb(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:$.OUTPUT_TOO_LARGE}:M(n,t,{toolName:A.LOCAL_RIPGREP})}}var La=y(()=>{"use strict";Et();jn();fe();Sd();Qb()});async function Ub(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Ue(tn,n);return r.ok===!1?r.error:await nn(r.data)}}),{toolName:A.LOCAL_RIPGREP},e)}var Ed=y(()=>{"use strict";Fr();fe();je();La();Fe();Ht();di()});import{ViewStructureQuerySchema as jb}from"@octocodeai/octocode-core/schemas";var $b,MA,Dr,_a,pi=y(()=>{"use strict";me();Be();tt();$b={maxDepth:G(0,20).optional(),limit:G(1,1e4).optional(),page:ae.default(1),itemsPerPage:G(1,50).optional()},MA=he(jb,$b),Dr=ue(jb,$b),_a=ie(MA,{maxQueries:5})});function GA(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function qb(e,t){let n=e[t];return n===void 0?!1:DA.has(n)||n==="{"&&BA(e,t)}function HA(e,t,n){let r=n.pop()??!1,o=qb(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?Vb(e,t+1):t+1})}function zA(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Vb(e,t)})}function kd(e){if(e.length>NA)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=GA(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=HA(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(qb(e,r)){let i=zA(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function BA(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 Vb(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function GW(e,t){let n=kd(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}var DA,NA,Od=y(()=>{"use strict";DA=new Set(["+","*","?"]),NA=1e3});function Wb(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(!kd(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 Kb(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 Yb(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 vd=y(()=>{"use strict";Od()});function Ad(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+ai(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Lr(r)})`}function Ld(e,t){let n=e.length,r=t.itemsPerPage||kt.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 QA(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 _d(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 Id=y(()=>{"use strict";Or();ci()});async function Ia(e){try{let t=Ke(e,A.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return UA(e,t.sanitizedPath,n)}catch(t){let n=Xe.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function UA(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=$A(e),s=r&&e.limit&&!jA(e,i)?e.limit*2:1e4,a;try{a=F.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:qA(e),limit:s})}catch(k){return KA(k,e,t)}let c=a.entries.map(k=>VA(k,n,e.details??!1)),l=Wb(c,e),u=e.sortBy??"name";l=l.sort((k,_)=>{let E=0;switch(u){case"size":{let O=k.sizeBytes??(k.size?ai(k.size):0),w=_.sizeBytes??(_.size?ai(_.size):0);E=O-w;break}case"time":n&&k.modified&&_.modified?E=k.modified.localeCompare(_.modified):E=k.name.localeCompare(_.name);break;case"extension":E=(k.extension||"").localeCompare(_.extension||"");break;default:E=k.name.localeCompare(_.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=Ld(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(k=>({...Yb(k),path:k.path??`${t.replace(/\/$/,"")}/${k.name}`}))}:{path:t,...Kb(p)},b=[...a.warnings,..._d({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.`]:[]],S=d===0,C=Ad(l);return j(Xb({...S?{status:"empty"}:{},...g,summary:C,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((k,_)=>k+_.path.length,0))}function jA(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function $A(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function qA(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function VA(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:Lr(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=WA(e.permissions)),o}function WA(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 KA(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=Xe.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return M(a,t,{toolName:A.LOCAL_VIEW_STRUCTURE})}function Xb(e,t){return e}var fi=y(()=>{"use strict";ci();fe();Et();eo();vd();Id();oe();be()});async function Jb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Ue(Dr,n);return r.ok===!1?r.error:await Ia(r.data)}}),{toolName:A.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var Fd=y(()=>{"use strict";pi();fe();je();fi();Fe();Ht();fi()});function eR(e){return Array.isArray(e.queries)}function tR(e){return Array.isArray(e.queries)}function nR(e){return Array.isArray(e.children)}var rn,Fa,Zb,mi=y(()=>{"use strict";rn=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],Fa=["fixes","dataflow"],Zb=["packages","repositories"]});import{z as h}from"zod";var Dd,Md,YA,rR,oR,XA,JA,Nr,iR,ZA,eL,An,sR,aR,cR,lR,Ma,tL,dK,nL,rL,uR,Nd,Da,dR,pR,Ln,Gr=y(()=>{"use strict";mi();Dd=h.lazy(()=>h.union([h.strictObject({kind:h.literal("local"),path:h.string().min(1)}),h.strictObject({kind:h.literal("github"),repo:h.string().min(1).optional(),owner:h.string().min(1).optional(),ref:h.string().min(1).optional()}),h.strictObject({kind:h.literal("materialized"),localPath:h.string().min(1),source:Dd.optional()}),h.strictObject({kind:h.literal("npm")})])),Md=h.union([h.string(),h.array(h.string()).max(100)]),YA=h.strictObject({path:Md.optional(),language:Md.optional(),include:h.array(h.string()).max(100).optional(),exclude:h.array(h.string()).max(100).optional(),excludeDir:h.array(h.string()).max(100).optional(),hidden:h.boolean().optional(),noIgnore:h.boolean().optional(),minDepth:h.number().int().min(0).max(64).optional(),maxDepth:h.number().int().min(0).max(64).optional()}).optional(),rR=h.enum(["smart","sensitive","insensitive"]),oR=h.string().max(1e4),XA=h.strictObject({id:h.string().optional(),kind:h.literal("text"),value:oR,case:rR.optional(),wholeWord:h.boolean().optional()}),JA=h.strictObject({id:h.string().optional(),kind:h.literal("regex"),value:oR,dialect:h.enum(["rust","pcre2","provider"]).optional(),case:rR.optional(),wholeWord:h.boolean().optional(),multiline:h.boolean().optional(),dotAll:h.boolean().optional()}),Nr=h.lazy(()=>h.strictObject({pattern:h.string().optional(),kind:h.string().optional(),inside:Nr.optional(),has:Nr.optional(),not:Nr.optional(),all:h.array(Nr).optional(),any:h.array(Nr).optional(),stopBy:h.literal("end").optional()})),iR=h.union([Nr,h.string().min(1)]),ZA=h.strictObject({id:h.string().optional(),kind:h.literal("structural"),lang:h.string().min(1),pattern:h.string().optional(),rule:iR.optional()}),eL=h.strictObject({id:h.string().optional(),kind:h.literal("field"),field:h.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:h.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:h.unknown().optional()}),An=h.lazy(()=>h.discriminatedUnion("kind",[h.strictObject({kind:h.literal("all"),id:h.string().optional(),of:h.array(An).min(1)}),h.strictObject({kind:h.literal("any"),id:h.string().optional(),of:h.array(An).min(1)}),h.strictObject({kind:h.literal("not"),id:h.string().optional(),predicate:An}),XA,JA,ZA,eL])),sR=h.strictObject({mode:h.enum(["never","auto","required"]),strategy:h.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:h.boolean().optional(),forceRefresh:h.boolean().optional()}),aR=h.strictObject({content:h.strictObject({range:h.strictObject({startLine:h.number().int().min(1).optional(),endLine:h.number().int().min(1).optional(),contextLines:h.number().int().min(0).max(100).optional()}).optional(),match:h.strictObject({text:h.string(),regex:h.boolean().optional(),caseSensitive:h.boolean().optional()}).optional(),contentView:h.enum(["exact","compact","symbols"]).optional(),charOffset:h.number().int().min(0).max(1e8).optional(),charLength:h.number().int().min(1).max(5e4).optional(),fullContent:h.boolean().optional()}).optional(),tree:h.strictObject({maxDepth:h.number().int().min(0).max(64).optional(),pattern:h.string().optional(),includeSizes:h.boolean().optional(),extensions:h.array(h.string()).optional(),filesOnly:h.boolean().optional(),directoriesOnly:h.boolean().optional(),sortBy:h.enum(["name","size","time","extension"]).optional(),reverse:h.boolean().optional()}).optional()}),cR=h.strictObject({search:h.strictObject({countLinesPerFile:h.boolean().optional(),countMatchesPerFile:h.boolean().optional(),onlyMatching:h.boolean().optional(),unique:h.boolean().optional(),countUnique:h.boolean().optional(),contextLines:h.number().int().min(0).max(100).optional(),invertMatch:h.boolean().optional(),matchWindow:h.number().int().min(0).optional(),matchContentLength:h.number().int().min(1).optional(),maxMatchesPerFile:h.number().int().min(1).optional(),matchPage:h.number().int().min(1).optional(),sort:h.enum(["relevance","matchCount","path","modified","accessed","created"]).optional(),sortReverse:h.boolean().optional(),rankingProfile:h.string().optional(),debugRanking:h.boolean().optional()}).optional(),budget:h.strictObject({maxFiles:h.number().int().min(1).optional(),maxCandidates:h.number().int().min(1).optional(),maxBytes:h.number().int().min(1).optional(),maxMaterializedBytes:h.number().int().min(1).optional(),maxPlanNodes:h.number().int().min(1).optional(),maxBooleanExpansion:h.number().int().min(1).optional(),timeoutMs:h.number().int().min(1).optional()}).optional()}),lR=h.enum(["discovery","paginated","detailed"]),Ma=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),target:h.enum(rn),from:Dd.optional(),scope:YA,where:An.optional(),materialize:sR.optional(),fetch:aR.optional(),select:h.array(h.string()).optional(),view:lR.optional(),controls:cR.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional()}),tL=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),queries:h.array(Ma).min(1).max(5),combine:h.enum(["independent","merge"]).optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),explain:h.boolean().optional()}),dK=h.union([Ma,tL]),nL=rn,rL=[...rn,...Fa],uR={schema:h.literal("oql").optional(),id:h.string().optional(),mainResearchGoal:h.string().optional(),researchGoal:h.string().optional(),reasoning:h.string().optional()},Nd={...uR,target:h.enum(rL).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:Dd.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:An.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:h.union([sR,h.enum(["never","auto","required"])]).optional(),fetch:aR.optional(),select:h.array(h.string()).optional(),view:lR.optional(),controls:cR.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional(),repo:h.string().optional(),owner:h.string().optional(),ref:h.string().optional(),path:Md.optional(),text:h.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:h.string().optional(),pattern:h.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:iR.optional(),lang:h.string().optional(),and:h.array(h.unknown()).optional(),or:h.array(h.unknown()).optional(),xor:h.array(h.unknown()).optional(),noneOf:h.array(h.unknown()).optional(),oneOf:h.array(h.unknown()).optional(),invert:h.unknown().optional(),filesOnly:h.boolean().optional(),filesWithoutMatch:h.boolean().optional(),verbose:h.boolean().optional()},Da=h.object({...Nd,target:h.enum(nL).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.")}).catchall(h.unknown()),dR=h.object(Nd).catchall(h.unknown()),pR=h.object({...uR,queries:h.array(h.unknown()).min(1)}).catchall(h.unknown()),Ln=h.object({...Nd,queries:h.array(h.unknown()).min(1).max(5).optional(),combine:h.enum(["independent","merge"]).optional()}).catchall(h.unknown())});function x(e,t,n={}){let r=n.severity??(iL.has(e)?"error":"warning"),o=n.blocksAnswer??(oL.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 fR(e){return e.some(t=>t.blocksAnswer)}var oL,iL,on,Rt=y(()=>{"use strict";oL=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","budgetExhausted","contentTruncated"]),iL=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed"]);on=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});import{z as P}from"zod";function gR(e,t){let n=hL[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 de,Gd,mR,sL,aL,cL,lL,uL,dL,pL,fL,mL,gL,hL,hR=y(()=>{"use strict";de=P.number().int().min(1),Gd=P.number().int().min(0),mR=P.enum(["symbols","files","dependencies","relations"]),sL=P.object({match:P.enum(["file","path"]).optional(),concise:P.boolean().optional(),extension:P.string().optional(),filename:P.string().optional(),page:de.optional(),limit:de.optional()}).passthrough(),aL=P.object({type:P.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:P.string().optional(),symbolName:P.string().optional(),symbolKind:P.string().optional(),lineHint:de.optional(),orderHint:P.number().int().optional(),includeDeclaration:P.boolean().optional(),depth:P.number().int().min(0).max(20).optional(),groupByFile:P.boolean().optional(),workspaceRoot:P.string().optional(),format:P.enum(["structured","compact"]).optional(),page:de.optional(),itemsPerPage:de.optional()}).passthrough(),cL=P.object({keywords:P.array(P.string()).optional(),topicsToSearch:P.union([P.string(),P.array(P.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:P.string().optional(),owner:P.string().optional(),stars:P.union([P.string(),P.number()]).optional(),forks:P.string().optional(),goodFirstIssues:P.string().optional(),size:P.string().optional(),created:P.string().optional(),updated:P.string().optional(),license:P.string().optional(),match:P.array(P.enum(["name","description","readme"])).optional(),visibility:P.enum(["public","private"]).optional(),archived:P.boolean().optional(),sort:P.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:P.boolean().optional(),page:de.optional()}).passthrough(),lL=P.object({packageName:P.string().optional(),keywords:P.array(P.string()).optional(),mode:P.enum(["lean","full"]).optional(),page:de.optional()}).passthrough(),uL=P.object({prNumber:de.optional(),concise:P.boolean().optional(),state:P.enum(["open","closed","merged"]).optional(),author:P.string().optional(),label:P.union([P.string(),P.array(P.string())]).optional(),keywordsToSearch:P.union([P.string(),P.array(P.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:P.string().optional(),base:P.string().optional(),created:P.string().optional(),updated:P.string().optional(),closed:P.string().optional(),"merged-at":P.string().optional(),draft:P.boolean().optional(),archived:P.boolean().optional(),sort:P.enum(["created","updated","best-match","comments","reactions"]).optional(),order:P.enum(["asc","desc"]).optional(),reviewMode:P.string().optional(),filePage:de.optional(),commentPage:de.optional(),commitPage:de.optional(),charOffset:Gd.optional(),charLength:de.optional(),minify:P.enum(["none","standard"]).optional(),limit:de.optional(),page:de.optional(),matchString:P.string().optional(),matchScope:P.enum(["body","title","comments","reviews","all"]).optional(),content:P.record(P.string(),P.unknown()).optional()}).passthrough(),dL=P.object({path:P.string().optional(),branch:P.string().optional(),since:P.string().optional(),until:P.string().optional(),author:P.string().optional(),includeDiff:P.boolean().optional(),limit:de.optional(),page:de.optional()}).passthrough(),pL=P.object({mode:P.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:P.string().optional(),entryPageNumber:de.optional(),maxEntries:de.optional(),entriesPerPage:de.optional(),minLength:P.number().int().min(1).max(128).optional(),scanOffset:Gd.optional(),charOffset:Gd.optional(),charLength:de.optional(),matchString:P.string().optional(),detailed:P.boolean().optional(),format:P.string().optional(),verbose:P.boolean().optional(),includeOffsets:P.boolean().optional()}).passthrough(),fL=P.object({prNumber:de.optional(),files:P.array(P.string()).optional(),baseRef:P.string().optional(),headRef:P.string().optional(),path:P.string().optional()}).passthrough(),mL=P.object({goal:P.string().optional(),intent:P.enum(["general","reachability","dependencies","symbols"]).optional(),facets:P.array(mR).optional(),mode:P.enum(["plan","analyze","prove"]).optional(),maxFiles:de.optional()}).passthrough(),gL=P.object({goal:P.string().optional(),intent:P.enum(["general","reachability","dependencies","symbols"]).optional(),facets:P.array(mR).optional(),mode:P.enum(["plan","analyze","prove"]).optional(),maxFiles:de.optional(),subject:P.string().optional(),subjectKind:P.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:P.union([P.string(),P.array(P.string())]).optional(),verdict:P.union([P.string(),P.array(P.string())]).optional(),direction:P.enum(["incoming","outgoing","both"]).optional(),proof:P.enum(["none","lsp"]).optional(),proofLimit:de.max(25).optional(),includePackets:P.boolean().optional(),includeFacts:P.boolean().optional(),includeEdges:P.boolean().optional()}).passthrough(),hL={semantics:aL,repositories:cL,packages:lL,pullRequests:uL,commits:dL,artifacts:pL,diff:fL,research:mL,graph:gL,code:sL}});function J(...e){throw new on(e)}function yR(e){return eR(e)?bL(e):bR(e)}function bL(e){let t=pR.safeParse(e);t.success||J(x("invalidQuery",Na(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)||J(x("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&J(x("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return bR(i)}catch(a){throw a instanceof on?new on(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}:{}}}function bR(e){let t=dR.safeParse(e);t.success||J(x("invalidQuery",Na(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??RL(n);r===void 0&&J(x("invalidQuery",`Could not determine \`target\`; specify one of: ${rn.join(", ")}.`,{queryPath:"target"})),Fa.includes(r)&&J(x("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${rn.join(", ")}.`}})),rn.includes(r)||J(x("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))yL.has(m)||J(x("unknownField",`Unknown field "${m}" is not part of OQL.`,{queryPath:m}));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=xL(n,r),a=TL(n,s),c=EL(n,r),l=_L(n,s,c,r),u=IL(n),d=CL(n,r),p={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(p.target==="code"&&!p.where&&J(x("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.where&&J(x("invalidQuery",`target:"${p.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.from?.kind==="github"&&!(p.from.repo&&p.from.repo.includes("/"))&&J(x("invalidQuery",`target:"${p.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).'}})),p.target==="materialize"&&(p.where&&J(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"})),p.from?.kind!=="github"&&p.from?.kind!=="materialized"&&J(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.'}}))),p.params!==void 0){let m=gR(p.target,p.params);m&&J(x("invalidQuery",m,{queryPath:"params"}))}let f=Ma.safeParse(p);return f.success||J(x("invalidQuery",Na(f.error))),f.data}function RL(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 CL(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!PL(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function PL(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 SL.some(n=>t.includes(n))}function xL(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&J(x("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),wL(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"};Zb.includes(t)||J(x("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function wL(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}function TL(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&&J(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}function EL(e,t){let n=vL(e);e.where&&n&&J(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;zd(r,"where");let o=An.safeParse(r);return o.success||J(x("invalidQuery",Na(o.error),{queryPath:"where"})),o.data}function Hd(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Hd(n),0):e.kind==="not"?1+Hd(e.predicate):1}function OL(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:kL}function vL(e){let t=n=>{let r=Hd(n),o=OL(e);return r>o&&J(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(Hr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(Hr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(Hr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&J(x("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=Hr(e.xor[0]),r=Hr(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(AL(e.oneOf.map(Hr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&J(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&J(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 Hr(e){if(e&&typeof e=="object"&&"kind"in e)return e;J(x("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function AL(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 zd(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&J(x("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>zd(n,`${t}.of[${r}]`));break;case"not":e.predicate||J(x("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),zd(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&J(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":LL(e,t);break;default:break}}function LL(e,t){if(e.op==="exists"){e.value!==void 0&&J(x("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&J(x("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&J(x("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function RR(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 RR(e.predicate);default:return!1}}function _L(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:RR(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function IL(e){return e.fetch?{...e.fetch}:void 0}function Na(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 yL,SL,kL,SR=y(()=>{"use strict";Gr();Rt();hR();mi();yL=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"]);SL=["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"];kL=64});function FL(e){return e?.mode==="auto"||e?.mode==="required"}function ML(e,t){let n=e.target==="files"?_n:sn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:sn,exact:!0,reason:`${t.kind} evaluated locally by ${sn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function DL(e,t,n){let r=FL(e.materialize);if(n)return NL(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:_n,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:zt,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:_n,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:_n,exact:!0,reason:`${Ga(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:_n,exact:!1,reason:`GitHub cannot enumerate files by ${Ga(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Ga(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:sn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:sn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:zt,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:zt,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?Bd(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:sn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:zt,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 Bd(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:_n,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:zt,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:zt,exact:!0,reason:"path/name predicate pushed to provider"}:Bd(e,`field "${t.field}"`,r)}}function Ga(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 NL(e,t,n){let r=Ga(t);return n?{route:"ROUTE",backend:e.target==="files"?_n:sn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:zt,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 Bd(e,t,n){if(n)return{route:"ROUTE",backend:sn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:zt,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 CR(e,t,n=!1){return e.sourceKind==="github"?DL(e,t,n):ML(e,t)}var sn,_n,zt,PR=y(()=>{"use strict";sn="localSearchCode",_n="localFindFiles",zt="ghSearchCode"});function zr(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 Ha=y(()=>{"use strict"});function xR(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&GL.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 "exact" or "compact".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "exact" or "compact".'}})),t}var GL,wR=y(()=>{"use strict";Rt();GL=new Set(["pullRequests","commits","diff"])});function TR(e){let t={schema:ut.schema,view:e.view??ut.view,page:e.page??ut.page,itemsPerPage:e.itemsPerPage??ut.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??ut.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??ut.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??ut.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?ut.detailedCodeContext:ut.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??ut.localSearchSort),t}var ut,ER=y(()=>{"use strict";ut={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function kR(e){return JSON.stringify(e)}function Qd(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${kR(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${kR(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Qd(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=Qd(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 OR(e){return["rule:",...Qd(e,1)].join(`
|
|
54
|
-
`)}var vR=y(()=>{"use strict"});function AR(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function LR(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return AR(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),AR(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=OR(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 In(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return LR(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=LR(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 Ud=y(()=>{"use strict";vR()});var za=y(()=>{"use strict";Td()});function jd(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 nt(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Br(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function $d(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var gi=y(()=>{"use strict"});function HL(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 hi(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=HL(e.where);if(n){let p=_R(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=jd(e.from),g=e.params??{},b=typeof g.extension=="string"||typeof n.extension=="string"?{}:Aa(Br(e.scope)),S=$d(e),C=nt(e.scope);return{ok:!0,diagnostics:[],query:{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...C?{path:C}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...S?{limit:S}:{},...e.page?{page:e.page}:{}}}}let r=In(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=_R(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}=jd(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Aa(Br(e.scope)),u=$d(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return{ok:!0,diagnostics:[],query:{...s?{owner:s}:{},...a?{repo:a}:{},keywords:[i],...l,...nt(e.scope)?{path:nt(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}:{}}}}function _R(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 qd=y(()=>{"use strict";Ud();Rt();za();gi()});function Qr(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return Vd.find(n=>n.id===`${t}.diff.${e.variant}`)}return Vd.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function Wd(e){return Vd.find(t=>t.id===e)}function Kd(e){let t=zL(e.source,e.target);if(e.target==="diff"){let n=zr(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return Qr({sourceKind:t,target:"diff",variant:r})}return Qr({sourceKind:t,target:e.target})}function IR(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function FR(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function zL(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var Vd,MR=y(()=>{"use strict";Ha();Vd=[{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.artifacts",target:"artifacts",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localBinaryInspect",operation:"inspectArtifact",exact:!0}],rowKind:"record",recordType:"artifact",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeArtifacts"]},{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 BL(e,t){return e.id??t}function Yd(e,t,n,r,o,i=!1){let s=BL(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>Yd(e,d,`${n}.of[${p}]`,r,o,i)),l=QL(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=Yd(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=CR(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"&&DR(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:UL(e.target),exact:a.exact}),a.route}function QL(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 UL(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"artifacts":return"inspectArtifact";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function DR(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Xd(e,t){if(!t)return;let n=FR(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Ba(e,t,n){if(!t)return!1;for(let r of IR(t,n))DR(e.backendCalls,r);return!0}function jL(e,t){return NR(e,t,"files")}function NR(e,t,n,r=Qr({sourceKind:"materialized",target:n})){let o=Qr({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Xd(e,o),Xd(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}`)),Ba(e,o,t),Ba(e,r,void 0),!0}function Qa(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Qa):e.kind==="not"?Qa(e.predicate):!1:!1}function $L(e){return e.target==="code"?Wd(Qa(e.where)?"local.code.structural":"local.code.textRegex"):Qr({sourceKind:"materialized",target:e.target})}function qL(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?Wd(Qa(e.where)?"local.code.structural":"local.code.textRegex")??Kd({source:t,target:e.target,params:e.params}):Kd({source:t,target:e.target,params:e.params})}function Jd(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Jd(n),0):e.kind==="not"?1+Jd(e.predicate):1:0}function GR(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=qL(e,o);if(Xd(n,s),e.where)Yd(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&NR(n,o,e.target,$L(e));else if(e.target==="diff"){let m=zr(e.params);m.kind==="prPatch"||m.kind==="directFile"?Ba(n,s,o)||n.diagnostics.push(x("unsupportedTarget",`No transformer registered for target:"diff" lane "${m.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 m=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(m?g&&jL(n,o):Ba(n,s,o))&&(!m||g)&&n.diagnostics.push(x("unsupportedTarget",m?'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(...VL(e,n.nodes)),n.diagnostics.push(...xR(e));let a=WL(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??ut.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=Jd(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(x("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let p={input:t,normalized:e,defaults:TR(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},f=!n.nodes.some(m=>m.route==="UNSUPPORTED")&&!n.diagnostics.some(m=>m.severity==="error"&&m.code!=="planTruncated");return{plan:p,executable:f}}function HR(e){return e.kind==="not"&&e.predicate.kind==="not"?HR(e.predicate.predicate):e}function VL(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=HR(e.where),r=hi({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function WL(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 zR=y(()=>{"use strict";PR();Ha();wR();Rt();ER();qd();MR()});function Ua(e){let t=YL(e),n=JL(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function YL(e){return!e.executable||e.diagnostics.some(t=>KL.has(t.code))?"unsupported":e.approximate||XL(e.diagnostics)?"candidate":fR(e.diagnostics)||BR(e)?"partial":"proof"}function XL(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function BR(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function JL(e){return!e.executable||BR(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function QR(e){return e.some(t=>!t.exact)}function Zd(e,t,n,r,o){return Ua({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var KL,UR=y(()=>{"use strict";Rt();KL=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function Bt(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 ja=y(()=>{"use strict"});function ep(e){return Bt(e)}function ZL(e){if(e)return Bt({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 $a(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,line:1,...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;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}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:e_(ZL(e.pagination),n.length)}}function e_(e,t){if(e)return e.totalItemsKind!=="files"?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function qa(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:ep(e.pagination)}}function jR(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:ep(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=n_(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:ep(e.pagination)}}function n_(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=t_[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function $R(e,t,n,r="compact"){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 t_,qR=y(()=>{"use strict";ja();t_={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import Ka from"node:path";import r_ from"node:fs";function o_(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.")}function Xa(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 KR(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function Ja(e,t,n){if(n){e.langType=n;return}let r=Pd(Br(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=KR(e.include,r.include))}function i_(e){return xd(Br(e))}function VR(e){let t=Ya(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function Za(e){return!!(e?.include?.length||e?.exclude?.length)}function rp(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(VR).filter(i=>!!i);n.length>0&&!e.names&&(e.names=KR(e.names,n));let r=(t?.include??[]).filter(i=>!VR(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=i_(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function s_(e,t){if(Za(t.scope)){op(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function op(e){e.limit=tp,e.itemsPerPage=tp}async function bi(e){let t=e.from,n=o_(e),r=nt(e.scope),o=r?Ka.join(n,r):n;if(!r_.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 u_(e,t,o);case"structure":return S_(e,t,o);case"content":return C_(e,t,o);default:return XR(e,t,o)}}function a_(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?JR(e.predicate):!1}function c_(e){return e.kind==="text"||e.kind==="regex"}function YR(e){return e?.kind==="not"&&c_(e.predicate)}async function XR(e,t,n){let r=e.where;if(a_(r))return b_(e,t,n,r);if(e.view==="discovery"&&YR(r))return f_(e,t,n,r);let o=In(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,...Xa(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...oS(e)};Ja(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),i.rule!==void 0&&(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 nn(s),c=$a(a,t),l=Ur(a,"localSearchCode"),u=l_(a);if(u.length>0){let d=u.reduce((f,m)=>f+(m.total??0),0),p=u.reduce((f,m)=>f+m.shown,0);l.push(x("matchTruncated",`${u.length} file(s) have more matches (showed ${p} 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`).'}})),{...c,diagnostics:l,provenance:[jr("localSearchCode",t,r)]}}function l_(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}async function u_(e,t,n){let r=e.where;if(YR(r))return p_(e,t,n,r);if(r&&JR(r))return d_(e,t,n,r);if(r&&nS(r)){let l=await XR({...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};rp(o,e.scope),s_(o,e);let i=[];r&&rS(r,o,i);let s=await _r(o),a=sp(s,e,n);return{...qa(a,t),diagnostics:[...i,...Ur(a,"localFindFiles")],provenance:[jr("localFindFiles",t,r)]}}function JR(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function d_(e,t,n,r){let o=[],i=[],a=[...(await Va(e,r,t,n,o,i)).values()].sort((c,l)=>c.path.localeCompare(l.path));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}}async function Va(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Va(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:m_(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Va(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,ip(a.get(l),u));return a}case"not":{let s=await eS(e,n,r,o),a=await Va(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return tS(e,t,n,r,o,i)}}async function p_(e,t,n,r){let o=await nn(ZR(e,n,r.predicate)),i=Ur(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[jr("localSearchCode",t,r)]}}async function f_(e,t,n,r){let o=await nn(ZR(e,n,r.predicate));return{...$a(o,t),diagnostics:Ur(o,"localSearchCode"),provenance:[jr("localSearchCode",t,r)]}}function ZR(e,t,n){let o=In(n).match,i={path:t,filesWithoutMatch:!0,...Xa(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...oS(e)};return Ja(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}function m_(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,ip(o,i))}return n}function g_(e,t){return new Set([...e].filter(n=>t.has(n)))}function ip(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}async function h_(e,t,n){return new Set((await eS(e,e.from,t,n)).keys())}async function eS(e,t,n,r){let o={path:n,entryType:"f"};rp(o,e.scope),Za(e.scope)&&(op(o),o.page=1);let i=await _r(o),s=sp(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),np(qa({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function y_(e,t,n,r,o){return new Set((await tS(e,t,e.from,n,r,o)).keys())}async function tS(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};rp(u,e.scope),rS(t,u,i),Za(e.scope)&&(op(u),u.page=1);let d=await _r(u),p=sp(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),np(qa(p,n).results)}let s=In(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:tp,...Xa(e.scope)};Ja(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),a.rule!==void 0&&(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 nn(c);return o.push({backend:"localSearchCode",source:e.from}),np((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function np(e){let t=new Map;for(let n of e)t.set(n.path,ip(t.get(n.path),n));return t}async function b_(e,t,n,r){let o=[],i=[],s=await Wa(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 Wa(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Wa(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:g_(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Wa(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 h_(e,r,o),a=await Wa(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await y_(e,t,r,o,i),rows:[]};default:{let s=await R_(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function R_(e,t,n,r,o,i){let s=In(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...Xa(e.scope)};Ja(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),a.rule!==void 0&&(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 nn(c);return o.push({backend:"localSearchCode",source:n}),$a(l,n).results}async function S_(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 Ia(r);return{...jR(o,t),diagnostics:Ur(o,"localViewStructure"),provenance:[jr("localViewStructure",t,void 0)]}}async function C_(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=E_(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 wa(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...$R(a,t,n,c),diagnostics:Ur(a,"localGetFileContent"),provenance:[jr("localGetFileContent",t,void 0)]}}function sp(e,t,n){if(!Za(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>P_(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 P_(e,t,n){let r=Ya(x_(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>WR(r,i))?!1:!(n?.exclude??[]).some(i=>WR(r,i))}function x_(e,t){let n=Ka.relative(t,e);return!n||n.startsWith("..")||Ka.isAbsolute(n)?e:n}function Ya(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function WR(e,t){let n=Ya(t),r=Ya(e),o=w_(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Ka.posix.basename(r))}function w_(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+=T_(r)}return new RegExp(`${t}$`)}function T_(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function E_(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 nS(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?nS(e.predicate):!1}function rS(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(yi(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(yi(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(yi(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(yi(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(yi(i));break}r&&n.push(x("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function yi(e){return x("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function oS(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&&(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}function Ur(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(k_(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function k_(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 jr(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var tp,ap=y(()=>{"use strict";me();La();li();fi();oi();Ud();qR();Rt();za();gi();tp=1e4});import{completeMetadata as O_}from"@octocodeai/octocode-core";function p2(e){return v_.has(e)}var V,ve,Fn,v_,Ri=y(()=>{"use strict";V=O_.toolNames,ve=V.LSP_GET_SEMANTIC_CONTENT,Fn="oqlSearch",v_=new Set([V.LOCAL_RIPGREP,V.LOCAL_FETCH_CONTENT,V.LOCAL_FIND_FILES,V.LOCAL_VIEW_STRUCTURE,V.LOCAL_BINARY_INSPECT,ve])});function Mn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function cp(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 iS,Dn=y(()=>{"use strict";Ri();iS=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{z as te}from"zod";import{NpmPackageQuerySchema as sS}from"@octocodeai/octocode-core/schemas";var aS,ec,tc,C2,nc=y(()=>{"use strict";Be();tt();Gt();aS={page:ae,mode:te.enum(["lean","full"]).optional()},ec=ue(sS,aS),tc=ie(he(sS,aS,{strict:!0}),{maxQueries:5}),C2=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(),next:te.record(te.string(),te.unknown()).optional()}).passthrough()).optional(),pagination:te.object({currentPage:te.number(),totalPages:te.number(),perPage:te.number(),totalFound:te.number(),returned:te.number(),hasMore:te.boolean(),nextPage:te.number().optional()}).optional()}).optional(),status:te.string().optional()})).optional()}).extend(Qe)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as uS}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as A_}from"@octocodeai/octocode-core/schemas/outputs";var L_,__,I_,dS,F_,Si,M_,Ci,cS,D_,N_,rc,oc,G_,H_,pS,$r,z_,B_,Q_,fS,U_,j_,$_,q_,V_,W_,K_,lS,Y_,Pi=y(()=>{"use strict";me();Be();tt();Dn();L_=G(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),__=G(0,1e5).optional(),I_=["structured","compact"],dS={type:R.enum(iS).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:L_.optional(),orderHint:__,depth:G(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:ae,itemsPerPage:G(1,100).optional(),contextLines:G(0,100).optional(),format:R.enum(I_).optional().default("structured")},F_=he(uS,dS),Si=ue(uS,dS),M_=Si,Ci=ie(F_,{maxQueries:5}),cS=R.object({line:R.number(),character:R.number()}),D_=R.object({start:cS,end:cS}),N_=R.object({startLine:R.number(),endLine:R.number()}),rc=R.object({uri:R.string(),content:R.string().optional(),displayRange:N_.optional(),isDefinition:R.boolean().optional()}),oc=R.string(),G_=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),H_=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),pS=R.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),$r=R.object({category:pS,reason:R.string()}),z_=R.object({currentPage:R.number(),totalPages:R.number(),totalResults:R.number(),hasMore:R.boolean(),itemsPerPage:R.number(),nextPage:R.number().optional()}),B_=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),Q_=R.string(),fS=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),U_=R.string(),j_=R.object({direction:R.enum(["incoming","outgoing"]),item:fS,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),$_=R.string(),q_=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),V_=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),W_=R.string(),K_=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([rc,oc]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([rc,oc]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([rc,oc]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([rc,oc])).optional(),byFile:R.array(R.union([V_,W_])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:$r.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([fS,U_]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([j_,$_])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:q_,empty:$r.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:D_.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([B_,Q_])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:$r.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:$r.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:$r.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:$r.optional()}),R.object({kind:R.literal("empty"),category:pS,reason:R.string()})]),lS=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:G_.optional(),lsp:H_,payload:K_,pagination:z_.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),Y_=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:lS}),R.object({id:R.string().min(1),status:R.literal("error"),data:A_}),R.object({id:R.string().min(1),data:lS})]))})});import{z as lp}from"zod";function sc(e){return Z_.find(t=>t.name===e)}function ic(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===V.PACKAGE_SEARCH?"Package":"Other"}function W2(e){return[...e].sort((t,n)=>{let r=mS.indexOf(ic(t)),o=mS.indexOf(ic(n));if(r!==o)return r-o;let i=gS.get(t)??Number.MAX_SAFE_INTEGER,s=gS.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function K2(e){let t=sc(e);if(!t)return"{}";try{return JSON.stringify(lp.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(lp.toJSONSchema(t.schema),null,2)}}function Y2(e){return JSON.stringify(e??{},null,2)}function X2(e){let t=ic(e),n=[...J_];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function J2(){return RS.map(e=>({...e}))}function Z2(){return JSON.stringify(Object.fromEntries(RS.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function e4(e,t){return t?.tools?.[e]?.description??e}function SS(e){let t=sc(e);if(!t)return[];let n=lp.toJSONSchema(t.schema);if(!qr(n))return[];let r=an(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!mp.has(i)&&!fp(r[i])):[]);return pp(r,o)}function hS(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function eI(e){let t=nI(e);if(t.length>0)return t.map(r=>({...r,command:hS(e,r.query)}));let n=tI(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:hS(e,n)}]}function t4(e){return eI(e)[0]?.query??{}}function tI(e){if(!sc(e))return{};let t=SS(e),n=t.filter(i=>!i.name.includes(".")),r=uI(n),o={};for(let i of r)o[i.name]=mI(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===ve&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function nI(e){return e===Fn?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===V.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"facebook",repo:"react",keywordsToSearch:["useState"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"facebook",repo:"react",path:"packages/react/src",since:"2024-01-01T00:00:00Z",perPage:5}}]:e===V.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"facebook",repo:"react",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["useState"],owner:"facebook",repo:"react",extension:"js",limit:5}}]:e===V.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"facebook",concise:!0,limit:5}}]:e===V.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"facebook",repo:"react",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===V.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"facebook",repo:"react",sparsePath:"packages/react"}}]:e===V.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:e===V.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"src/index.ts",startLine:1,endLine:40,minify:"none"}},{label:"matched slice",query:{path:"src/index.ts",matchString:"registerTool",contextLines:8,minify:"standard"}}]:e===V.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:".",names:["*.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/**",entryType:"f",itemsPerPage:20}}]:e===V.LOCAL_BINARY_INSPECT?[{label:"archive listing",query:{path:"archive.zip",mode:"list",entriesPerPage:50}},{label:"binary strings",query:{path:"dist/app.node",mode:"strings",minLength:8,charLength:2e3}}]:e===ve?[{label:"semantic definition",query:{uri:"/path/to/file.ts",type:"definition",symbolName:"myFunction",lineHint:42}},{label:"symbol outline",query:{uri:"/path/to/file.ts",type:"documentSymbols"}}]:[]}function n4(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Ot("Tool input must be valid JSON.")}return rI(e,r,n)}function rI(e,t,n={}){let r=iI(e,t,n),o=sc(e);if(!o)throw new Ot(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Ot("Tool input does not match the expected schema.",oI(i.error));return i.data}function oI(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function iI(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(an(t)&&Array.isArray(t.queries))r=t.queries;else if(an(t))r=[t];else throw new Ot('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Ot("At least one query is required.");let o=an(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,l)=>{i=!0,n.onUnknownFields?.(c,l)}},a=r.map((c,l)=>sI(e,l,cI(e,c,l,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new Ot("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function sI(e,t,n,r){let o={...n},i=ic(e),s=r.sourceLabel??"direct tool execution",a=aI(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 aI(e,t){return`Execute ${e} via ${t}`}function cI(e,t,n,r={}){if(!an(t))throw new Ot("Tool input must be a JSON object or an array of objects.");let o=new Set([...SS(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...mp]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function lI(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 up(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=qr(e.items)?e.items:void 0;return`array<${n?up(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(qr).map(up).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 uI(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&&dI(i)).sort(pI),o=Math.max(yS,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=>!CS.has(i.name)).filter(i=>i.type!=="boolean").slice(0,yS)}function dI(e){return CS.has(e.name)||e.type==="boolean"?!1:fI(e)?dp.has(e.name):!0}function pI(e,t){let n=dp.get(e.name)??Number.MAX_SAFE_INTEGER,r=dp.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function fI(e){return e.constraints?.includes("default ")===!0}function pp(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&mp.has(o))continue;let s=qr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:up(s),constraints:lI(s),description:typeof s.description=="string"?s.description:void 0}),an(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!fp(s.properties?.[u]):!1):[]);r.push(...pp(s.properties,l,a))}let c=s.type==="array"&&qr(s.items)?s.items:void 0;if(c&&an(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!fp(c.properties?.[u]):!1):[]);r.push(...pp(c.properties,l,a))}}return r}function mI(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[bS(e,n)]}return bS(e,t)}function bS(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"facebook";case"repo":return"react";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"react";default:return e}}function an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qr(e){return an(e)}function fp(e){return qr(e)&&"default"in e}var mS,gS,Ot,X_,mp,J_,RS,Z_,yS,dp,CS,gp=y(()=>{"use strict";Ri();Dn();ta();ei();la();ni();ya();Sa();nc();ii();si();Fr();pi();Pi();ri();Gr();mS=["GitHub","Local Code","Package","Other"],gS=new Map([V.GITHUB_SEARCH_CODE,V.GITHUB_SEARCH_REPOSITORIES,V.GITHUB_SEARCH_PULL_REQUESTS,V.GITHUB_FETCH_CONTENT,V.GITHUB_VIEW_REPO_STRUCTURE,V.GITHUB_CLONE_REPO,V.LOCAL_RIPGREP,V.LOCAL_FIND_FILES,V.LOCAL_FETCH_CONTENT,V.LOCAL_VIEW_STRUCTURE,ve,V.PACKAGE_SEARCH,Fn].map((e,t)=>[e,t])),Ot=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},X_=["id","mainResearchGoal","researchGoal","reasoning"],mp=new Set([...X_]),J_=["id","researchGoal","reasoning"],RS=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],Z_=[{name:V.GITHUB_SEARCH_CODE,schema:aa,inputSchema:ca},{name:V.GITHUB_FETCH_CONTENT,schema:xr,inputSchema:na},{name:V.GITHUB_VIEW_REPO_STRUCTURE,schema:ba,inputSchema:Ra},{name:V.GITHUB_SEARCH_REPOSITORIES,schema:ga,inputSchema:ha},{name:V.GITHUB_SEARCH_PULL_REQUESTS,schema:wr,inputSchema:ma},{name:V.PACKAGE_SEARCH,schema:ec,inputSchema:tc},{name:V.GITHUB_CLONE_REPO,schema:Zo,inputSchema:ea},{name:V.LOCAL_RIPGREP,schema:tn,inputSchema:ka},{name:V.LOCAL_VIEW_STRUCTURE,schema:Dr,inputSchema:_a},{name:V.LOCAL_FIND_FILES,schema:Ar,inputSchema:Ea},{name:V.LOCAL_FETCH_CONTENT,schema:vr,inputSchema:Ta},{name:ve,schema:Si,inputSchema:Ci},{name:V.LOCAL_BINARY_INSPECT,schema:Tr,inputSchema:Ca},{name:Fn,schema:Da,inputSchema:Ln}];yS=4,dp=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]]),CS=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});import{existsSync as PS}from"fs";import{delimiter as gI,dirname as hI,join as xS}from"path";function wS(){return process.platform==="win32"?"npm.cmd":"npm"}function yI(){let e=hI(process.execPath);return xS(e,wS())}function bI(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function RI(){let e=(process.env.PATH??"").split(gI).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...bI()])]}function TS(){let e=yI();if(PS(e))return{command:process.execPath,argsPrefix:[e]};let t=wS();for(let n of RI()){let r=xS(n,t);if(PS(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function a4(e=1e4){let t=TS();return Dh(t.command,[...t.argsPrefix,"--version"],e)}async function xi(e,t,n={}){if(!SI.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Xs(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=TS(),c=await kn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:CI});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var SI,CI,hp=y(()=>{"use strict";Xo();SI=["view","search","ping","config","whoami"],CI=[...Yo,...Mh]});function Ti(e){try{return new URL(e).host||e}catch{return e}}function ES(e,t=Date.now()){let n=Vr.get(Ti(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<wi)throw new yp(Ti(e),wi-r);n.state="half-open"}}function Rp(e){let t=Vr.get(Ti(e));t&&(t.failures=0,t.state="closed")}function kS(e,t=Date.now()){let n=Ti(e),r=Vr.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=bp&&(r.state="open",r.openedAt=t)),Vr.set(n,r)}function u4(){Vr.clear(),bp=5,wi=3e4}function d4(e){typeof e.failureThreshold=="number"&&(bp=e.failureThreshold),typeof e.cooldownMs=="number"&&(wi=e.cooldownMs)}function OS(e,t=Date.now()){let n=Vr.get(Ti(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<wi:!1}var l4,Vr,bp,wi,yp,ac=y(()=>{"use strict";l4=5,Vr=new Map,bp=5,wi=3e4;yp=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});function vS(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function xI(e,t,n,r){e&&Yt({limit_type:"primary",retry_after_seconds:vS(r),api_method:t,api_url:n,provider:e})}function wI(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Xr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&$m(r),e.status===429&&xI(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function TI(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=vS(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function cn(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=PI,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let b=e.includes("?")?"&":"?";d=`${e}${b}version=${encodeURIComponent(Cn)}`}let p={"User-Agent":`Octocode-MCP/${Cn}`,...i},f=globalThis.fetch;if(!f)throw new Error(Xr.FETCH_NOT_AVAILABLE.message);ES(d);let m,g=n+1;for(let b=1;b<=g;b++){if(c?.aborted)throw new Error("Request aborted");try{let S=await f(d,{method:s,headers:p,signal:c});if(!S.ok)throw wI(S,s,d,u,l);if(S.status===204)return Rp(d),null;let C=await S.json();return Rp(d),C}catch(S){let C=S;if(c?.aborted||S instanceof Error&&S.name==="AbortError")throw new Error("Request aborted");if(C&&C.retryable===!1)throw S;if(m=S instanceof Error?S:new Error(String(S)),b===g)break;let k=TI(b,r,o,C);await new Promise(_=>setTimeout(_,k))}}throw kS(d),new Error(Xr.FETCH_FAILED_AFTER_RETRIES.message(g,m?.message||""))}var PI,Sp=y(()=>{"use strict";gs();ft();wo();ac();PI=6e4});import{z as L}from"zod";var cc,EI,AS,LS,Cp=y(()=>{"use strict";cc=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()}),EI=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()}),AS=L.looseObject({objects:L.array(EI),total:L.union([L.number(),L.string()]).optional()}),LS=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});async function Pp(){if(Ei)return Ei;try{let e=await xi("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 Ei=t,t}}catch{}return Ei=lc,lc}function E4(){Ei=null}async function k4(){try{let e=await Pp(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}function Nn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function rt(e){return e===void 0?0:U(e)}async function NS(e){try{let t=`${OI}/${encodeURIComponent(e)}`,n=await cn(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:rt(n)}}catch{return{rawResponseChars:0}}}function uc(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function GS(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function vI(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function AI(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function _S(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 IS(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 LI(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function xp(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Nn(e.repository):(e.repository.url&&(r=Nn(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:LI(e),...o?{repositoryDirectory:o}:{},..._S(e.exports)?{exports:_S(e.exports)}:{},...IS(e.bin,e.name)?{bin:IS(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 _I(e){return typeof e.links?.repository=="string"?Nn(e.links.repository):typeof e.repository=="string"?Nn(e.repository):typeof e.repository?.url=="string"?Nn(e.repository.url):null}function II(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:_I(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 HS(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function zS(e){try{let t=await Pp(),n=HS(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await cn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=rt(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await cn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:rt(i)}}catch{return{rawResponseChars:0}}}async function wp(e,t,n){let[r,o]=await Promise.all([NS(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):zS(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 dc(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function FI(e,t){try{let n=await xi("view",[e,"--json"],{timeout:kI});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,...dc(c)?{}:{errorDetail:c},rawResponseChars:rt(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=rt(o),s=cc.safeParse(o);return s.success?{pkg:xp(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,...dc(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function MI(e,t){try{let n=await Pp(),r=HS(e),o=`${n}/${r}/latest`,i;try{i=await cn(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=rt(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=cc.safeParse(i);return a.success?{pkg:xp(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,...dc(r)?{}:{errorDetail:r},rawResponseChars:0}}}function DI(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function BS(e,t){let n=0,r;for(let o of DI(e)){let i;try{i=await cn(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);dc(l)||(r=l);continue}if(n+=rt(i),!i||typeof i!="object")continue;let s=cc.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:xp(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Tp(e,t=!1){let[n,r]=await Promise.allSettled([FI(e,t),MI(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?wp(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function NI(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Tp(e,t);if(!r){if(o){let s=GS(o);if(s&&n){let a=await BS(e,t);if(a.pkg){let c=await wp(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function GI(e,t,n,r=0){let o=Math.max(t+r,t),i=await xi("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:rt(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=rt(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((m,g)=>{let b=m?.score?.final??0;return(g?.score?.final??0)-b}).slice(r,r+t),d=await Promise.all(u.map(async m=>{if(!m||typeof m!="object")return null;let g=m;if(!g.name)return null;if(n){let b=await Tp(g.name,!0);if(b.pkg)return b}return{pkg:II(g),rawResponseChars:0}})),p=d.map(m=>m?.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+(g?.rawResponseChars??0),0);return{packages:p,totalFound:a.length,rawResponseChars:c+f}}async function HI(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${lc}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await cn(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(m){return{error:`NPM registry search failed: ${m instanceof Error?m.message:String(m)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=rt(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=AS.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((m,g)=>{let b=m.score?.final??0;return(g.score?.final??0)-b}).map(m=>m.package).filter(m=>typeof m.name=="string"&&m.name.length>0).slice(0,t),d=await Promise.all(u.map(async m=>{if(n){let g=await Tp(m.name,!0);if(g.pkg)return g}return{pkg:{name:m.name,npmUrl:(m.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(m.name)}`,repoUrl:m.links?.repository&&typeof m.links.repository=="string"?Nn(m.links.repository):null,version:m.version??"unknown",source:"registry",...m.description?{description:m.description}:{},...m.links?.homepage?{homepage:m.links.homepage}:{}},rawResponseChars:0}})),p=d.map(m=>m.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+g.rawResponseChars,0);return{packages:p,totalFound:AI(c.data.total,p.length),rawResponseChars:a+f}}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 FS(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 cn(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:rt(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:rt(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"?Nn(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:rt(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function MS(e,t,n,r=0){try{let o=await GI(e,t,n,r);if(!("error"in o))return o}catch{}return HI(e,t,n,r)}async function DS(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}):NS(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):zS(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function QS(e,t,n,r=0){let o=He("npm-search",{name:e,limit:t,metadata:n,from:r});return ze(o,async()=>{if(OS(lc)){if(r===0&&t===1&&uc(e)){let u=await BS(e,n);if(u.pkg){let d=await wp(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await FS(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&&uc(e)){let l=await NI(e,n,t===1);if("error"in l){if(!GS(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await MS(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return DS(s);let a=vI(e);if(a!==e){let l=await MS(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return DS(l)}let c=await FS(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 zI(e){try{let t=await xi("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=LS.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 lc,kI,Ei,OI,Ep=y(()=>{"use strict";hp();Sp();Mt();ac();Cp();oe();lc="https://registry.npmjs.org",kI=3e3,Ei=null;OI="https://api.npmjs.org/downloads/point/last-week"});async function US(e){let t=uc(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return QS(e.name,n,!0,r)}var kp=y(()=>{"use strict";Ep()});function BI(e){return"error"in e}function pc(e){return"npmUrl"in e}function QI(e){return pc(e)&&e.path?e.path:e.name}function UI(e){return pc(e)?e.repoUrl:e.repository}function jI(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function $I(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 qI(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 VI(e,t){let n=qI(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function WI(e){let t=QI(e),n=$I(UI(e)),r={name:t};pc(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=jI(pc(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=VI(n,o);return i&&(r.next=i),r}function KI(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 jS(e){return se(e.queries,async t=>{try{if(!t.packageName)return M("Package name is required for package search",t);let n=await US({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(BI(n))return M(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(WI),i=o.length>0,s=r.length>1||n.totalFound>1,a=KI(t,n.totalFound,o.length,s);return _e(t,{packages:o,pagination:a},i,A.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return M(n,t,{toolName:A.PACKAGE_SEARCH})}},{toolName:A.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var Op=y(()=>{"use strict";kp();je();Fe();fe()});import{safeReadFile as YI}from"@octocodeai/octocode-engine/lsp/validation";function ki(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function qS(e,t,n){if(t<=0)return e;let r=await YI(e.uri);if(!r)return e;let o=Do(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(`
|
|
55
|
-
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function XI(e,t){return Promise.all(e.map(async n=>({...n,from:await qS(n.from,t,n.fromRanges)})))}async function JI(e,t){return Promise.all(e.map(async n=>({...n,to:await qS(n.to,t)})))}async function vp(e,t,n,r,o){if(n<=0||!e)return{calls:[],...$S};try{let i=await e.getIncomingCalls(t),s=o>0?await XI(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=ki(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),vp(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 Ap(e,t,n,r,o){if(n<=0||!e)return{calls:[],...$S};try{let i=await e.getOutgoingCalls(t),s=o>0?await JI(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=ki(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Ap(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 $S,Lp=y(()=>{"use strict";br();$S={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});import{readFile as ZI,stat as eF}from"node:fs/promises";import{SymbolResolver as tF,SymbolResolutionError as nF}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as fc}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function _p(e,t){let n=e.uri,r=Ke({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await eF(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:fc.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:fc.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 ZI(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:fc.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function VS(e,t){let n=await _p(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 tF({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:rF(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof nF)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:fc.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 rF(e){return{start:e,end:{line:e.line,character:e.character}}}var Ip=y(()=>{"use strict";Et()});import Oi from"node:path";import{fileURLToPath as oF}from"node:url";import{acquirePooledClient as gc,isLanguageServerAvailable as hc}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as iF}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Dp}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function XS(e){return Fp||(Fp=new Set(F.getSupportedJsTsExtensions().map(t=>`.${t}`))),Fp.has(Oi.extname(e).toLowerCase())}function aF(e,t){let n=e.startsWith("file://")?oF(e):e;return Oi.isAbsolute(n)?n:Oi.resolve(t,n)}function JS(){return[...F.getSupportedJsTsExtensions(),...sF]}function cF(){return JS().map(e=>`**/*.${e}`)}async function uF(e,t){let n=e.symbolName?.trim();if(n)try{return(await F.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:cF(),excludeDir:[...lF],maxSnippetChars:1})).files[0]?.path}catch{return}}async function dF(e,t){if(e.uri)return aF(e.uri,t);let n=await uF(e,t);if(n)return n;try{let o=F.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:JS(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function pF(e){return e instanceof Error?e.message:String(e)}function fF(e,t){if(!XS(e))return null;try{let n=F.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}async function Np(e){return se(e.queries||[],async t=>Ve({toolName:ve,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await TF(t);return hF(yF(t,n))}}),{toolName:ve,minQueryTimeoutMs:3e4},e)}function hF(e){return j(e,U(e))}function yF(e,t){return e.format!=="compact"||!bF(t)?t:RF(t)}function bF(e){return Gn(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Gn(e.payload)}function RF(e){return{...e,format:"compact",payload:SF(e.payload)}}function SF(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(WS)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(PF)}:{locations:(e.locations??[]).map(WS)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:eC(e.root)}:{},direction:e.direction,calls:e.calls.map(xF),...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(CF)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function CF(e){if(!Gn(e))return String(e);let t=Ye(e,"line"),n=Ye(e,"character"),r=Ye(e,"endLine"),o=Qt(e,"kind"),i=Qt(e,"name"),s=Ye(e,"childCount"),a=Qt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function WS(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${nC(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function PF(e){if(!Gn(e))return String(e);let t=Qt(e,"uri"),n=Ye(e,"firstLine"),r=Ye(e,"firstCharacter"),o=Ye(e,"count"),i=tC(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 xF(e){if(!Gn(e))return String(e);let t=Qt(e,"direction"),n=eC(e.item),r=tC(e,"ranges").map(wF).join(","),o=Ye(e,"rangeCount"),i=Ye(e,"rangeSampleCount"),s=Qt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${nC(s,180)}`:""].filter(Boolean).join(" ")}function eC(e){if(!Gn(e))return String(e);let t=Qt(e,"name"),n=Qt(e,"kind"),r=Qt(e,"uri"),o=Ye(e,"line"),i=Ye(e,"endLine"),s=Ye(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function wF(e){return Gn(e)?`${Ye(e,"line")}:${Ye(e,"character")}`:String(e)}function Gn(e){return typeof e=="object"&&e!==null}function Qt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ye(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function tC(e,t){let n=e[t];return Array.isArray(n)?n:[]}function nC(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function TF(e){if(e.type==="documentSymbols")return EF(e);if(e.type==="workspaceSymbol")return LF(e);if(e.type==="diagnostic")return FF(e);let t=await VS(e,ve);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return jF(e,i)}let n=e.workspaceRoot??await Dp(t.value.uri);if(!await hc(t.value.uri,n)){if(e.type==="references"){let i=OF(e,t.value);if(i)return i}return St(e.type,t.value,"Language server unavailable")}let o=await gc(n,t.value.uri);if(!o)return St(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?Mp(e,t.value,"definition","definitionProvider",await iF({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):St(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?Mp(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):St(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?Mp(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):St(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?rC(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):St(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?vF(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):St(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?AF(e,t.value,o):St(e.type,t.value,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return o.hasCapability("typeHierarchyProvider")?IF(e,t.value,o):St(e.type,t.value,"typeHierarchyProvider unsupported",!0)}}async function EF(e){let t=await _p(e,ve);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Dp(t.value.uri),r=await hc(t.value.uri,n),o=r?await gc(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=fF(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let S=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(S)?S:[],a="lsp"}else{let S=zg(t.value.content,t.value.uri);S&&(s=S,a="markdown")}let l=a!==void 0,u=NF(s),d=zF(s),{pageItems:p,pagination:f}=Hn(u,e.page??1,e.itemsPerPage??yc),m=BF(u,S=>S.kind),b=l?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(l?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable; native outline supports JS/TS only")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:p.length,topLevelSymbols:d,kinds:m},payload:{kind:"documentSymbols",symbols:p,...b?{empty:b}:{}},pagination:f}}function Mp(e,t,n,r,o){let i=o.length>0,s=o.map(cp),{pageItems:a,pagination:c}=Hn(s,e.page??1,e.itemsPerPage??ZS);return{type:e.type,uri:t.uri,resolvedSymbol:Mn(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 rC(e,t,n,r=kF){let o=r.kind==="native",i=n.map(d=>{let p=d.uri===t.uri&&d.range.start.line===t.resolvedSymbol.position.line&&d.range.start.character===t.resolvedSymbol.position.character;return{...d,...p?{isDefinition:!0}:{}}}),s=e.groupByFile?$F(i):void 0,a=s??i.map(cp),{pageItems:c,pagination:l}=Hn(a,e.page??1,e.itemsPerPage??ZS),u=i.length===0?{category:"noReferences",reason:o?"no in-file references found":"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:Mn(t.resolvedSymbol),lsp:o?{serverAvailable:!1,source:"native"}:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...s?{byFile:c}:{locations:c},totalReferences:i.length,totalFiles:new Set(i.map(d=>d.uri)).size,...u?{empty:u}:{}},pagination:l,...u&&o?{warnings:["source: native (oxc) \u2014 same-file references only; install a language server for cross-file references."]}:{}}}function OF(e,t){if(!XS(t.uri))return null;let n;try{let i=F.findInFileReferences(t.content,t.uri,t.resolvedSymbol.position.line,t.resolvedSymbol.position.character);if(!i)return null;let s=JSON.parse(i);if(!Array.isArray(s))return null;n=s}catch{return null}let r=t.content.split(`
|
|
56
|
-
`),o=n.map(i=>({uri:t.uri,range:i,content:(r[i.start.line]??"").trim()}));return rC(e,t,o,{kind:"native",scope:"file"})}async function vF(e,t,n){let r=qF(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function AF(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 vp(n,o,i,new Set([ki(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Ap(n,o,i,new Set([ki(o)]),e.contextLines??0):s,l=C=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(C.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(C=>!l(C)),p=[...a.calls.map(C=>({direction:"incoming",...C})),...d.map(C=>({direction:"outgoing",...C}))],f=p.map(C=>C.direction==="incoming"?QF(C,e.contextLines??0):UF(C,e.contextLines??0)),{pageItems:m,pagination:g}=Hn(f,e.page??1,e.itemsPerPage??mF),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",S=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Mn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Gp(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:S,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function LF(e){let t=e.symbolName??"",n=Oi.resolve(e.workspaceRoot??process.cwd()),r=await dF(e,n);if(!await hc(r,n))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};let i=await gc(n,r);if(!i)return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};if(!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{Oi.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: ${pF(u)}`}}}let a=_F(s),{pageItems:c,pagination:l}=Hn(a,e.page??1,e.itemsPerPage??yc);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 _F(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:mc(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function IF(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}=Hn(s,e.page??1,e.itemsPerPage??yc);return{type:e.type,uri:t.uri,resolvedSymbol:Mn(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}}async function FF(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Dp(t):process.cwd());if(!await hc(t,n))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};let o=await gc(n,t);if(!o)return{type:"diagnostic",uri:t,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};if(!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=MF(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Hn(s,e.page??1,e.itemsPerPage??yc);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 MF(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>DF(r))}return[]}function DF(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}:{}}]:[]}function Hn(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function NF(e){let t=[];for(let n of e)oC(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function oC(e,t,n){if(!e||typeof e!="object")return;let r=e,o=HF(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:mc(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)&&GF.has(mc(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)oC(s,t,i)}}function HF(e){if(KS(e.range))return e.range;let t=e.location;return t&&KS(t.range)?t.range:void 0}function KS(e){if(!e||typeof e!="object")return!1;let t=e;return YS(t.start)&&YS(t.end)}function YS(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function zF(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function BF(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function QF(e,t){let n=iC(e.fromRanges);return{direction:"incoming",item:Gp(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...sC(e.from,t)}}function UF(e,t){let n=iC(e.fromRanges);return{direction:"outgoing",item:Gp(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...sC(e.to,t)}}function Gp(e){return{name:e.name,kind:mc(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 iC(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>=gF))break}return n}function sC(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function mc(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function aC(e,t){return/unavailable/i.test(t)?"serverUnavailable":/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function jF(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:aC(e.type,t),reason:t}}}function St(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Mn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:aC(e,n),reason:n}}}function $F(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 qF(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=>VF(r)).join(`
|
|
57
|
-
`)
|
|
58
|
-
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:XF,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return jp(r)}catch{return r}}function JF(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:ZF(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 ZF(e){try{return JSON.stringify(e)}catch{return}}var XF,qp=y(()=>{"use strict";Ko();XF="TOOL_CALLBACK_EXCEPTION"});import{releaseAllPooledClients as e0}from"@octocodeai/octocode-engine/lsp/manager";function t0(e){return async t=>e(t)}function n0(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:t0(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function o0(e){return r0.find(t=>t.name===e)}async function Kp(e,t){let n=o0(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=i0(n,t);return await s0(n),a0(n),await c0(n,r)}catch(r){return $p(n.name,r)}finally{e===ve&&await e0()}}function i0(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function s0(e){e.requiresServerRuntime&&(Vp||(Vp=Um()),await Vp),e.requiresProviders&&(Wp||(Wp=Ih().then(()=>{})),await Wp)}function a0(e){if(!e.isLocal&&!e.isClone)return;let t=ge();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}if(e.isClone&&!(t.local.enabled&&t.local.enableClone)){let n=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true and ENABLE_LOCAL=true to use it.`);throw n.code="cloneDisabled",n}}async function c0(e,t){try{let n=e.security==="remote"?await l0(e,t):await u0(e,t);return jp(n)}catch(n){return $p(e.name,n)}}async function l0(e,t){return pf(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function u0(e,t){return ff(e.execute,e.name)(t)}var Vp,Wp,r0,uC=y(()=>{"use strict";lr();Qs();Ae();Dn();Qp();qp();Oc();gp();Vp=null,Wp=null;r0=cC.map(n0)});var Yp=y(()=>{"use strict";gp();uC()});function Pe(e,t){return Kp(e,{queries:[{...d0,...t}]})}var d0,Rc=y(()=>{"use strict";Yp();d0={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function fC(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 vi(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function p0(e){return e.structuredContent?.results?.[0]?.status}function Sc(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 mC(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function dC(...e){return e.map(mC).filter(Boolean).join("/")}function f0(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function pC(e){return mC(e).split("/").filter(Boolean).length}function m0(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function g0(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function h0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y0(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(h0).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function b0(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(m0).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!y0(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(g0(o.path)))}function gC(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function R0(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 S0(e){return typeof e=="string"?[]:e.matches??[]}async function hC(e){switch(e.target){case"content":return x0(e);case"structure":return w0(e);case"files":return C0(e);default:return P0(e)}}async function C0(e){let t=hi(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 Pe("ghSearchCode",t.query),r=vi(n),o=new Set,i=[];for(let a of r?.files??[]){let c=gC(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Te(e),path:c,entryType:"file"}))}let s=Bt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...Cc(n,"ghSearchCode"),...Sc(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:Te(e)}]}}function Te(e){return e.from??{kind:"github"}}async function P0(e){let t=hi(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Pe("ghSearchCode",t.query),r=vi(n),o=[];for(let s of r?.files??[]){let a=gC(s),c=R0(s),l=S0(s);if(l.length===0){o.push({kind:"code",source:Te(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Te(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=Bt(r?.pagination);return{results:o,...i?{pagination:i}:{},diagnostics:[...Cc(n,"ghSearchCode"),...Sc(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:Te(e)}]}}async function x0(e){let{owner:t,repo:n}=fC(Te(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=T0(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:nt(e.scope)??"",type:"file",minify:o,...Te(e).kind==="github"&&Te(e).ref?{branch:Te(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 Pe("ghGetFileContent",s),c=vi(a),l=o==="none"?"exact":o==="symbols"?"symbols":"compact",u=c?.pagination,d=c?.results??c?.files??[],p=d.map(m=>{let g=m.pagination??u,b=typeof g?.charOffset=="number",S={...m.startLine!==void 0?{startLine:m.startLine}:{},...m.endLine!==void 0?{endLine:m.endLine}:{},...b?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Te(e),path:m.path,content:m.content,contentView:l,...Object.keys(S).length?{range:S}:{}}}),f=u??d.find(m=>m.pagination)?.pagination;return{results:p,...f?.hasMore!==void 0?{pagination:{hasMore:!!f.hasMore,...f.currentPage!==void 0?{currentPage:f.currentPage}:{},...f.totalPages!==void 0?{totalPages:f.totalPages}:{},...f.charLength!==void 0?{itemsPerPage:f.charLength}:{},...f.totalChars!==void 0?{totalItems:f.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...Cc(a,"ghGetFileContent"),...Sc(p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Te(e)}]}}async function w0(e){let{owner:t,repo:n}=fC(Te(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:nt(e.scope)??"",...Te(e).kind==="github"&&Te(e).ref?{branch:Te(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 Pe("ghViewRepoStructure",r),i=vi(o),s=[],a=nt(e.scope);for(let u of f0(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=dC(a,d,p);s.push({kind:"tree",source:Te(e),path:f,entryType:"directory",depth:pC(f)})}for(let p of u.files??[]){let f=dC(a,d,p);s.push({kind:"tree",source:Te(e),path:f,entryType:"file",depth:pC(f)})}}let c=b0(s,e),l=Bt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...Cc(o,"ghViewRepoStructure"),...Sc(c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Te(e)}]}}function T0(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 Cc(e,t){let n=p0(e);if(n==="error"){let r=vi(e);return[x("invalidQuery",r?.error??"GitHub backend error",{backend:t})]}return n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}var yC=y(()=>{"use strict";Rc();ja();Rt();qd();gi()});import bC from"node:path";function RC(e){return[...new Set(e)]}function CC(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 PC(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!bC.isAbsolute(r.localPath)?bC.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function xC(e){if(e.from?.kind!=="github")return bi(e);let t=e.from,{owner:n,repo:r}=CC(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=nt(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 Pe("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=PC(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??{},p={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:RC([...d.excludeDir??[],".git"]),exclude:RC([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await bi(p);return{...f,diagnostics:[...f.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"},...f.provenance]}}async function wC(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[SC(f,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}=CC(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:nt(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await Pe("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=PC(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 p=!i;return{results:[SC(c,t,t.ref,p,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 SC(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 TC=y(()=>{"use strict";Rc();ap();Rt();gi()});import{builtinModules as E0}from"node:module";import Re from"node:path";import{readFile as Pc,readdir as k0}from"node:fs/promises";async function Zp(e){let t=Re.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=L0(r,e.intent,e.facets),i=_0(o,e.facets),s=I0(o,i),a=Q0();if(n==="plan")return F0({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:kC([],[],a)});let c=await M0(t,e.maxFiles??5e3),l=await D0(c.filter(w=>w.endsWith(O0))),u=await z0(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),p=kC(u,d,a);await tM(u);let f=new Set(l.map(w=>w.name).filter(_C)),m=$0(u),g=q0(t,l,u),b=V0(g,m),S=u.filter(w=>!b.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),C=W0(t,l,u,f),k=await Y0(u),_=Z0(k,u,b),E=_.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,O=_.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:b.size,unusedFiles:S.length,unlistedDependencies:C.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:C.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:C.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:_.length,candidateUnusedExports:E,transitiveDeadExports:O,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,H)=>w+H.declarations.length,0),nativeGraphCalls:d.reduce((w,H)=>w+H.calls.length,0)},manifests:l.map(w=>({manifest:zn(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(H=>zn(t,H)),dependencyCount:[...w.deps.keys()].length})),files:S,dependencies:C,symbols:_,graphFacts:d,graphCapabilities:p,caveats:["This is a smart research flow with native AST graph facts where available plus heuristic cross-file reachability. LSP references should be used before destructive cleanup.","Graph capability coverage is explicit: tree-sitter/OXC facts are syntax inventory, not semantic deletion proof.","Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function L0(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 _0(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 I0(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:["localSearchCode structural","lspGetSemantics documentSymbols"],produces:["symbols","lineHints"],evidence:"proof"},{id:"reference-proof",purpose:"Use references grouped by file to separate direct, external, and transitive retention.",tools:["lspGetSemantics references","localSearchCode"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"proof"}),(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 F0(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."]}}async function M0(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await k0(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(v0.has(s.name))continue;await r(Re.join(o,s.name));continue}s.isFile()&&n.push(Re.join(o,s.name))}}return await r(e),n}async function D0(e){return(await Promise.all(e.map(async n=>N0(n)))).filter(n=>n!==null)}async function N0(e){let t=await G0(e);if(!t)return null;let n=Re.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=iM(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:LC(t.name),deps:r,entrypoints:H0(n,t)}}async function G0(e){try{let t=JSON.parse(await Pc(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function H0(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=LC(t[o]);i&&n.add(Re.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(Re.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(Re.resolve(e,o));vC(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(Re.resolve(e,o));return[...n]}function vC(e,t,n){if(typeof t=="string"){n.add(Re.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))vC(e,r,n)}async function z0(e,t){let n=ef(),r=t.filter(i=>n.has(Re.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await Pc(i,"utf8").catch(()=>""),a=Re.extname(i).toLowerCase(),c=B0(s,i,zn(e,i)),l=aM(c?c.imports.map(u=>u.specifier):j0(s));return{path:i,rel:zn(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!AC(u)).map(oM).filter(_C).filter(u=>!A0.has(u)),...c?{graphFacts:c}:{}}}))}function B0(e,t,n){try{let r=F.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??Re.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(sM):[]}}catch{return}}function ef(){if(Ai)return Ai;try{let e=F.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Ai=new Set(e.length>0?e:EC)}catch{Ai=new Set(EC)}return Ai}function Q0(){if(Li)return Li;try{let e=JSON.parse(F.getGraphFactCapabilities());Li=Array.isArray(e)?e.filter(U0):[]}catch{Li=[]}return Li}function U0(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 kC(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...ef()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=OC(e,l=>l.language),s=OC(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 OC(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function j0(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 $0(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,Re.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??Re.dirname(o.path);for(let a of o.imports){if(!AC(a))continue;let c=rM(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function q0(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=Jp(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let s=Jp(Re.resolve(e,i),r);s&&o.add(s)}return[...o]}function V0(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}function W0(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=K0(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:zn(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:zn(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:zn(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function K0(e,t){return t.filter(r=>e.startsWith(`${r.dir}${Re.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function Y0(e){return(await Promise.all(e.map(async n=>{let r=X0(n);if(r.length>0)return r;let o=await Pc(n.path,"utf8").catch(()=>"");return J0(n.rel,o)}))).flat()}function X0(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 J0(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:nM(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 Z0(e,t,n){let r=new Map(t.map(o=>[o.rel,o]));return e.map(o=>{let i=t.filter(u=>u.rel!==o.file&&eM(u.path,o.symbol)),s=i.filter(u=>n.has(u.path)),a=r.get(o.file),c=a?n.has(a.path):!1,l=s.length>0?"reachable":i.length>0?"transitive-dead":c?"candidate-unused-export":"unused-export";return{symbol:o.symbol,kind:o.kind,file:o.file,line:o.line,evidenceSource:o.evidenceSource,directRefs:i.length,externalRefs:s.length,retainedBy:i.map(u=>u.rel),verdict:l}})}function eM(e,t){return Xp.get(e)?.has(t)??!1}async function tM(e){Xp.clear(),await Promise.all(e.map(async t=>{let n=await Pc(t.path,"utf8").catch(()=>"");Xp.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function nM(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function rM(e,t,n){return Jp(Re.resolve(e,t),n)}function Jp(e,t){let n=ef(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(Re.join(e,`index${o}`));return r.find(o=>t.has(o))}function AC(e){return e.startsWith("./")||e.startsWith("../")}function oM(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function iM(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function LC(e){return typeof e=="string"&&e.trim()?e:void 0}function _C(e){return typeof e=="string"&&e.length>0}function sM(e){return typeof e=="string"}function aM(e){return[...new Set(e)]}function zn(e,t){return Re.relative(e,t)||Re.basename(t)}var EC,O0,v0,A0,Ai,Li,Xp,IC=y(()=>{"use strict";be();EC=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],O0="package.json",v0=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),A0=new Set(E0.flatMap(e=>[e,`node:${e}`]));Xp=new Map});import tf from"node:path";function nf(e){let t=e.root,n=[...e.symbols.map(a=>cM(t,a)),...e.files.map(a=>pM(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>fM(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let o={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},i=0,s=0;for(let a of n)o[a.verdict]+=1,i+=a.why.length,s+=a.retainedBy.length+(a.retains?.length??0);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function cM(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=lM(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:"references",source:"ripgrep",confidence:"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:uM(r),next:dM(e,t)}}function lM(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 uM(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via reference scan; likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable references found, but the scan is token-based. Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only referenced from unreachable code. Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function dM(e,t){let n=tf.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:"exact"}}},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 pM(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:tf.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:tf.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function fM(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 FC=y(()=>{"use strict"});import{statSync as mM}from"node:fs";import Z from"node:path";function ln(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function MC(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}}function af(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 gM(e,t){if(!t||Z.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?Z.join(n.base,t):t}function hM(e,t,n){let r=t??n??".";if(!e)return r;if(Z.isAbsolute(e))return e;if(n&&Z.isAbsolute(n))return Z.resolve(n,e);if(t&&Z.isAbsolute(t)){let o=KC(t)?t:Z.dirname(t);return Z.resolve(o,e)}return e}function DC(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function jC(e){if(!e)return[];for(let t of UC){let n=e[t];if(Array.isArray(n))return n}return[e]}function bM(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))yM.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 Ii(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=zM(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function $C(e){return e==="plan"||e==="prove"?e:"analyze"}function xc(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??RM),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 SM(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;qC.includes(o)&&t.add(o)}return t.size>0?t:void 0}function CM(e,t){let n=SM(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 qC){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=xc(e,u.length);o[l]=u.slice(d,p),o[`${l}Page`]=f,s=f.itemsPerPage,a=Math.max(a,f.totalPages??1),f.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 PM(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 NC(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 xM(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:NC(e.relation),verdicts:NC(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 wM(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 Wr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function VC(e,t){if(!wM(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=>Wr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>Wr(i.relation,t)),o=e.why.some(i=>Wr(i.claim,t));return n||r||o}function rf(e,t){e.set(t.id,t)}function TM(e,t,n){Wr(t.claim,n)&&e.set(t.id,t)}function of(e,t,n,r){Wr(n.relation,r)&&(rf(e,n.from),rf(e,n.to),t.set(n.id,n))}function EM(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function kM(e,t,n,r,o,i){let s=t.filter(g=>VC(g,r)),a=xc(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,p=new Map,f={},m={};for(let g of s)f[g.verdict]=(f[g.verdict]??0)+1,m[g.proofStatus]=(m[g.proofStatus]??0)+1;for(let g of c){if(rf(l,g.subject),r.includeFacts)for(let b of g.why)TM(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of g.retainedBy)of(l,u,b,r);if(r.direction!=="incoming")for(let b of g.retains??[])of(l,u,b,r)}for(let b of g.missingProof)p.set(EM(b),b)}return r.includeEdges&&AM(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:p.size,byVerdict:f,proofStatus:m},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...p.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 WC(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 OM(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{subjects:e.length,facts:n,edges:r,byVerdict:t}}function AM(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=LM(a.relation);if(!Wr(c,i))continue;let l=GC(a.from,e,a.line),u=GC(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||of(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 LM(e){let t=e.trim();return vM.has(t)?t:"references"}function GC(e,t,n){let r=_M(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 _M(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:Z.isAbsolute(o)?Z.relative(t,o):o,name:i}}function HC(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function IM(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 FM(e,t,n,r,o){let i=n.filter(l=>VC(l,r)),s=xc(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 DM(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"),MM(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 MM(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 DM(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=Z.isAbsolute(t.subject.uri)?t.subject.uri:Z.resolve(e,t.subject.uri);try{let i=await Pe("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=NM(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=ln(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:cf(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,p=_i(a?.totalReferences)??_i(u?.totalReferences)??_i(a?.referenceCount)??_i(u?.referenceCount)??_i(d?.totalItems)??zC(u)??zC(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:GM(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 NM(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 zC(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 GM(e,t){let n=new Set;return sf(e,n,t),[...n].slice(0,25)}function sf(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)sf(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"&&HM(i)&&t.add(Z.isAbsolute(i)?Z.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])sf(r[o],t,n)}function HM(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}function _i(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function cf(e){return typeof e=="string"?e:void 0}function BC(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zM(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"));case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:void 0}case"pullRequest":return n("number")?`#${n("number")}`:n("url");case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12);case"artifact":return n("localPath")??n("path");case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename");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"}}function lf(e,t){let{status:n,data:r}=ln(e);return n==="error"?[x("invalidQuery",af(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function KC(e){try{let t=Z.isAbsolute(e)?e:Z.resolve(e);return mM(t).isDirectory()}catch{return!1}}function wc(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 un(e){return e.params??{}}function BM(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function uf(e,t){let n={...un(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}function Tc(e,t,n,r){let{data:o,status:i}=ln(e),s=lf(e,n),a=i==="error"?[]:jC(o);a.length===0&&!s.some(d=>d.code==="zeroMatches"||d.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=Bt(c,l);return{results:Ii(a,t,r,bM(o)),...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function QM(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?.pagination;return o?.hasMore&&n.push(x("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:YC(o,t)})),n}function YC(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 UM(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:YC(n,t)}}async function jM(e){let{owner:t}=wc(e.from),n=uf(e,"limit"),r=typeof n.language=="string"?n.language:BM(e),o=wd(r);o&&(n.language=o);let i=await Pe("ghSearchRepos",{...t?{owner:t}:{},...n});return Tc(i,"repository","ghSearchRepos",e.from??{kind:"github"})}async function $M(e){let t=await Pe("npmSearch",{...uf(e)});return Tc(t,"package","npmSearch",e.from??{kind:"npm"})}async function QC(e){let{owner:t,repo:n}=wc(e.from),r=e.target==="commits",o=r?void 0:WM(e),i=r?qM(e):void 0,s=uf(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await Pe("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=Tc(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?YM(c,o):i?VM(c,i):c}function qM(e){let t=un(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function VM(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),p=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,p)+(p<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 WM(e){let t=un(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 KM(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(`
|
|
59
|
-
`)}function YM(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=KM(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}}async function XM(e){let t=un(e),{owner:n,repo:r}=wc(e.from),o=zr(t);if(o.kind==="prPatch"){let i=await Pe("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return Tc(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?JM(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):ZM(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 JM(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=f=>Pe("localGetFileContent",{path:f,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r),o(t.path)]),a=ln(i),c=ln(s),l=typeof a.data?.content=="string"?a.data.content:void 0,u=typeof c.data?.content=="string"?c.data.content:void 0;if(a.status==="error"||c.status==="error"||l===void 0||u===void 0){let f=af(a.data?.error??c.data?.error,"Could not read local file.");return{results:[],diagnostics:[x("invalidQuery",f,{backend:"localGetFileContent"})],provenance:[{backend:"localGetFileContent",source:e.from}]}}let d=XC(l,u);return{results:[{kind:"record",recordType:"diff",id:`${r}..${t.path}`,...e.from?{source:e.from}:{},data:{path:t.path,basePath:r,headPath:t.path,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","Files are identical.",{backend:"localGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"localGetFileContent",source:e.from}]}}async function ZM(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=p=>Pe("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:p,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=MC(i),c=MC(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(p=>p.status==="error"||typeof p.content!="string");if(l){let p=af(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[x("invalidQuery",p,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=XC(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 XC(e,t){let n=e===""?[]:e.split(`
|
|
48
|
+
`);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 eL(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(OA.test(e))return"comment";let o=tL(e,t,r);if(o<0)return"code";let i=nL(e);return i>=0&&o>i?"comment":rL(e,o)?"string":"code"}function tL(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function nL(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 rL(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function Ob(e){if(!e)return!1;if(md.test(e))return!0;let t=Eb(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Pb,fe,kA,OA,Cb,fi,vA,md,AA,LA,_A,IA,FA,MA,DA,wb,vb=y(()=>{"use strict";Pb=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],fe={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},kA=2e3,OA=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Cb={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+['"]/]},fi={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Cb},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Cb},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/]}},vA=/^\s*#{1,6}\s/,md=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,AA=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,LA=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,_A=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,IA=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,FA=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,MA=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,DA=new Set(["typescript","javascript","rust","python","go","java","scala"]),wb=/\.([a-z0-9]+)$/i});async function va(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=Tb(e,s,uL(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),p=!!(t.countLinesPerFile||t.countMatchesPerFile),f=d||p,m=c.reduce((G,X)=>G+(X.matchCount??0),0),g=f?o?.totalOccurrences??o?.totalStructuralMatches??m:m,b=t,w=Math.min(b.itemsPerPage||Dt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=b.page||1,T=Math.max(1,Math.ceil(u/w)),A=(S-1)*w,_=Math.min(A+w,u),k=c.slice(A,_),x=b.maxMatchesPerFile||Dt.DEFAULT_MATCHES_PER_PAGE,N=k.map(G=>{let X=G.matches?.length??0,$=Math.ceil(X/x),Ae=Math.max(1,b.matchPage||1),Le=(Ae-1)*x,tn=Math.min(Le+x,X),nn=f?void 0:G.matches?.slice(Le,tn),oe=nn?.length,vt=l?.get(G.path);return{path:G.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:G.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:G.matchCount||1}:{totalMatchRows:X,...oe!==void 0?{returnedMatchRows:oe}:{}},...nn!==void 0&&{matches:nn},...vt?{ranking:{score:vt.score,profile:vt.profile,pathRole:vt.pathRole,reasons:vt.reasons}}:{},pagination:!f&&X>x?{currentPage:Ae,totalPages:$,matchesPerPage:x,totalMatches:X,hasMore:Ae<$,...Ae<$?{nextMatchPage:Ae+1}:{}}:void 0}}),F=N.filter(G=>G.pagination?.hasMore),O=sL(N,t,n,{isFileListMode:f,currentPage:S,totalFilePages:T,matchPage:b.matchPage||1,matchesPerPage:x,hasFileWithMoreMatches:F.length>0}),B={searchEngine:n,...o?{stats:o}:{},files:N,pagination:{currentPage:S,totalPages:T,filesPerPage:w,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<T,...S<T?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(O).length>0?{next:O}:{}};return Lb(B,t,{totalMatches:g,totalFiles:u})}function Lb(e,t,n){return e}function sL(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=aL(i);s.fetchExact={tool:"localGetFileContent",query:Oa({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:Oa({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=cL(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Oa({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Oa({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function aL(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-Ab),endLine:n+Ab}}function cL(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return lL(e?.metavars);if(!t.matchWindow)return t.onlyMatching?hd(e?.value):hd(t.keywords)}}function lL(e){if(e)for(let t of Object.values(e))for(let n of t){let r=hd(n);if(r)return r}}function hd(e){if(typeof e!="string")return;let t=e.trim();if(iL.test(t)&&!oL.has(t))return t}function Oa(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function uL(e){let t=e.rankingProfile,n=!!(e.include?.length||Ob(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var Ab,oL,iL,mi=y(()=>{"use strict";_r();vb();Ab=8,oL=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"]),iL=/^[A-Za-z_$][A-Za-z0-9_$]*$/});function _b(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=M.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&dL(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&pL(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function dL(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function pL(e){return/\(\?[=!<]/.test(e)}var yd=y(()=>{"use strict";we()});import{validateRipgrepQuery as fL}from"@octocodeai/octocode-core/schemas/runtime";function mL(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function gL(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:mL(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 hL(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 Ib(e){let t=[],n=fL(e);if(!n.isValid)return D(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=hn.safeParse(e);if(!r.success){let g=r.error.issues.map(b=>b.message);return D(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return D(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=tt(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=_b({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return D(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 M.searchRipgrep(gL(a))}catch(g){return D(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(b=>{let w={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(w.count=b.count),b.kind!==void 0&&(w.kind=b.kind),b.scoreHint!==void 0&&(w.scoreHint=b.scoreHint),w})})),p=hL(d),f={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 q({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>Dt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await va(d,o,"rg",[...t,...l],f);return q(m,p)}var bd=y(()=>{"use strict";Mt();Nr();_r();Re();mi();yd();ce();we()});function RL(e){return e.trim().replace(/^\./,"").toLowerCase()}function Gr(e){if(!e?.trim())return;let t=RL(e),n=yL[t]??bL[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function SL(e){return[...e??[]].map(t=>`**/*.${t}`)}function Rd(e){return[...e??[]].map(t=>`*.${t}`)}function Aa(e){let t=Gr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Sd(e){let t=Gr(e);return t?t.kind==="extension"&&t.extension?{include:SL([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function Pd(e){let t=Gr(e);return t?t.kind==="extension"&&t.extension?Rd([t.extension]):t.kind==="language"?Rd(t.extensions):t.normalized?Rd([t.normalized]):[]:[]}function Fb(e){let t=Gr(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 Cd(e){return Gr(e)?.canonicalLanguage}var yL,bL,xd=y(()=>{"use strict";yL={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"]}},bL={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"]}}});import{readFile as PL,stat as CL}from"node:fs/promises";function TL(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function Db(e){return e.include?.length?e.include:Fb(e.langType)}async function kL(e){try{return(await CL(e)).isFile()}catch{return!1}}async function OL(e,t){let n=await PL(e,"utf8"),r=M.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Nb(e){let t=tt(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await kL(t.sanitizedPath)?await OL(t.sanitizedPath,e):M.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...Db(e)?{include:Db(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Mb.length?{excludeDir:Mb}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??xL,maxFileBytes:wL})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return D(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(EL+TL(e.pattern)),await va(r,e,"structural",i,o)}var Mb,xL,wL,EL,Gb=y(()=>{"use strict";we();Mt();Re();xd();mi();Mb=[],xL=2e3,wL=1e6,EL="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 vL(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 Nt(e){let t=vL(e);if(t.mode==="structural")return await Nb(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Ib(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}:D(n,t,{toolName:v.LOCAL_RIPGREP})}}var gi=y(()=>{"use strict";Mt();wn();Re();bd();Gb()});async function Hb(e){let{queries:t}=e;return ue(t||[],async n=>Ze({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Ve(hn,n);return r.ok===!1?r.error:await Nt(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var wd=y(()=>{"use strict";Nr();Re();Be();gi();Qe();Kt();mi()});import{z as te}from"zod";import{ViewStructureQuerySchema as zb}from"@octocodeai/octocode-core/schemas";var Qb,AL,Hr,La,LL,_L,n2,hi=y(()=>{"use strict";Se();qe();lt();Je();Tt();Qb={maxDepth:H(0,20).optional(),limit:H(1,1e4).optional(),page:pe.default(1),itemsPerPage:H(1,50).optional()},AL=Pe(zb,Qb),Hr=ge(zb,Qb),La=le(AL,{maxQueries:5}),LL=te.object({name:te.string().optional(),type:te.enum(["file","dir","directory","link","symlink"]),path:te.string().optional(),depth:te.number().optional(),size:te.union([te.number(),te.string()]).optional(),modified:te.string().optional(),permissions:te.string().optional()}),_L=te.object({path:te.string().optional(),entries:te.array(LL).optional(),files:te.array(te.string()).optional(),folders:te.array(te.string()).optional(),links:te.array(te.string()).optional(),summary:te.union([te.string(),te.record(te.string(),te.unknown())]).optional(),pagination:Oe.optional(),warnings:te.array(te.string()).optional()}),n2=te.object({results:te.array(te.object({id:te.string(),status:te.enum(["empty","error"]).optional(),data:_L}))}).extend(Ft)});function ML(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Bb(e,t){let n=e[t];return n===void 0?!1:IL.has(n)||n==="{"&&GL(e,t)}function DL(e,t,n){let r=n.pop()??!1,o=Bb(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?jb(e,t+1):t+1})}function NL(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:jb(e,t)})}function Ed(e){if(e.length>FL)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=ML(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=DL(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Bb(e,r)){let i=NL(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function GL(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 jb(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function o2(e,t){let n=Ed(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}var IL,FL,Td=y(()=>{"use strict";IL=new Set(["+","*","?"]),FL=1e3});function Ub(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(!Ed(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 $b(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 qb(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 kd=y(()=>{"use strict";Td()});function Od(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+ui(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Mr(r)})`}function vd(e,t){let n=e.length,r=t.itemsPerPage||Dt.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 HL(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 Ad(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 Ld=y(()=>{"use strict";_r();di()});async function _a(e){try{let t=tt(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return zL(e,t.sanitizedPath,n)}catch(t){let n=rt.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function zL(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=BL(e),s=r&&e.limit&&!QL(e,i)?e.limit*2:1e4,a;try{a=M.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:jL(e),limit:s})}catch(T){return qL(T,e,t)}let c=a.entries.map(T=>UL(T,n,e.details??!1)),l=Ub(c,e),u=e.sortBy??"name";l=l.sort((T,A)=>{let _=0;switch(u){case"size":{let k=T.sizeBytes??(T.size?ui(T.size):0),x=A.sizeBytes??(A.size?ui(A.size):0);_=k-x;break}case"time":n&&T.modified&&A.modified?_=T.modified.localeCompare(A.modified):_=T.name.localeCompare(A.name);break;case"extension":_=(T.extension||"").localeCompare(A.extension||"");break;default:_=T.name.localeCompare(A.name);break}return e.reverse?-_:_}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=vd(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(T=>({...qb(T),path:T.path??`${t.replace(/\/$/,"")}/${T.name}`}))}:{path:t,...$b(p)},b=[...a.warnings,...Ad({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.`]:[]],w=d===0,S=Od(l);return q(Wb({...w?{status:"empty"}:{},...g,summary:S,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((T,A)=>T+A.path.length,0))}function QL(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function BL(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function jL(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function UL(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:Mr(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=$L(e.permissions)),o}function $L(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 qL(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=rt.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return D(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function Wb(e,t){return e}var yi=y(()=>{"use strict";di();Re();Mt();uo();kd();Ld();ce();we()});async function Vb(e){let{queries:t}=e;return ue(t||[],async n=>Ze({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Ve(Hr,n);return r.ok===!1?r.error:await _a(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var _d=y(()=>{"use strict";hi();Re();Be();yi();Qe();Kt();yi()});function Xb(e){return Array.isArray(e.queries)}function Jb(e){return Array.isArray(e.queries)}function Zb(e){return Array.isArray(e.children)}var Hn,Ia,Kb,Yb,zr=y(()=>{"use strict";Hn=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],Ia=["fixes","dataflow"],Kb=["packages","repositories"],Yb={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});import{z as h}from"zod";var Fd,Id,WL,eR,tR,VL,KL,Qr,nR,YL,XL,zn,rR,oR,iR,sR,Fa,JL,L2,aR,cR,lR,uR,Ma,dR,pR,Qn,Br=y(()=>{"use strict";zr();Fd=h.lazy(()=>h.union([h.strictObject({kind:h.literal("local"),path:h.string().min(1)}),h.strictObject({kind:h.literal("github"),repo:h.string().min(1).optional(),owner:h.string().min(1).optional(),ref:h.string().min(1).optional()}),h.strictObject({kind:h.literal("materialized"),localPath:h.string().min(1),source:Fd.optional()}),h.strictObject({kind:h.literal("npm")})])),Id=h.union([h.string(),h.array(h.string()).max(100)]),WL=h.strictObject({path:Id.optional(),language:Id.optional(),include:h.array(h.string()).max(100).optional(),exclude:h.array(h.string()).max(100).optional(),excludeDir:h.array(h.string()).max(100).optional(),hidden:h.boolean().optional(),noIgnore:h.boolean().optional(),minDepth:h.number().int().min(0).max(64).optional(),maxDepth:h.number().int().min(0).max(64).optional()}).optional(),eR=h.enum(["smart","sensitive","insensitive"]),tR=h.string().max(1e4),VL=h.strictObject({id:h.string().optional(),kind:h.literal("text"),value:tR,case:eR.optional(),wholeWord:h.boolean().optional()}),KL=h.strictObject({id:h.string().optional(),kind:h.literal("regex"),value:tR,dialect:h.enum(["rust","pcre2","provider"]).optional(),case:eR.optional(),wholeWord:h.boolean().optional(),multiline:h.boolean().optional(),dotAll:h.boolean().optional()}),Qr=h.lazy(()=>h.strictObject({pattern:h.string().optional(),kind:h.string().optional(),inside:Qr.optional(),has:Qr.optional(),not:Qr.optional(),all:h.array(Qr).optional(),any:h.array(Qr).optional(),stopBy:h.literal("end").optional()})),nR=h.union([Qr,h.string().min(1)]),YL=h.strictObject({id:h.string().optional(),kind:h.literal("structural"),lang:h.string().min(1),pattern:h.string().optional(),rule:nR.optional()}),XL=h.strictObject({id:h.string().optional(),kind:h.literal("field"),field:h.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:h.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:h.unknown().optional()}),zn=h.lazy(()=>h.discriminatedUnion("kind",[h.strictObject({kind:h.literal("all"),id:h.string().optional(),of:h.array(zn).min(1)}),h.strictObject({kind:h.literal("any"),id:h.string().optional(),of:h.array(zn).min(1)}),h.strictObject({kind:h.literal("not"),id:h.string().optional(),predicate:zn}),VL,KL,YL,XL])),rR=h.strictObject({mode:h.enum(["never","auto","required"]),strategy:h.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:h.boolean().optional(),forceRefresh:h.boolean().optional()}),oR=h.strictObject({content:h.strictObject({range:h.strictObject({startLine:h.number().int().min(1).optional(),endLine:h.number().int().min(1).optional(),contextLines:h.number().int().min(0).max(100).optional()}).optional(),match:h.strictObject({text:h.string(),regex:h.boolean().optional(),caseSensitive:h.boolean().optional()}).optional(),contentView:h.enum(["exact","compact","symbols"]).optional(),charOffset:h.number().int().min(0).max(1e8).optional(),charLength:h.number().int().min(1).max(5e4).optional(),fullContent:h.boolean().optional()}).optional(),tree:h.strictObject({maxDepth:h.number().int().min(0).max(64).optional(),pattern:h.string().optional(),includeSizes:h.boolean().optional(),extensions:h.array(h.string()).optional(),filesOnly:h.boolean().optional(),directoriesOnly:h.boolean().optional(),sortBy:h.enum(["name","size","time","extension"]).optional(),reverse:h.boolean().optional()}).optional()}),iR=h.strictObject({search:h.strictObject({countLinesPerFile:h.boolean().optional(),countMatchesPerFile:h.boolean().optional(),onlyMatching:h.boolean().optional(),unique:h.boolean().optional(),countUnique:h.boolean().optional(),contextLines:h.number().int().min(0).max(100).optional(),invertMatch:h.boolean().optional(),matchWindow:h.number().int().min(0).optional(),matchContentLength:h.number().int().min(1).optional(),maxMatchesPerFile:h.number().int().min(1).optional(),matchPage:h.number().int().min(1).optional(),sort:h.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:h.boolean().optional(),rankingProfile:h.string().optional(),debugRanking:h.boolean().optional()}).optional(),budget:h.strictObject({maxFiles:h.number().int().min(1).optional(),maxCandidates:h.number().int().min(1).optional(),maxBytes:h.number().int().min(1).optional(),maxMaterializedBytes:h.number().int().min(1).optional(),maxPlanNodes:h.number().int().min(1).optional(),maxBooleanExpansion:h.number().int().min(1).optional(),timeoutMs:h.number().int().min(1).optional()}).optional()}),sR=h.enum(["discovery","paginated","detailed"]),Fa=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),target:h.enum(Hn),from:Fd.optional(),scope:WL,where:zn.optional(),materialize:rR.optional(),fetch:oR.optional(),select:h.array(h.string()).optional(),view:sR.optional(),controls:iR.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional()}),JL=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),queries:h.array(Fa).min(1).max(5),combine:h.enum(["independent","merge"]).optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),explain:h.boolean().optional()}),L2=h.union([Fa,JL]),aR=[...Hn,...Ia],cR={schema:h.literal("oql").optional(),id:h.string().optional(),mainResearchGoal:h.string().optional(),researchGoal:h.string().optional(),reasoning:h.string().optional()},lR={...cR,target:h.enum(aR).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:Fd.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:zn.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:h.union([rR,h.enum(["never","auto","required"])]).optional(),fetch:oR.optional(),select:h.array(h.string()).optional(),view:sR.optional(),controls:iR.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional(),repo:h.string().optional(),owner:h.string().optional(),ref:h.string().optional(),path:Id.optional(),text:h.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:h.string().optional(),pattern:h.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:nR.optional(),lang:h.string().optional(),and:h.array(h.unknown()).optional(),or:h.array(h.unknown()).optional(),xor:h.array(h.unknown()).optional(),noneOf:h.array(h.unknown()).optional(),oneOf:h.array(h.unknown()).optional(),invert:h.unknown().optional(),filesOnly:h.boolean().optional(),filesWithoutMatch:h.boolean().optional(),verbose:h.boolean().optional()},uR={...lR,target:h.enum(aR).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.")},Ma=h.object(uR).catchall(h.unknown()),dR=h.object(lR).catchall(h.unknown()),pR=h.object({...cR,queries:h.array(h.unknown()).min(1)}).catchall(h.unknown()),Qn=h.object({...uR,queries:h.array(h.unknown()).min(1).max(5).optional(),combine:h.enum(["independent","merge"]).optional()}).catchall(h.unknown())});function P(e,t,n={}){let r=n.severity??(e_.has(e)?"error":"warning"),o=n.blocksAnswer??(ZL.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 fR(e){return e.some(t=>t.blocksAnswer)}var ZL,e_,yn,yt=y(()=>{"use strict";ZL=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"]),e_=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);yn=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});import{z as C}from"zod";function gR(e,t){let n=d_[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 he,Md,mR,t_,n_,r_,o_,i_,s_,a_,c_,l_,u_,d_,hR=y(()=>{"use strict";he=C.number().int().min(1),Md=C.number().int().min(0),mR=C.enum(["symbols","files","dependencies","relations"]),t_=C.object({match:C.enum(["file","path"]).optional(),concise:C.boolean().optional(),extension:C.string().optional(),filename:C.string().optional(),page:he.optional(),limit:he.optional()}).passthrough(),n_=C.object({type:C.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:C.string().optional(),symbolName:C.string().optional(),symbolKind:C.string().optional(),lineHint:he.optional(),orderHint:C.number().int().optional(),includeDeclaration:C.boolean().optional(),depth:C.number().int().min(0).max(20).optional(),groupByFile:C.boolean().optional(),workspaceRoot:C.string().optional(),format:C.enum(["structured","compact"]).optional(),page:he.optional(),itemsPerPage:he.optional()}).passthrough(),r_=C.object({keywords:C.array(C.string()).optional(),topicsToSearch:C.union([C.string(),C.array(C.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:C.string().optional(),owner:C.string().optional(),stars:C.union([C.string(),C.number()]).optional(),forks:C.string().optional(),goodFirstIssues:C.string().optional(),size:C.string().optional(),created:C.string().optional(),updated:C.string().optional(),license:C.string().optional(),match:C.array(C.enum(["name","description","readme"])).optional(),visibility:C.enum(["public","private"]).optional(),archived:C.boolean().optional(),sort:C.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:C.boolean().optional(),page:he.optional()}).passthrough(),o_=C.object({packageName:C.string().optional(),keywords:C.array(C.string()).optional(),mode:C.enum(["lean","full"]).optional(),page:he.optional()}).passthrough(),i_=C.object({prNumber:he.optional(),concise:C.boolean().optional(),state:C.enum(["open","closed","merged"]).optional(),author:C.string().optional(),label:C.union([C.string(),C.array(C.string())]).optional(),keywordsToSearch:C.union([C.string(),C.array(C.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:C.string().optional(),base:C.string().optional(),created:C.string().optional(),updated:C.string().optional(),closed:C.string().optional(),"merged-at":C.string().optional(),draft:C.boolean().optional(),archived:C.boolean().optional(),sort:C.enum(["created","updated","best-match","comments","reactions"]).optional(),order:C.enum(["asc","desc"]).optional(),reviewMode:C.string().optional(),filePage:he.optional(),commentPage:he.optional(),commitPage:he.optional(),charOffset:Md.optional(),charLength:he.optional(),minify:C.enum(["none","standard"]).optional(),limit:he.optional(),page:he.optional(),matchString:C.string().optional(),matchScope:C.enum(["body","title","comments","reviews","all"]).optional(),content:C.record(C.string(),C.unknown()).optional()}).passthrough(),s_=C.object({path:C.string().optional(),branch:C.string().optional(),since:C.string().optional(),until:C.string().optional(),author:C.string().optional(),includeDiff:C.boolean().optional(),limit:he.optional(),page:he.optional()}).passthrough(),a_=C.object({mode:C.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:C.string().optional(),entryPageNumber:he.optional(),maxEntries:he.optional(),entriesPerPage:he.optional(),minLength:C.number().int().min(1).max(128).optional(),scanOffset:Md.optional(),charOffset:Md.optional(),charLength:he.optional(),matchString:C.string().optional(),detailed:C.boolean().optional(),format:C.string().optional(),verbose:C.boolean().optional(),includeOffsets:C.boolean().optional()}).passthrough(),c_=C.object({prNumber:he.optional(),files:C.array(C.string()).optional(),baseRef:C.string().optional(),headRef:C.string().optional(),path:C.string().optional()}).passthrough(),l_=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array(mR).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:he.optional()}).passthrough(),u_=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array(mR).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:he.optional(),subject:C.string().optional(),subjectKind:C.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:C.union([C.string(),C.array(C.string())]).optional(),verdict:C.union([C.string(),C.array(C.string())]).optional(),direction:C.enum(["incoming","outgoing","both"]).optional(),proof:C.enum(["none","lsp"]).optional(),proofLimit:he.max(25).optional(),includePackets:C.boolean().optional(),includeFacts:C.boolean().optional(),includeEdges:C.boolean().optional()}).passthrough(),d_={semantics:n_,repositories:r_,packages:o_,pullRequests:i_,commits:s_,artifacts:a_,diff:c_,research:l_,graph:u_,code:t_}});function J(...e){throw new yn(e)}function yR(e){return Xb(e)?f_(e):bR(e)}function f_(e){let t=pR.safeParse(e);t.success||J(P("invalidQuery",Da(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)||J(P("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&J(P("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return bR(i)}catch(a){throw a instanceof yn?new yn(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}:{}}}function bR(e){let t=dR.safeParse(e);t.success||J(P("invalidQuery",Da(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??m_(n);r===void 0&&J(P("invalidQuery",`Could not determine \`target\`; specify one of: ${Hn.join(", ")}.`,{queryPath:"target"})),Ia.includes(r)&&J(P("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${Hn.join(", ")}.`}})),Hn.includes(r)||J(P("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))p_.has(m)||J(P("unknownField",`Unknown field "${m}" is not part of OQL.`,{queryPath:m}));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=b_(n,r),a=S_(n,s),c=P_(n,r),l=k_(n,s,c,r),u=O_(n),d=h_(n,r),p={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(p.target==="code"&&!p.where&&J(P("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.where&&J(P("invalidQuery",`target:"${p.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.from?.kind==="github"&&!(p.from.repo&&p.from.repo.includes("/"))&&J(P("invalidQuery",`target:"${p.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).'}})),p.target==="materialize"&&(p.where&&J(P("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"})),p.from?.kind!=="github"&&p.from?.kind!=="materialized"&&J(P("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.'}}))),p.params!==void 0){let m=gR(p.target,p.params);m&&J(P("invalidQuery",m,{queryPath:"params"}))}let f=Fa.safeParse(p);return f.success||J(P("invalidQuery",Da(f.error))),f.data}function m_(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 h_(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!y_(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function y_(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 g_.some(n=>t.includes(n))}function b_(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&J(P("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),R_(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"};Kb.includes(t)||J(P("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function R_(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}function S_(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&&J(P("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}function P_(e,t){let n=w_(e);e.where&&n&&J(P("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;Nd(r,"where"),Gd(r,"where",new Map);let o=zn.safeParse(r);return o.success||J(P("invalidQuery",Da(o.error),{queryPath:"where"})),o.data}function Dd(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Dd(n),0):e.kind==="not"?1+Dd(e.predicate):1}function x_(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:C_}function w_(e){let t=n=>{let r=Dd(n),o=x_(e);return r>o&&J(P("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(jr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(jr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(jr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&J(P("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=jr(e.xor[0]),r=jr(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(E_(e.oneOf.map(jr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&J(P("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&J(P("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 jr(e){if(e&&typeof e=="object"&&"kind"in e)return e;J(P("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function E_(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 Nd(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&J(P("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Nd(n,`${t}.of[${r}]`));break;case"not":e.predicate||J(P("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Nd(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&J(P("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":T_(e,t);break;default:break}}function Gd(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&J(P("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)=>Gd(r,`${t}.of[${o}]`,n)):e.kind==="not"&&Gd(e.predicate,`${t}.predicate`,n)}function T_(e,t){if(e.op==="exists"){e.value!==void 0&&J(P("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&J(P("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&J(P("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function RR(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 RR(e.predicate);default:return!1}}function k_(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:RR(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function O_(e){return e.fetch?{...e.fetch}:void 0}function Da(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 p_,g_,C_,SR=y(()=>{"use strict";Br();yt();hR();zr();p_=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"]);g_=["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"];C_=64});function v_(e){return e?.mode==="auto"||e?.mode==="required"}function A_(e,t){let n=e.target==="files"?Bn:bn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:bn,exact:!0,reason:`${t.kind} evaluated locally by ${bn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function L_(e,t,n){let r=v_(e.materialize);if(n)return __(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:Bn,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:Xt,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:Bn,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:Xt,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:Bn,exact:!0,reason:`${Na(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:Bn,exact:!1,reason:`GitHub cannot enumerate files by ${Na(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Na(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:bn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:bn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:Xt,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:Xt,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?Hd(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:bn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:Xt,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 Hd(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:Bn,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:Xt,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:Xt,exact:!0,reason:"path/name predicate pushed to provider"}:Hd(e,`field "${t.field}"`,r)}}function Na(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 __(e,t,n){let r=Na(t);return n?{route:"ROUTE",backend:e.target==="files"?Bn:bn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:Xt,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 Hd(e,t,n){if(n)return{route:"ROUTE",backend:bn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:Xt,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 PR(e,t,n=!1){return e.sourceKind==="github"?L_(e,t,n):A_(e,t)}var bn,Bn,Xt,CR=y(()=>{"use strict";bn="localSearchCode",Bn="localFindFiles",Xt="ghSearchCode"});function Ur(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 Ga=y(()=>{"use strict"});function xR(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&I_.has(e.target)&&t.push(P("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "exact" or "compact".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "exact" or "compact".'}})),t}var I_,wR=y(()=>{"use strict";yt();I_=new Set(["pullRequests","commits","diff"])});function ER(e){let t={schema:bt.schema,view:e.view??bt.view,page:e.page??bt.page,itemsPerPage:e.itemsPerPage??bt.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??bt.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??bt.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??bt.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?bt.detailedCodeContext:bt.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??bt.localSearchSort),t}var bt,TR=y(()=>{"use strict";bt={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function kR(e){return JSON.stringify(e)}function zd(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${kR(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${kR(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...zd(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=zd(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 OR(e){return["rule:",...zd(e,1)].join(`
|
|
49
|
+
`)}var vR=y(()=>{"use strict"});function AR(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function LR(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return AR(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),AR(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=OR(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 jn(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return LR(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=LR(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 Qd=y(()=>{"use strict";vR()});var Ha=y(()=>{"use strict";xd()});function za(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(za):e.kind==="not"?za(e.predicate):[e]}function Bd(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 ut(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function $r(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function jd(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var bi=y(()=>{"use strict"});function _R(e,t,n){let r=e.where,o=r?za(r):[],i=r&&F_.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>P("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 M_(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 Ri(e,t={}){if(!e.where)return{ok:!1,diagnostics:[P("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=M_(e.where);if(n){let p=IR(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=Bd(e.from),g=e.params??{},b=typeof g.extension=="string"||typeof n.extension=="string"?{}:Aa($r(e.scope)),w=jd(e),S=ut(e.scope);return _R(e,{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...w?{limit:w}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=jn(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[P("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=IR(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:[P("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Bd(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Aa($r(e.scope)),u=jd(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return _R(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...ut(e.scope)?{path:ut(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 IR(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(P("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(P("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var F_,Ud=y(()=>{"use strict";Qd();yt();Ha();bi();F_=new Set(["text","regex","structural","field"])});function qr(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return $d.find(n=>n.id===`${t}.diff.${e.variant}`)}return $d.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function qd(e){return $d.find(t=>t.id===e)}function Wd(e){let t=D_(e.source,e.target);if(e.target==="diff"){let n=Ur(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return qr({sourceKind:t,target:"diff",variant:r})}return qr({sourceKind:t,target:e.target})}function FR(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function MR(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function D_(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var $d,DR=y(()=>{"use strict";Ga();$d=[{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.artifacts",target:"artifacts",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localBinaryInspect",operation:"inspectArtifact",exact:!0}],rowKind:"record",recordType:"artifact",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeArtifacts"]},{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 N_(e,t){return e.id??t}function Vd(e,t,n,r,o,i=!1){let s=N_(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>Vd(e,d,`${n}.of[${p}]`,r,o,i)),l=G_(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(P("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=Vd(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=PR(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(P(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&NR(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:H_(e.target),exact:a.exact}),a.route}function G_(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 H_(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"artifacts":return"inspectArtifact";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function NR(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Kd(e,t){if(!t)return;let n=MR(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Qa(e,t,n){if(!t)return!1;for(let r of FR(t,n))NR(e.backendCalls,r);return!0}function z_(e,t){return GR(e,t,"files")}function GR(e,t,n,r=qr({sourceKind:"materialized",target:n})){let o=qr({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Kd(e,o),Kd(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}`)),Qa(e,o,t),Qa(e,r,void 0),!0}function Ba(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Ba):e.kind==="not"?Ba(e.predicate):!1:!1}function Q_(e){return e.target==="code"?qd(Ba(e.where)?"local.code.structural":"local.code.textRegex"):qr({sourceKind:"materialized",target:e.target})}function B_(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?qd(Ba(e.where)?"local.code.structural":"local.code.textRegex")??Wd({source:t,target:e.target,params:e.params}):Wd({source:t,target:e.target,params:e.params})}function Yd(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Yd(n),0):e.kind==="not"?1+Yd(e.predicate):1:0}function HR(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=B_(e,o);if(Kd(n,s),e.where)Vd(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&GR(n,o,e.target,Q_(e));else if(e.target==="diff"){let m=Ur(e.params);m.kind==="prPatch"||m.kind==="directFile"?Qa(n,s,o)||n.diagnostics.push(P("unsupportedTarget",`No transformer registered for target:"diff" lane "${m.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(P("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 m=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(m?g&&z_(n,o):Qa(n,s,o))&&(!m||g)&&n.diagnostics.push(P("unsupportedTarget",m?'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(P("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(...U_(e,n.nodes)),n.diagnostics.push(...j_(e)),n.diagnostics.push(...xR(e));let a=$_(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??bt.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(P("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=Yd(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(P("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let p={input:t,normalized:e,defaults:ER(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},f=!n.nodes.some(m=>m.route==="UNSUPPORTED")&&!n.diagnostics.some(m=>m.severity==="error"&&m.code!=="planTruncated");return{plan:p,executable:f}}function zR(e){return e.kind==="not"&&e.predicate.kind==="not"?zR(e.predicate.predicate):e}function j_(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Yb[e.target]:void 0;if(n)return n.includes(t)?[]:[P("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[P("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 U_(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=zR(e.where),r=Ri({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function $_(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(P("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(P("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 QR=y(()=>{"use strict";CR();Ga();wR();yt();TR();Ud();DR();zr()});function ja(e){let t=W_(e),n=K_(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 W_(e){return!e.executable||e.diagnostics.some(t=>q_.has(t.code))?"unsupported":e.approximate||V_(e.diagnostics)?"candidate":fR(e.diagnostics)||BR(e)?"partial":"proof"}function V_(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function BR(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function K_(e){return!e.executable||BR(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function jR(e){return e.some(t=>!t.exact)}function Xd(e,t,n,r,o){return ja({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var q_,UR=y(()=>{"use strict";yt();q_=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function Jt(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 Ua=y(()=>{"use strict"});function Jd(e){return Jt(e)}function Y_(e){if(e)return Jt({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 $a(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;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}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:Zd(Y_(e.pagination),n.length)}}function Zd(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 qa(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:Jd(e.pagination)}}function $R(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:Jd(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=J_(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:Jd(e.pagination)}}function J_(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=X_[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function qR(e,t,n,r="compact"){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 X_,ep=y(()=>{"use strict";Ua();X_={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import Ka from"node:path";import Z_ from"node:fs";function eI(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.")}function Xa(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 nI(e){return tI.test(e)}function KR(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function Ja(e,t,n){if(n){e.langType=n;return}let r=Sd($r(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=KR(e.include,r.include))}function rI(e){return Pd($r(e))}function WR(e){let t=Ya(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function Za(e){return!!(e?.include?.length||e?.exclude?.length)}function rp(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(WR).filter(i=>!!i);n.length>0&&!e.names&&(e.names=KR(e.names,n));let r=(t?.include??[]).filter(i=>!WR(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=rI(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function oI(e,t){if(Za(t.scope)){op(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function op(e){e.limit=tp,e.itemsPerPage=tp}async function Pi(e){let t=e.from,n=eI(e),r=ut(e.scope),o=r?Ka.join(n,r):n;if(!Z_.existsSync(o))return{results:[],diagnostics:[P("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 cI(e,t,o);case"structure":return SI(e,t,o);case"content":return PI(e,t,o);default:return XR(e,t,o)}}function iI(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?JR(e.predicate):!1}function sI(e){return e.kind==="text"||e.kind==="regex"}function YR(e){return e?.kind==="not"&&sI(e.predicate)}async function XR(e,t,n){let r=e.where;if(iI(r))return bI(e,t,n,r);if(e.view==="discovery"&&YR(r))return fI(e,t,n,r);let o=jn(r);if(o.unsupported)return{results:[],diagnostics:[P(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...Xa(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...oS(e)};Ja(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 Nt(s),c=$a(a,t),l=Wr(a,"localSearchCode"),u=aI(a);if(u.length>0){let d=u.reduce((f,m)=>f+(m.total??0),0),p=u.reduce((f,m)=>f+m.shown,0);l.push(P("matchTruncated",`${u.length} file(s) have more matches (showed ${p} 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(P("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&&nI(i.keywords)&&l.push(P("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:[Vr("localSearchCode",t,r)]}}function aI(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}async function cI(e,t,n){let r=e.where;if(YR(r))return pI(e,t,n,r);if(r&&JR(r))return uI(e,t,n,r);if(r&&nS(r)){let l=await XR({...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};rp(o,e.scope),oI(o,e),lI(o,e);let i=[];r&&rS(r,o,i);let s=await Dr(o),a=sp(s,e,n);return{...qa(a,t),diagnostics:[...i,...Wr(a,"localFindFiles")],provenance:[Vr("localFindFiles",t,r)]}}function lI(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function JR(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function uI(e,t,n,r){let o=[],i=[],a=[...(await Wa(e,r,t,n,o,i)).values()].sort(dI(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(P("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function dI(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 Wa(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Wa(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:mI(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Wa(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,ip(a.get(l),u));return a}case"not":{let s=await eS(e,n,r,o),a=await Wa(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return tS(e,t,n,r,o,i)}}async function pI(e,t,n,r){let o=await Nt(ZR(e,n,r.predicate)),i=Wr(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[Vr("localSearchCode",t,r)]}}async function fI(e,t,n,r){let o=await Nt(ZR(e,n,r.predicate));return{...$a(o,t),diagnostics:Wr(o,"localSearchCode"),provenance:[Vr("localSearchCode",t,r)]}}function ZR(e,t,n){let o=jn(n).match,i={path:t,filesWithoutMatch:!0,...Xa(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...oS(e)};return Ja(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}function mI(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,ip(o,i))}return n}function gI(e,t){return new Set([...e].filter(n=>t.has(n)))}function ip(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}async function hI(e,t,n){return new Set((await eS(e,e.from,t,n)).keys())}async function eS(e,t,n,r){let o={path:n,entryType:"f"};rp(o,e.scope),Za(e.scope)&&(op(o),o.page=1);let i=await Dr(o),s=sp(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),np(qa({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function yI(e,t,n,r,o){return new Set((await tS(e,t,e.from,n,r,o)).keys())}async function tS(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};rp(u,e.scope),rS(t,u,i),Za(e.scope)&&(op(u),u.page=1);let d=await Dr(u),p=sp(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),np(qa(p,n).results)}let s=jn(t);if(s.unsupported)return i.push(P(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:tp,...Xa(e.scope)};Ja(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 Nt(c);return o.push({backend:"localSearchCode",source:e.from}),np((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function np(e){let t=new Map;for(let n of e)t.set(n.path,ip(t.get(n.path),n));return t}async function bI(e,t,n,r){let o=[],i=[],s=await Va(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(P("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function Va(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Va(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:gI(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Va(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 hI(e,r,o),a=await Va(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await yI(e,t,r,o,i),rows:[]};default:{let s=await RI(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function RI(e,t,n,r,o,i){let s=jn(t);if(s.unsupported)return i.push(P(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...Xa(e.scope)};Ja(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 Nt(c);return o.push({backend:"localSearchCode",source:n}),$a(l,n).results}async function SI(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 _a(r);return{...$R(o,t),diagnostics:Wr(o,"localViewStructure"),provenance:[Vr("localViewStructure",t,void 0)]}}async function PI(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=TI(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 wa(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...qR(a,t,n,c),diagnostics:Wr(a,"localGetFileContent"),provenance:[Vr("localGetFileContent",t,void 0)]}}function sp(e,t,n){if(!Za(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>CI(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 CI(e,t,n){let r=Ya(xI(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>VR(r,i))?!1:!(n?.exclude??[]).some(i=>VR(r,i))}function xI(e,t){let n=Ka.relative(t,e);return!n||n.startsWith("..")||Ka.isAbsolute(n)?e:n}function Ya(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function VR(e,t){let n=Ya(t),r=Ya(e),o=wI(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Ka.posix.basename(r))}function wI(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+=EI(r)}return new RegExp(`${t}$`)}function EI(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function TI(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 nS(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?nS(e.predicate):!1}function rS(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(P("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(Si(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(Si(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(Si(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(P("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(Si(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(Si(i));break}r&&n.push(P("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function Si(e){return P("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function oS(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}function Wr(e,t){let n=[];e.status==="error"?n.push(P("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(P(kI(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function kI(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 Vr(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var tp,tI,ap=y(()=>{"use strict";Se();gi();pi();yi();ai();Qd();ep();yt();Ha();bi();tp=1e4;tI=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});import{completeMetadata as OI}from"@octocodeai/octocode-core";function Ci(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function I4(e){return vI.has(e)}var V,Ke,Un,vI,xi=y(()=>{"use strict";V=OI.toolNames,Ke=V.LSP_GET_SEMANTIC_CONTENT,Un="oqlSearch";vI=new Set([V.LOCAL_RIPGREP,V.LOCAL_FETCH_CONTENT,V.LOCAL_FIND_FILES,V.LOCAL_VIEW_STRUCTURE,V.LOCAL_BINARY_INSPECT,Ke])});function $n(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function cp(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 iS,Kr=y(()=>{"use strict";xi();iS=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{z as ne}from"zod";import{NpmPackageQuerySchema as sS}from"@octocodeai/octocode-core/schemas";var aS,ec,tc,j4,nc=y(()=>{"use strict";qe();lt();Je();Tt();aS={page:pe,mode:ne.enum(["lean","full"]).optional()},ec=ge(sS,aS),tc=le(Pe(sS,aS,{strict:!0}),{maxQueries:5}),j4=ne.object({results:ne.array(ne.looseObject({id:ne.string(),data:ne.looseObject({packages:ne.array(ne.object({name:ne.string(),version:ne.string().optional(),description:ne.string().optional(),license:ne.string().optional(),downloads:ne.number().optional(),repository:ne.string().optional(),repositoryDirectory:ne.string().optional(),repositoryId:ne.string().optional(),next:ne.record(ne.string(),ne.unknown()).optional()}).passthrough()).optional(),repositories:ne.record(ne.string(),ne.object({repository:ne.string(),owner:ne.string(),repo:ne.string(),repositoryDirectory:ne.string().optional(),next:ne.record(ne.string(),ne.unknown())}).passthrough()).optional(),pagination:Oe.optional()}).optional(),status:ne.string().optional()})).optional()}).extend(We)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as uS}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as AI}from"@octocodeai/octocode-core/schemas/outputs";var LI,_I,II,dS,FI,wi,MI,Ei,cS,DI,NI,rc,oc,GI,HI,pS,Yr,zI,QI,BI,fS,jI,UI,$I,qI,WI,VI,KI,lS,YI,Ti=y(()=>{"use strict";Se();qe();lt();Kr();Tt();LI=H(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),_I=H(0,1e5).optional(),II=["structured","compact"],dS={type:R.enum(iS).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:LI.optional(),orderHint:_I,depth:H(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:pe,itemsPerPage:H(1,100).optional(),contextLines:H(0,100).optional(),format:R.enum(II).optional().default("structured")},FI=Pe(uS,dS),wi=ge(uS,dS),MI=wi,Ei=le(FI,{maxQueries:5}),cS=R.object({line:R.number(),character:R.number()}),DI=R.object({start:cS,end:cS}),NI=R.object({startLine:R.number(),endLine:R.number()}),rc=R.object({uri:R.string(),content:R.string().optional(),displayRange:NI.optional(),isDefinition:R.boolean().optional()}),oc=R.string(),GI=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),HI=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),pS=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Yr=R.object({category:pS,reason:R.string()}),zI=Oe,QI=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),BI=R.string(),fS=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),jI=R.string(),UI=R.object({direction:R.enum(["incoming","outgoing"]),item:fS,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),$I=R.string(),qI=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),WI=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),VI=R.string(),KI=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([rc,oc]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([rc,oc]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([rc,oc]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([rc,oc])).optional(),byFile:R.array(R.union([WI,VI])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:Yr.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([fS,jI]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([UI,$I])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:qI,empty:Yr.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:DI.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([QI,BI])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:Yr.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:Yr.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:Yr.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:Yr.optional()}),R.object({kind:R.literal("empty"),category:pS,reason:R.string()})]),lS=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:GI.optional(),lsp:HI.optional(),payload:KI,pagination:zI.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),YI=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:lS}),R.object({id:R.string().min(1),status:R.literal("error"),data:AI}),R.object({id:R.string().min(1),data:lS})]))})});import{z as lp}from"zod";function sc(e){return ZI.find(t=>t.name===e)}function ic(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===V.PACKAGE_SEARCH?"Package":"Other"}function yY(e){return[...e].sort((t,n)=>{let r=mS.indexOf(ic(t)),o=mS.indexOf(ic(n));if(r!==o)return r-o;let i=gS.get(t)??Number.MAX_SAFE_INTEGER,s=gS.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function bY(e){let t=sc(e);if(!t)return"{}";try{return JSON.stringify(lp.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(lp.toJSONSchema(t.schema,{io:"input"}),null,2)}}function RY(e){return JSON.stringify(e??{},null,2)}function SY(e){let t=ic(e),n=[...JI];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function PY(){return RS.map(e=>({...e}))}function CY(){return JSON.stringify(Object.fromEntries(RS.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function xY(e,t){return t?.tools?.[e]?.description??e}function SS(e){let t=sc(e);if(!t)return[];let n=lp.toJSONSchema(t.schema,{io:"input"});if(!Xr(n))return[];let r=Rn(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!mp.has(i)&&!fp(r[i])):[]);return pp(r,o)}function hS(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function eF(e){let t=nF(e);if(t.length>0)return t.map(r=>({...r,command:hS(e,r.query)}));let n=tF(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:hS(e,n)}]}function wY(e){return eF(e)[0]?.query??{}}function tF(e){if(!sc(e))return{};let t=SS(e),n=t.filter(i=>!i.name.includes(".")),r=uF(n),o={};for(let i of r)o[i.name]=mF(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Ke&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function nF(e){return e===Un?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===V.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}}]:e===V.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===V.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===V.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===V.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===V.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:e===V.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"src/index.ts",startLine:1,endLine:40,minify:"none"}},{label:"matched slice",query:{path:"src/index.ts",matchString:"registerTool",contextLines:8,minify:"standard"}}]:e===V.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:".",names:["*.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/**",entryType:"f",itemsPerPage:20}}]:e===V.LOCAL_BINARY_INSPECT?[{label:"archive listing",query:{path:"archive.zip",mode:"list",entriesPerPage:50}},{label:"binary strings",query:{path:"dist/app.node",mode:"strings",minLength:8,charLength:2e3}}]:e===Ke?[{label:"semantic definition",query:{uri:"/path/to/file.ts",type:"definition",symbolName:"myFunction",lineHint:42}},{label:"symbol outline",query:{uri:"/path/to/file.ts",type:"documentSymbols"}}]:[]}function EY(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Gt("Tool input must be valid JSON.")}return rF(e,r,n)}function rF(e,t,n={}){let r=iF(e,t,n),o=sc(e);if(!o)throw new Gt(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Gt("Tool input does not match the expected schema.",oF(i.error));return i.data}function oF(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function iF(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(Rn(t)&&Array.isArray(t.queries))r=t.queries;else if(Rn(t))r=[t];else throw new Gt('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Gt("At least one query is required.");let o=Rn(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>sF(e,a,cF(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function sF(e,t,n,r){let o={...n},i=ic(e),s=r.sourceLabel??"direct tool execution",a=aF(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 aF(e,t){return`Execute ${e} via ${t}`}function cF(e,t,n,r={}){if(!Rn(t))throw new Gt("Tool input must be a JSON object or an array of objects.");let o=new Set([...SS(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...mp]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}if(s.length>0&&o.size>0&&(r.onUnknownFields?.(s,n),r.rejectUnknownFields===!0))throw new Gt(`Unknown field(s): ${s.join(", ")}`,[`Remove unknown field(s) from query ${n+1}: ${s.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`]);return i}function lF(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 up(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Xr(e.items)?e.items:void 0;return`array<${n?up(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Xr).map(up).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 uF(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&&dF(i)).sort(pF),o=Math.max(yS,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=>!PS.has(i.name)).filter(i=>i.type!=="boolean").slice(0,yS)}function dF(e){return PS.has(e.name)||e.type==="boolean"?!1:fF(e)?dp.has(e.name):!0}function pF(e,t){let n=dp.get(e.name)??Number.MAX_SAFE_INTEGER,r=dp.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function fF(e){return e.constraints?.includes("default ")===!0}function pp(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&mp.has(o))continue;let s=Xr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:up(s),constraints:lF(s),description:typeof s.description=="string"?s.description:void 0}),Rn(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!fp(s.properties?.[u]):!1):[]);r.push(...pp(s.properties,l,a))}let c=s.type==="array"&&Xr(s.items)?s.items:void 0;if(c&&Rn(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!fp(c.properties?.[u]):!1):[]);r.push(...pp(c.properties,l,a))}}return r}function mF(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[bS(e,n)]}return bS(e,t)}function bS(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 Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xr(e){return Rn(e)}function fp(e){return Xr(e)&&"default"in e}var mS,gS,Gt,XI,mp,JI,RS,ZI,yS,dp,PS,gp=y(()=>{"use strict";xi();Kr();ea();ri();la();ii();ya();Sa();nc();ci();li();Nr();hi();Ti();si();Br();mS=["GitHub","Local Code","Package","Other"],gS=new Map([V.GITHUB_SEARCH_CODE,V.GITHUB_SEARCH_REPOSITORIES,V.GITHUB_SEARCH_PULL_REQUESTS,V.GITHUB_FETCH_CONTENT,V.GITHUB_VIEW_REPO_STRUCTURE,V.GITHUB_CLONE_REPO,V.LOCAL_RIPGREP,V.LOCAL_FIND_FILES,V.LOCAL_FETCH_CONTENT,V.LOCAL_VIEW_STRUCTURE,Ke,V.PACKAGE_SEARCH,...Ci()?[Un]:[]].map((e,t)=>[e,t])),Gt=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},XI=["id","mainResearchGoal","researchGoal","reasoning"],mp=new Set([...XI]),JI=["id","researchGoal","reasoning"],RS=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],ZI=[{name:V.GITHUB_SEARCH_CODE,schema:aa,inputSchema:ca},{name:V.GITHUB_FETCH_CONTENT,schema:kr,inputSchema:ta},{name:V.GITHUB_VIEW_REPO_STRUCTURE,schema:ba,inputSchema:Ra},{name:V.GITHUB_SEARCH_REPOSITORIES,schema:ga,inputSchema:ha},{name:V.GITHUB_SEARCH_PULL_REQUESTS,schema:Or,inputSchema:ma},{name:V.PACKAGE_SEARCH,schema:ec,inputSchema:tc},{name:V.GITHUB_CLONE_REPO,schema:ni,inputSchema:Zs},{name:V.LOCAL_RIPGREP,schema:hn,inputSchema:ka},{name:V.LOCAL_VIEW_STRUCTURE,schema:Hr,inputSchema:La},{name:V.LOCAL_FIND_FILES,schema:Fr,inputSchema:Ta},{name:V.LOCAL_FETCH_CONTENT,schema:Ir,inputSchema:Ea},{name:Ke,schema:wi,inputSchema:Ei},{name:V.LOCAL_BINARY_INSPECT,schema:vr,inputSchema:Pa},...Ci()?[{name:Un,schema:Ma,inputSchema:Qn}]:[]];yS=4,dp=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]]),PS=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});import{existsSync as CS}from"fs";import{delimiter as gF,dirname as hF,join as xS}from"path";function wS(){return process.platform==="win32"?"npm.cmd":"npm"}function yF(){let e=hF(process.execPath);return xS(e,wS())}function bF(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function RF(){let e=(process.env.PATH??"").split(gF).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...bF()])]}function ES(){let e=yF();if(CS(e))return{command:process.execPath,argsPrefix:[e]};let t=wS();for(let n of RF()){let r=xS(n,t);if(CS(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function AY(e=1e4){let t=ES();return Fh(t.command,[...t.argsPrefix,"--version"],e)}async function ki(e,t,n={}){if(!SF.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=qs(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=ES(),c=await Yt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:PF});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var SF,PF,hp=y(()=>{"use strict";Tr();SF=["view","search","ping","config","whoami"],PF=[...ei,...Ih]});function vi(e){try{return new URL(e).host||e}catch{return e}}function TS(e,t=Date.now()){let n=Jr.get(vi(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Oi)throw new yp(vi(e),Oi-r);n.state="half-open"}}function Rp(e){let t=Jr.get(vi(e));t&&(t.failures=0,t.state="closed")}function kS(e,t=Date.now()){let n=vi(e),r=Jr.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=bp&&(r.state="open",r.openedAt=t)),Jr.set(n,r)}function IY(){Jr.clear(),bp=5,Oi=3e4}function FY(e){typeof e.failureThreshold=="number"&&(bp=e.failureThreshold),typeof e.cooldownMs=="number"&&(Oi=e.cooldownMs)}function OS(e,t=Date.now()){let n=Jr.get(vi(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Oi:!1}var _Y,Jr,bp,Oi,yp,ac=y(()=>{"use strict";_Y=5,Jr=new Map,bp=5,Oi=3e4;yp=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});function vS(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function xF(e,t,n,r){e&&un({limit_type:"primary",retry_after_seconds:vS(r),api_method:t,api_url:n,provider:e})}function wF(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(so.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&jm(r),e.status===429&&xF(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function EF(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=vS(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Sn(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=CF,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let b=e.includes("?")?"&":"?";d=`${e}${b}version=${encodeURIComponent(An)}`}let p={"User-Agent":`Octocode-MCP/${An}`,...i},f=globalThis.fetch;if(!f)throw new Error(so.FETCH_NOT_AVAILABLE.message);TS(d);let m,g=n+1;for(let b=1;b<=g;b++){if(c?.aborted)throw new Error("Request aborted");try{let w=await f(d,{method:s,headers:p,signal:c});if(!w.ok)throw wF(w,s,d,u,l);if(w.status===204)return Rp(d),null;let S=await w.json();return Rp(d),S}catch(w){let S=w;if(c?.aborted||w instanceof Error&&w.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw w;if(m=w instanceof Error?w:new Error(String(w)),b===g)break;let T=EF(b,r,o,S);await new Promise(A=>setTimeout(A,T))}}throw kS(d),new Error(so.FETCH_FAILED_AFTER_RETRIES.message(g,m?.message||""))}var CF,Sp=y(()=>{"use strict";ps();Pt();vo();ac();CF=6e4});import{z as L}from"zod";var cc,TF,AS,LS,Pp=y(()=>{"use strict";cc=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()}),TF=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()}),AS=L.looseObject({objects:L.array(TF),total:L.union([L.number(),L.string()]).optional()}),LS=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});async function Cp(){if(Ai)return Ai;try{let e=await ki("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 Ai=t,t}}catch{}return Ai=lc,lc}function KY(){Ai=null}async function YY(){try{let e=await Cp(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}function qn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function dt(e){return e===void 0?0:j(e)}async function NS(e){try{let t=`${OF}/${encodeURIComponent(e)}`,n=await Sn(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:dt(n)}}catch{return{rawResponseChars:0}}}function uc(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function GS(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function vF(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function AF(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function _S(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 IS(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 LF(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function xp(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=qn(e.repository):(e.repository.url&&(r=qn(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:LF(e),...o?{repositoryDirectory:o}:{},..._S(e.exports)?{exports:_S(e.exports)}:{},...IS(e.bin,e.name)?{bin:IS(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 _F(e){return typeof e.links?.repository=="string"?qn(e.links.repository):typeof e.repository=="string"?qn(e.repository):typeof e.repository?.url=="string"?qn(e.repository.url):null}function IF(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:_F(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 HS(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function zS(e){try{let t=await Cp(),n=HS(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Sn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=dt(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Sn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:dt(i)}}catch{return{rawResponseChars:0}}}async function wp(e,t,n){let[r,o]=await Promise.all([NS(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):zS(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 dc(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function FF(e,t){try{let n=await ki("view",[e,"--json"],{timeout:kF});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,...dc(c)?{}:{errorDetail:c},rawResponseChars:dt(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=dt(o),s=cc.safeParse(o);return s.success?{pkg:xp(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,...dc(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function MF(e,t){try{let n=await Cp(),r=HS(e),o=`${n}/${r}/latest`,i;try{i=await Sn(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=dt(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=cc.safeParse(i);return a.success?{pkg:xp(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,...dc(r)?{}:{errorDetail:r},rawResponseChars:0}}}function DF(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function QS(e,t){let n=0,r;for(let o of DF(e)){let i;try{i=await Sn(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);dc(l)||(r=l);continue}if(n+=dt(i),!i||typeof i!="object")continue;let s=cc.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:xp(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Ep(e,t=!1){let[n,r]=await Promise.allSettled([FF(e,t),MF(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?wp(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function NF(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Ep(e,t);if(!r){if(o){let s=GS(o);if(s&&n){let a=await QS(e,t);if(a.pkg){let c=await wp(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function GF(e,t,n,r=0){let o=Math.max(t+r,t),i=await ki("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:dt(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=dt(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((m,g)=>{let b=m?.score?.final??0;return(g?.score?.final??0)-b}).slice(r,r+t),d=await Promise.all(u.map(async m=>{if(!m||typeof m!="object")return null;let g=m;if(!g.name)return null;if(n){let b=await Ep(g.name,!0);if(b.pkg)return b}return{pkg:IF(g),rawResponseChars:0}})),p=d.map(m=>m?.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+(g?.rawResponseChars??0),0);return{packages:p,totalFound:a.length,rawResponseChars:c+f}}async function HF(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${lc}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Sn(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(m){return{error:`NPM registry search failed: ${m instanceof Error?m.message:String(m)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=dt(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=AS.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((m,g)=>{let b=m.score?.final??0;return(g.score?.final??0)-b}).map(m=>m.package).filter(m=>typeof m.name=="string"&&m.name.length>0).slice(0,t),d=await Promise.all(u.map(async m=>{if(n){let g=await Ep(m.name,!0);if(g.pkg)return g}return{pkg:{name:m.name,npmUrl:(m.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(m.name)}`,repoUrl:m.links?.repository&&typeof m.links.repository=="string"?qn(m.links.repository):null,version:m.version??"unknown",source:"registry",...m.description?{description:m.description}:{},...m.links?.homepage?{homepage:m.links.homepage}:{}},rawResponseChars:0}})),p=d.map(m=>m.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+g.rawResponseChars,0);return{packages:p,totalFound:AF(c.data.total,p.length),rawResponseChars:a+f}}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 FS(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 Sn(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:dt(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:dt(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"?qn(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:dt(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function MS(e,t,n,r=0){try{let o=await GF(e,t,n,r);if(!("error"in o))return o}catch{}return HF(e,t,n,r)}async function DS(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}):NS(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):zS(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function BS(e,t,n,r=0){let o=Ue("npm-search",{name:e,limit:t,metadata:n,from:r});return $e(o,async()=>{if(OS(lc)){if(r===0&&t===1&&uc(e)){let u=await QS(e,n);if(u.pkg){let d=await wp(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await FS(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&&uc(e)){let l=await NF(e,n,t===1);if("error"in l){if(!GS(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await MS(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return DS(s);let a=vF(e);if(a!==e){let l=await MS(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return DS(l)}let c=await FS(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 zF(e){try{let t=await ki("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=LS.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 lc,kF,Ai,OF,Tp=y(()=>{"use strict";hp();Sp();qt();ac();Pp();ce();lc="https://registry.npmjs.org",kF=3e3,Ai=null;OF="https://api.npmjs.org/downloads/point/last-week"});async function jS(e){let t=uc(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return BS(e.name,n,!0,r)}var kp=y(()=>{"use strict";Tp()});function QF(e){return"error"in e}function pc(e){return"npmUrl"in e}function BF(e){return pc(e)&&e.path?e.path:e.name}function jF(e){return pc(e)?e.repoUrl:e.repository}function UF(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function $F(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 US(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 $S(e,t){let n=US(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function qF(e){let t=BF(e),n=$F(jF(e)),r={name:t};pc(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=UF(pc(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=$S(n,o);return i&&(r.next=i),r}function WF(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=US(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:$S(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...p}=i;return{...p,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function VF(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 qS(e){return ue(e.queries,async t=>{try{if(!t.packageName)return D("Package name is required for package search",t);let n=await jS({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(QF(n))return D(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(qF),i=o.length>0,s=r.length>1||n.totalFound>1,a=VF(t,n.totalFound,o.length,s),l={...WF(o),pagination:a};return He(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return D(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var Op=y(()=>{"use strict";kp();Be();Qe();Re()});import{safeReadFile as KF}from"@octocodeai/octocode-engine/lsp/validation";function Li(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function VS(e,t,n){if(t<=0)return e;let r=await KF(e.uri);if(!r)return e;let o=Qo(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(`
|
|
50
|
+
`);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function YF(e,t){return Promise.all(e.map(async n=>({...n,from:await VS(n.from,t,n.fromRanges)})))}async function XF(e,t){return Promise.all(e.map(async n=>({...n,to:await VS(n.to,t)})))}async function vp(e,t,n,r,o){if(n<=0||!e)return{calls:[],...WS};try{let i=await e.getIncomingCalls(t),s=o>0?await YF(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=Li(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),vp(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 Ap(e,t,n,r,o){if(n<=0||!e)return{calls:[],...WS};try{let i=await e.getOutgoingCalls(t),s=o>0?await XF(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=Li(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Ap(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 WS,Lp=y(()=>{"use strict";Pr();WS={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function ZF(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function KS(e,t){if(t===void 0||t==="progressIdle")return e;let n=ZF(e);if(!n||!JF.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 JF,YS=y(()=>{"use strict";JF=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as e0,stat as t0}from"node:fs/promises";import{SymbolResolver as n0,SymbolResolutionError as r0}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as fc}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function _p(e,t){let n=e.uri,r=tt({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await t0(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:fc.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:fc.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 e0(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:fc.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function XS(e,t){let n=await _p(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 n0({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:o0(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof r0)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:fc.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 o0(e){return{start:e,end:{line:e.line,character:e.character}}}var Ip=y(()=>{"use strict";Mt()});import Ht from"node:path";import{readFile as i0}from"node:fs/promises";import{fileURLToPath as s0}from"node:url";import{acquirePooledClient as gc,isLanguageServerAvailable as hc,unavailableHintFor as a0}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as c0}from"@octocodeai/octocode-engine/lsp/config";import{resolveImportAliasDefinitions as l0}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Dp}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function u0(e){return Fp||(Fp=new Set(M.getSupportedJsTsExtensions().map(t=>`.${t}`))),Fp.has(Ht.extname(e).toLowerCase())}function Wn(e,t){let n=c0(e),r=a0(n,void 0);throw new Me(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 p0(e,t){let n=e.startsWith("file://")?s0(e):e;return Ht.isAbsolute(n)?n:Ht.resolve(t,n)}function nP(){return[...M.getSupportedJsTsExtensions(),...d0]}function f0(){return nP().map(e=>`**/*.${e}`)}async function g0(e,t){let n=e.symbolName?.trim();if(n)try{return(await M.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:f0(),excludeDir:[...m0],maxSnippetChars:1})).files[0]?.path}catch{return}}async function h0(e,t){if(e.uri)return p0(e.uri,t);let n=await g0(e,t);if(n)return n;try{let o=M.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:nP(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function y0(e){return e instanceof Error?e.message:String(e)}function b0(e,t){if(!u0(e))return null;try{let n=M.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}async function Np(e){return ue(e.queries||[],async t=>Ze({toolName:Ke,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await F0(t);return P0(C0(t,n))}}),{toolName:Ke,minQueryTimeoutMs:3e4},e)}function P0(e){return q(e,j(e))}function C0(e,t){return e.format!=="compact"||!x0(t)?t:w0(t)}function x0(e){return Vn(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Vn(e.payload)}function w0(e){return{...e,format:"compact",payload:E0(e.payload)}}function E0(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(JS)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(k0)}:{locations:(e.locations??[]).map(JS)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:oP(e.root)}:{},direction:e.direction,calls:e.calls.map(O0),...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(T0)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function T0(e){if(!Vn(e))return String(e);let t=nt(e,"line"),n=nt(e,"character"),r=nt(e,"endLine"),o=en(e,"kind"),i=en(e,"name"),s=nt(e,"childCount"),a=en(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function JS(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${sP(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function k0(e){if(!Vn(e))return String(e);let t=en(e,"uri"),n=nt(e,"firstLine"),r=nt(e,"firstCharacter"),o=nt(e,"count"),i=iP(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 O0(e){if(!Vn(e))return String(e);let t=en(e,"direction"),n=oP(e.item),r=iP(e,"ranges").map(v0).join(","),o=nt(e,"rangeCount"),i=nt(e,"rangeSampleCount"),s=en(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${sP(s,180)}`:""].filter(Boolean).join(" ")}function oP(e){if(!Vn(e))return String(e);let t=en(e,"name"),n=en(e,"kind"),r=en(e,"uri"),o=nt(e,"line"),i=nt(e,"endLine"),s=nt(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function v0(e){return Vn(e)?`${nt(e,"line")}:${nt(e,"character")}`:String(e)}function Vn(e){return typeof e=="object"&&e!==null}function en(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function nt(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function iP(e,t){let n=e[t];return Array.isArray(n)?n:[]}function sP(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function I0(e,t,n){if(typeof e.openDocument=="function")try{let r=Ht.extname(t.uri).slice(1),o=ZS.includes(r)?ZS:[r],i=await Nt({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:L0,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=Ht.isAbsolute(a)?a:Ht.join(n,a);if(Ht.resolve(c)!==Ht.resolve(t.uri))try{let l=await i0(c,"utf-8");if(l.length>_0)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function F0(e){if(e.type==="documentSymbols")return D0(e);if(e.type==="workspaceSymbol")return z0(e);if(e.type==="diagnostic")return j0(e);let t=await XS(e,Ke);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return Z0(e,a)}let n=e.workspaceRoot??await Dp(t.value.uri);await hc(t.value.uri,n)||Wn(t.value.uri,e.type);let o=await gc(n,t.value.uri);o||Wn(t.value.uri,e.type),A0.has(e.type)&&await I0(o,t.value,n);let i=o.getReadiness?.(),s=await M0(e,t.value,o);return KS(s,i)}async function M0(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?Mp(e,t,"definition","definitionProvider",await l0({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):Zt(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?Mp(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):Zt(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?Mp(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):Zt(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?N0(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):Zt(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?G0(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):Zt(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?H0(e,t,n):Zt(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?B0(e,t,n):Zt(e.type,t,"typeHierarchyProvider unsupported",!0)}}async function D0(e){let t=await _p(e,Ke);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Dp(t.value.uri),r=await hc(t.value.uri,n),o=r?await gc(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=b0(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let b=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(b)?b:[],a="lsp"}else{let b=Ng(t.value.content,t.value.uri);b&&(s=b,a="markdown")}let l=a!==void 0;!l&&!r&&Wn(t.value.uri,"documentSymbols");let u=q0(s),d=K0(s),{pageItems:p,pagination:f}=Kn(u,e.page??1,e.itemsPerPage??yc),m=Y0(u,b=>b.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:p.length,topLevelSymbols:d,kinds:m},payload:{kind:"documentSymbols",symbols:p,...g?{empty:g}:{}},pagination:f}}function Mp(e,t,n,r,o){let i=o.length>0,s=o.map(cp),{pageItems:a,pagination:c}=Kn(s,e.page??1,e.itemsPerPage??rP);return{type:e.type,uri:t.uri,resolvedSymbol:$n(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 N0(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?eM(r):void 0,i=o??r.map(cp),{pageItems:s,pagination:a}=Kn(i,e.page??1,e.itemsPerPage??rP),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:$n(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 G0(e,t,n){let r=tM(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:$n(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function H0(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Zt(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 vp(n,o,i,new Set([Li(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Ap(n,o,i,new Set([Li(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)),p=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],f=p.map(S=>S.direction==="incoming"?X0(S,e.contextLines??0):J0(S,e.contextLines??0)),{pageItems:m,pagination:g}=Kn(f,e.page??1,e.itemsPerPage??R0),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",w=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:$n(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Gp(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:w,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function z0(e){let t=e.symbolName??"",n=Ht.resolve(e.workspaceRoot??process.cwd()),r=await h0(e,n);await hc(r,n)||Wn(r,"workspaceSymbol");let i=await gc(n,r);if(i||Wn(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{Ht.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: ${y0(u)}`}}}let a=Q0(s),{pageItems:c,pagination:l}=Kn(a,e.page??1,e.itemsPerPage??yc);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 Q0(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:mc(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function B0(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Zt(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}=Kn(s,e.page??1,e.itemsPerPage??yc);return{type:e.type,uri:t.uri,resolvedSymbol:$n(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}}async function j0(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Dp(t):process.cwd());await hc(t,n)||Wn(t,"diagnostic");let o=await gc(n,t);if(o||Wn(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=U0(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Kn(s,e.page??1,e.itemsPerPage??yc);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 U0(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>$0(r))}return[]}function $0(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}:{}}]:[]}function Kn(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function q0(e){let t=[];for(let n of e)aP(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function aP(e,t,n){if(!e||typeof e!="object")return;let r=e,o=V0(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:mc(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)&&W0.has(mc(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)aP(s,t,i)}}function V0(e){if(eP(e.range))return e.range;let t=e.location;return t&&eP(t.range)?t.range:void 0}function eP(e){if(!e||typeof e!="object")return!1;let t=e;return tP(t.start)&&tP(t.end)}function tP(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function K0(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Y0(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function X0(e,t){let n=cP(e.fromRanges);return{direction:"incoming",item:Gp(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...lP(e.from,t)}}function J0(e,t){let n=cP(e.fromRanges);return{direction:"outgoing",item:Gp(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...lP(e.to,t)}}function Gp(e){return{name:e.name,kind:mc(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 cP(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>=S0))break}return n}function lP(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function mc(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function uP(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 Z0(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:uP(e.type,t),reason:t}}}function Zt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:$n(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:uP(e,n),reason:n}}}function eM(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 tM(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=>nM(r)).join(`
|
|
51
|
+
`).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 nM(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 Fp,d0,m0,yc,rP,R0,S0,A0,L0,_0,ZS,W0,bc=y(()=>{"use strict";gi();Be();ce();Kt();co();wn();Lp();Kr();YS();Ip();we();As();d0=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];m0=[".git","node_modules","dist","out","coverage","target"];yc=40,rP=40,R0=10,S0=8;A0=new Set(["references","callers","callees","callHierarchy","implementation"]),L0=12,_0=512*1024,ZS=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];W0=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});var Hp,zp=y(()=>{"use strict";Re();Hp={hasTool(e){return Hl(e)},getDescription(e){return Nl[e]??""},getToolName(e){return v[e]??String(e)}}});function rM(e,t){return t.getToolName(e)}function Rt(e,t,n){let r=rM(t,e);return{...n,name:r,description:Qp(r,e)}}function oM(e=Hp){let t=Rt(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:aa,inputSchema:ca,executionFn:Py,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=Rt(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:kr,inputSchema:ta,executionFn:by,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=Rt(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:ba,inputSchema:Ra,executionFn:zy,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=Rt(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ga,inputSchema:ha,executionFn:Ny,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=Rt(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Or,inputSchema:ma,executionFn:Ly,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=Rt(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ec,inputSchema:tc,executionFn:qS,security:"remote",requiresServerRuntime:!0}}),a=Rt(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:ni,inputSchema:Zs,executionFn:Xh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=Rt(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:hn,inputSchema:ka,executionFn:Hb,security:"basic"}}),l=Rt(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Hr,inputSchema:La,executionFn:Vb,security:"basic"}}),u=Rt(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Fr,inputSchema:Ta,executionFn:bb,security:"basic"}}),d=Rt(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Ir,inputSchema:Ea,executionFn:mb,security:"basic"}}),p={name:Ke,description:Qp(Ke,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:wi,inputSchema:Ei,executionFn:Np,security:"basic",requiresServerRuntime:!0}},f=Rt(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:vr,inputSchema:Pa,executionFn:sb,security:"basic"}}),m={name:Un,description:Qp(Un,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ma,inputSchema:Qn,executionFn:pP,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},g=[t,n,r,o,i,s,a,c,l,u,d,p,f,...Ci()?[m]:[]];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:p,LOCAL_BINARY_INSPECT:f,OQL_SEARCH:m,ALL_TOOLS:g}}var Qp,Ye,f5,m5,g5,h5,y5,b5,R5,S5,P5,C5,x5,w5,E5,T5,dP,Bp=y(()=>{"use strict";ea();ri();la();ii();ya();Sa();nc();ci();li();Nr();hi();Ti();si();Br();cd();Nu();Hu();Qu();Ku();Ju();Zu();Op();dd();pd();wd();_d();bc();jp();Kr();xi();zp();Qp=(e,t=Hp)=>t.getDescription(e);Ye=oM(),f5=Ye.GITHUB_SEARCH_CODE,m5=Ye.GITHUB_FETCH_CONTENT,g5=Ye.GITHUB_VIEW_REPO_STRUCTURE,h5=Ye.GITHUB_SEARCH_REPOSITORIES,y5=Ye.GITHUB_SEARCH_PULL_REQUESTS,b5=Ye.PACKAGE_SEARCH,R5=Ye.GITHUB_CLONE_REPO,S5=Ye.LOCAL_RIPGREP,P5=Ye.LOCAL_VIEW_STRUCTURE,C5=Ye.LOCAL_FIND_FILES,x5=Ye.LOCAL_FETCH_CONTENT,w5=Ye.LSP_GET_SEMANTIC_CONTENT,E5=Ye.LOCAL_BINARY_INSPECT,T5=Ye.OQL_SEARCH,dP=Ye.ALL_TOOLS});import{ContentSanitizer as iM}from"@octocodeai/octocode-engine/security";function $p(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:Et(t.structuredContent)}}catch{}return aM(t)?cM(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}=iM.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function aM(e){return Wi()==="mcp"&&process.env[sM]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function cM(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:lM(e.structuredContent)},...t]}}function lM(e){let t=["structuredContent available"];if(Up(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=uM(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Up(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function uM(e){let t=0,n=0;for(let r of e)Up(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Up(e){return typeof e=="object"&&e!==null}function qp(e,t){let n=pM(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
52
|
+
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:dM,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return $p(r)}catch{return r}}function pM(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:fM(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 fM(e){try{return JSON.stringify(e)}catch{return}}var sM,dM,Wp=y(()=>{"use strict";xr();ot();sM="OCTOCODE_MCP_FULL_TEXT";dM="TOOL_CALLBACK_EXCEPTION"});function gM(e){let t=e;return n=>t(n)}function hM(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:gM(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function bM(e){return yM.find(t=>t.name===e)}async function Vp(e,t){let n=bM(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=RM(n,t);return await SM(n),PM(n),await CM(n,r)}catch(r){return qp(n.name,r)}}function RM(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function SM(e){e.requiresServerRuntime&&(Rc||(Rc=mM().catch(t=>{throw Rc=null,t})),await Rc),e.requiresProviders&&(Sc||(Sc=Ah().then(()=>{}).catch(t=>{throw Sc=null,t})),await Sc)}function PM(e){if(!e.isLocal&&!e.isClone)return;let t=De();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 CM(e,t){try{let n=e.security==="remote"?await xM(e,t):await wM(e,t);return $p(n)}catch(n){return qp(e.name,n)}}async function xM(e,t){return mf(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function wM(e,t){return gf(e.execute,e.name)(t)}var Rc,Sc,mM,yM,fP=y(()=>{"use strict";fr();Hs();ot();Bp();Wp();Oc();gp();Rc=null,Sc=null,mM=Qm;yM=dP.map(hM)});var Kp=y(()=>{"use strict";gp();fP()});function ve(e,t){return Vp(e,{queries:[{...EM,...t}]})}function Pn(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function Zr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function _i(e){return typeof e=="string"?e:void 0}var EM,Ii=y(()=>{"use strict";Kp();EM={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function hP(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 Fi(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function yP(e){return e.structuredContent?.results?.[0]?.status}function TM(e,t){return e>0?[]:[P("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 bP(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function mP(...e){return e.map(bP).filter(Boolean).join("/")}function kM(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function gP(e){return bP(e).split("/").filter(Boolean).length}function OM(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function vM(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function AM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function LM(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(AM).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function _M(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(OM).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!LM(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(vM(o.path)))}function RP(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function IM(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 FM(e){return typeof e=="string"?[]:e.matches??[]}async function SP(e){switch(e.target){case"content":return NM(e);case"structure":return GM(e);case"files":return MM(e);default:return DM(e)}}async function MM(e){let t=Ri(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 ve("ghSearchCode",t.query),r=Fi(n),o=new Set,i=[];for(let a of r?.files??[]){let c=RP(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Fe(e),path:c,entryType:"file"}))}let s=Jt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...Pc(n,i.length,"ghSearchCode"),...i.length>0?[P("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:Fe(e)}]}}function Fe(e){return e.from??{kind:"github"}}async function DM(e){let t=Ri(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await ve("ghSearchCode",t.query),r=Fi(n),o=[];for(let s of r?.files??[]){let a=RP(s),c=IM(s),l=FM(s);if(l.length===0){o.push({kind:"code",source:Fe(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Fe(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=Zd(Jt(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...Pc(n,o.length,"ghSearchCode"),...o.length>0?[P("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:Fe(e)}]}}async function NM(e){let{owner:t,repo:n}=hP(Fe(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=HM(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:ut(e.scope)??"",type:"file",minify:o,...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(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 ve("ghGetFileContent",s),c=Fi(a),l=o==="none"?"exact":o==="symbols"?"symbols":"compact",u=c?.pagination,d=c?.results??c?.files??[],p=d.map(m=>{let g=m.pagination??u,b=typeof g?.charOffset=="number",w={...m.startLine!==void 0?{startLine:m.startLine}:{},...m.endLine!==void 0?{endLine:m.endLine}:{},...b?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Fe(e),path:m.path,content:m.content,contentView:l,...Object.keys(w).length?{range:w}:{}}}),f=u??d.find(m=>m.pagination)?.pagination;return{results:p,...f?.hasMore!==void 0?{pagination:{hasMore:!!f.hasMore,...f.currentPage!==void 0?{currentPage:f.currentPage}:{},...f.totalPages!==void 0?{totalPages:f.totalPages}:{},...f.charLength!==void 0?{itemsPerPage:f.charLength}:{},...f.totalChars!==void 0?{totalItems:f.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...Pc(a,p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Fe(e)}]}}async function GM(e){let{owner:t,repo:n}=hP(Fe(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:ut(e.scope)??"",...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(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 ve("ghViewRepoStructure",r),i=Fi(o),s=[],a=ut(e.scope);for(let u of kM(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=mP(a,d,p);s.push({kind:"tree",source:Fe(e),path:f,entryType:"directory",depth:gP(f)})}for(let p of u.files??[]){let f=mP(a,d,p);s.push({kind:"tree",source:Fe(e),path:f,entryType:"file",depth:gP(f)})}}let c=_M(s,e),l=Jt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...Pc(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Fe(e)}]}}function HM(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 eo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function zM(e){if(yP(e)==="error"){let r=Fi(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:eo(o.status),retryAfterSeconds:eo(o.retryAfter),rateLimitRemaining:eo(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:eo(n.status),retryAfterSeconds:eo(n.retryAfterSeconds),rateLimitRemaining:eo(n.rateLimitRemaining)}}function QM(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 P("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?P("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."}}):P("invalidQuery",e.message,{backend:t})}function BM(e,t){let n=zM(e);return n?[QM(n,t)]:yP(e)==="empty"?[P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function Pc(e,t,n){let r=BM(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...TM(t,n)]}var PP=y(()=>{"use strict";Ii();Ua();ep();yt();Ud();bi()});import CP from"node:path";function xP(e){return[...new Set(e)]}function EP(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 TP(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!CP.isAbsolute(r.localPath)?CP.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function kP(e){if(e.from?.kind!=="github")return Pi(e);let t=e.from,{owner:n,repo:r}=EP(t);if(!n||!r)return{results:[],diagnostics:[P("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=ut(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 ve("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=TP(s);if(u==="error"||!a)return{results:[],diagnostics:[P("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},p={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:xP([...d.excludeDir??[],".git"]),exclude:xP([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await Pi(p);return{...f,diagnostics:[...f.diagnostics,...c?[P("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"},...f.provenance]}}async function OP(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[wP(f,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[P("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}=EP(t);if(!n||!r)return{results:[],diagnostics:[P("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:ut(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await ve("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=TP(a);if(d==="error"||!c)return{results:[],diagnostics:[P("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let p=!i;return{results:[wP(c,t,t.ref,p,l)],diagnostics:l?[P("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 wP(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 vP=y(()=>{"use strict";Ii();ap();yt();bi()});import{builtinModules as jM}from"node:module";import Ee from"node:path";import{readFile as Cc,readdir as UM}from"node:fs/promises";async function Jp(e){let t=Ee.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=VM(r,e.intent,e.facets),i=KM(o,e.facets),s=YM(o,i),a=iD();if(n==="plan")return XM({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:LP([],[],a)});let c=await JM(t,e.maxFiles??5e3),l=await ZM(c.filter(x=>x.endsWith($M))),u=await rD(t,c),d=u.map(x=>x.graphFacts).filter(x=>x!==void 0),p=LP(u,d,a);await bD(u);let f=new Set(l.map(x=>x.name).filter(DP)),m=cD(u),g=lD(t,l,u),b=uD(g,m),w=u.filter(x=>!b.has(x.path)).map(x=>({kind:"unusedFile",file:x.rel,retainedBy:[],verdict:"unused-file"})),S=dD(t,l,u,f),T=await fD(u),A=hD(T,u,b),_=A.filter(x=>x.verdict==="candidate-unused-export"||x.verdict==="unused-export").length,k=A.filter(x=>x.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:b.size,unusedFiles:w.length,unlistedDependencies:S.filter(x=>x.kind==="unlistedDependency").length,unusedDependencies:S.filter(x=>x.kind==="unusedDependency").length,duplicateDependencies:S.filter(x=>x.kind==="duplicateDependency").length,exportedSymbols:A.length,candidateUnusedExports:_,transitiveDeadExports:k,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((x,N)=>x+N.declarations.length,0),nativeGraphCalls:d.reduce((x,N)=>x+N.calls.length,0)},manifests:l.map(x=>({manifest:Yn(t,x.path),...x.name?{name:x.name}:{},entrypoints:x.entrypoints.map(N=>Yn(t,N)),dependencyCount:[...x.deps.keys()].length})),files:w,dependencies:S,symbols:A,graphFacts:d,graphCapabilities:p,caveats:["This is a smart research flow with native AST graph facts where available plus heuristic cross-file reachability. LSP references should be used before destructive cleanup.","Graph capability coverage is explicit: tree-sitter/OXC facts are syntax inventory, not semantic deletion proof.","Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function VM(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 KM(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 YM(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:["localSearchCode structural","lspGetSemantics documentSymbols"],produces:["symbols","lineHints"],evidence:"proof"},{id:"reference-proof",purpose:"Use references grouped by file to separate direct, external, and transitive retention.",tools:["lspGetSemantics references","localSearchCode"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"proof"}),(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 XM(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."]}}async function JM(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await UM(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(qM.has(s.name))continue;await r(Ee.join(o,s.name));continue}s.isFile()&&n.push(Ee.join(o,s.name))}}return await r(e),n}async function ZM(e){return(await Promise.all(e.map(async n=>eD(n)))).filter(n=>n!==null)}async function eD(e){let t=await tD(e);if(!t)return null;let n=Ee.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=CD(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:MP(t.name),deps:r,entrypoints:nD(n,t)}}async function tD(e){try{let t=JSON.parse(await Cc(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function nD(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=MP(t[o]);i&&n.add(Ee.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(Ee.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(Ee.resolve(e,o));IP(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(Ee.resolve(e,o));return[...n]}function IP(e,t,n){if(typeof t=="string"){n.add(Ee.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))IP(e,r,n)}async function rD(e,t){let n=Zp(),r=t.filter(i=>n.has(Ee.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await Cc(i,"utf8").catch(()=>""),a=Ee.extname(i).toLowerCase(),c=oD(s,i,Yn(e,i)),l=wD(c?c.imports.map(u=>u.specifier):aD(s));return{path:i,rel:Yn(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!FP(u)).map(PD).filter(DP).filter(u=>!WM.has(u)),...c?{graphFacts:c}:{}}}))}function oD(e,t,n){try{let r=M.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??Ee.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(xD):[]}}catch{return}}function Zp(){if(Mi)return Mi;try{let e=M.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Mi=new Set(e.length>0?e:AP)}catch{Mi=new Set(AP)}return Mi}function iD(){if(Di)return Di;try{let e=JSON.parse(M.getGraphFactCapabilities());Di=Array.isArray(e)?e.filter(sD):[]}catch{Di=[]}return Di}function sD(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 LP(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...Zp()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=_P(e,l=>l.language),s=_P(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 _P(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function aD(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 cD(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,Ee.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??Ee.dirname(o.path);for(let a of o.imports){if(!FP(a))continue;let c=SD(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function lD(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=Xp(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let s=Xp(Ee.resolve(e,i),r);s&&o.add(s)}return[...o]}function uD(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}function dD(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=pD(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:Yn(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:Yn(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:Yn(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function pD(e,t){return t.filter(r=>e.startsWith(`${r.dir}${Ee.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function fD(e){return(await Promise.all(e.map(async n=>{let r=mD(n);if(r.length>0)return r;let o=await Cc(n.path,"utf8").catch(()=>"");return gD(n.rel,o)}))).flat()}function mD(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 gD(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:RD(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 hD(e,t,n){let r=new Map(t.map(o=>[o.rel,o]));return e.map(o=>{let i=t.filter(u=>u.rel!==o.file&&yD(u.path,o.symbol)),s=i.filter(u=>n.has(u.path)),a=r.get(o.file),c=a?n.has(a.path):!1,l=s.length>0?"reachable":i.length>0?"transitive-dead":c?"candidate-unused-export":"unused-export";return{symbol:o.symbol,kind:o.kind,file:o.file,line:o.line,evidenceSource:o.evidenceSource,directRefs:i.length,externalRefs:s.length,retainedBy:i.map(u=>u.rel),verdict:l}})}function yD(e,t){return Yp.get(e)?.has(t)??!1}async function bD(e){Yp.clear(),await Promise.all(e.map(async t=>{let n=await Cc(t.path,"utf8").catch(()=>"");Yp.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function RD(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function SD(e,t,n){return Xp(Ee.resolve(e,t),n)}function Xp(e,t){let n=Zp(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(Ee.join(e,`index${o}`));return r.find(o=>t.has(o))}function FP(e){return e.startsWith("./")||e.startsWith("../")}function PD(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function CD(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function MP(e){return typeof e=="string"&&e.trim()?e:void 0}function DP(e){return typeof e=="string"&&e.length>0}function xD(e){return typeof e=="string"}function wD(e){return[...new Set(e)]}function Yn(e,t){return Ee.relative(e,t)||Ee.basename(t)}var AP,$M,qM,WM,Mi,Di,Yp,NP=y(()=>{"use strict";we();AP=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],$M="package.json",qM=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),WM=new Set(jM.flatMap(e=>[e,`node:${e}`]));Yp=new Map});import ef from"node:path";function tf(e){let t=e.root,n=[...e.symbols.map(a=>ED(t,a)),...e.files.map(a=>vD(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>AD(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let o={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},i=0,s=0;for(let a of n)o[a.verdict]+=1,i+=a.why.length,s+=a.retainedBy.length+(a.retains?.length??0);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function ED(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=TD(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:"references",source:"ripgrep",confidence:"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:kD(r),next:OD(e,t)}}function TD(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 kD(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via reference scan; likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable references found, but the scan is token-based. Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only referenced from unreachable code. Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function OD(e,t){let n=ef.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:"exact"}}},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 vD(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:ef.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:ef.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function AD(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 GP=y(()=>{"use strict"});import HP from"node:path";function no(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??LD),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 zP(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 BP(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:zP(e.relation),verdicts:zP(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 _D(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 to(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function of(e,t){if(!_D(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=>to(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>to(i.relation,t)),o=e.why.some(i=>to(i.claim,t));return n||r||o}function nf(e,t){e.set(t.id,t)}function ID(e,t,n){to(t.claim,n)&&e.set(t.id,t)}function rf(e,t,n,r){to(n.relation,r)&&(nf(e,n.from),nf(e,n.to),t.set(n.id,n))}function FD(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function jP(e,t,n,r,o,i){let s=t.filter(g=>of(g,r)),a=no(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,p=new Map,f={},m={};for(let g of s)f[g.verdict]=(f[g.verdict]??0)+1,m[g.proofStatus]=(m[g.proofStatus]??0)+1;for(let g of c){if(nf(l,g.subject),r.includeFacts)for(let b of g.why)ID(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of g.retainedBy)rf(l,u,b,r);if(r.direction!=="incoming")for(let b of g.retains??[])rf(l,u,b,r)}for(let b of g.missingProof)p.set(FD(b),b)}return r.includeEdges&&DD(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:p.size,byVerdict:f,proofStatus:m},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...p.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 sf(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 UP(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{subjects:e.length,facts:n,edges:r,byVerdict:t}}function DD(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=ND(a.relation);if(!to(c,i))continue;let l=QP(a.from,e,a.line),u=QP(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||rf(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 ND(e){let t=e.trim();return MD.has(t)?t:"references"}function QP(e,t,n){let r=GD(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 GD(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:HP.isAbsolute(o)?HP.relative(t,o):o,name:i}}var LD,MD,af=y(()=>{"use strict";LD=25;MD=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});import xc from"node:path";function lf(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function qP(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 WP(e,t,n,r,o){let i=n.filter(l=>of(l,r)),s=no(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 zD(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(P(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(P("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"),HD(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(P("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 HD(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 zD(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=xc.isAbsolute(t.subject.uri)?t.subject.uri:xc.resolve(e,t.subject.uri);try{let i=await ve("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=QD(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=Pn(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:_i(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,p=Zr(a?.totalReferences)??Zr(u?.totalReferences)??Zr(a?.referenceCount)??Zr(u?.referenceCount)??Zr(d?.totalItems)??$P(u)??$P(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:BD(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 QD(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 $P(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 BD(e,t){let n=new Set;return cf(e,n,t),[...n].slice(0,25)}function cf(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)cf(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"&&jD(i)&&t.add(xc.isAbsolute(i)?xc.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])cf(r[o],t,n)}function jD(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var VP=y(()=>{"use strict";Ii();yt();af()});import{statSync as UD}from"node:fs";import de from"node:path";function KP(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}}function tC(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 $D(e,t){if(!t||de.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?de.join(n.base,t):t}function qD(e,t,n){let r=t??n??".";if(!e)return r;if(de.isAbsolute(e))return e;if(n&&de.isAbsolute(n))return de.resolve(n,e);if(t&&de.isAbsolute(t)){let o=df(t)?t:de.dirname(t);return de.resolve(o,e)}return e}function YP(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function rC(e){if(!e)return[];for(let t of nC){let n=e[t];if(Array.isArray(n))return n}return[e]}function VD(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 KD(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))WD.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 Ni(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=ZD(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function oC(e){return e==="plan"||e==="prove"?e:"analyze"}function YD(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;iC.includes(o)&&t.add(o)}return t.size>0?t:void 0}function XD(e,t){let n=YD(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 iC){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=no(e,u.length);o[l]=u.slice(d,p),o[`${l}Page`]=f,s=f.itemsPerPage,a=Math.max(a,f.totalPages??1),f.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 JD(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 XP(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ZD(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"))??ro(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:ro(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??ro(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??ro(t);case"artifact":return n("localPath")??n("path");case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:ro(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 ro(t)}function ro(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function uf(e,t){let{status:n,data:r}=Pn(e);return n==="error"?[P("invalidQuery",tC(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function df(e){try{let t=de.isAbsolute(e)?e:de.resolve(e);return UD(t).isDirectory()}catch{return!1}}function wc(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 Cn(e){return e.params??{}}function eN(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function pf(e,t){let n={...Cn(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}function Ec(e,t,n,r){let{data:o,status:i}=Pn(e),s=uf(e,n),a=i==="error"?[]:rC(o);a.length===0&&!s.some(p=>p.code==="zeroMatches"||p.severity==="error")&&s.push(P("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=Jt(c,l),d=t==="package"?VD(o):void 0;return{results:Ni(a,t,r,KD(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function JP(){return P("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 tN(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(P("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(P("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(JP()):(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(JP());let i=e?.pagination;return i?.hasMore&&n.push(P("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:sC(i,t)})),n}function sC(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 nN(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:sC(n,t)}}async function rN(e){let{owner:t}=wc(e.from),n=pf(e,"limit"),r=typeof n.language=="string"?n.language:eN(e),o=Cd(r);o&&(n.language=o);let i=await ve("ghSearchRepos",{...t?{owner:t}:{},...n}),s=Ec(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&oN(n)&&s.diagnostics.push(P("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 oN(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 iN(e){let t=await ve("npmSearch",{...pf(e)});return Ec(t,"package","npmSearch",e.from??{kind:"npm"})}async function ZP(e){let{owner:t,repo:n}=wc(e.from),r=e.target==="commits",o=r?void 0:cN(e),i=r?sN(e):void 0,s=pf(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await ve("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=Ec(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?uN(c,o):i?aN(c,i):c}function sN(e){let t=Cn(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function aN(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),p=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,p)+(p<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(P("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(P("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 cN(e){let t=Cn(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 lN(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(`
|
|
53
|
+
`)}function uN(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=lN(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(P("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(P("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}}async function dN(e){let t=Cn(e),{owner:n,repo:r}=wc(e.from),o=Ur(t);if(o.kind==="prPatch"){let i=await ve("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return Ec(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?pN(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):fN(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[P("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 pN(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[P("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=f=>({results:[],diagnostics:[P("invalidQuery",f,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=df(r)?r:de.dirname(r),s=de.isAbsolute(t.path)?de.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(!eC.test(t.baseRef)||!eC.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(de.sep).join("/")}`,c=f=>Yt("git",["-C",i,"show",`${f}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let f=l.success?u:l,m=l.success?t.headRef:t.baseRef;return o(`git show ${m}:${a} failed: ${f.stderr.trim().split(`
|
|
54
|
+
`)[0]||f.error?.message||`exit ${f.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=aC(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?[P("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function fN(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[P("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=p=>ve("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:p,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=KP(i),c=KP(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(p=>p.status==="error"||typeof p.content!="string");if(l){let p=tC(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[P("invalidQuery",p,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=aC(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?[P("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function aC(e,t){let n=e===""?[]:e.split(`
|
|
60
55
|
`),r=t===""?[]:t.split(`
|
|
61
56
|
`),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let f=o-1;f>=0;f--)for(let m=i-1;m>=0;m--)s[f][m]=n[f]===r[m]?s[f+1][m+1]+1:Math.max(s[f+1][m],s[f][m+1]);let a=[],c=0,l=0,u=0,d=0,p=0;for(;d<o&&p<i;)n[d]===r[p]?(a.push(` ${n[d]}`),u++,d++,p++):s[d+1][p]>=s[d][p+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[p]}`),c++,p++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;p<i;)a.push(`+ ${r[p++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
|
|
62
|
-
`)}}async function eD(e){let t=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!t)return{results:[],diagnostics:[x("invalidQuery",'target:"artifacts" needs a local file `from` (path).',{backend:"localBinaryInspect"})],provenance:[]};let n=await Pe("localBinaryInspect",{path:t,...un(e)}),{data:r,status:o}=ln(n),i=lf(n,"localBinaryInspect");return o==="error"||!r?{results:[],diagnostics:i.length?i:[x("zeroMatches","localBinaryInspect returned no data.",{backend:"localBinaryInspect",severity:"info",blocksAnswer:!1})],provenance:[{backend:"localBinaryInspect",source:e.from}]}:{results:Ii([r],"artifact",e.from),diagnostics:[...i,...tD(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function tD(e,t){let n=e.pagination&&typeof e.pagination=="object"?e.pagination:void 0;return e.isPartial!==!0&&n?.hasMore!==!0?[]:[x("partialResult","Artifact text is paginated; follow the artifact continuation before treating the inline content as complete.",{backend:"localBinaryInspect",blocksAnswer:!0,continuation:nD(t,n)})]}function nD(e,t){if(!(t?.hasMore!==!0||typeof t.nextCharOffset!="number"))return{query:{...e,params:{...e.params??{},charOffset:t.nextCharOffset,...typeof t.charLength=="number"?{charLength:t.charLength}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}async function rD(e){let t,n,r=[],o=[],i=un(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,O=KC(E);n=c??(O?Z.resolve(E):void 0),t=a??(O?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=DC(e),O=E?Z.isAbsolute(E)?E:Z.join(e.from.localPath,E):void 0;s?(n=c??e.from.localPath,t=a??O):t=a??O??e.from.localPath}else if(e.from?.kind==="github"){let{owner:E,repo:O}=wc(e.from);if(!E||!O)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,H=DC(e),I=w&&!Z.isAbsolute(w)?w:H,v=await Pe("ghCloneRepo",{owner:E,repo:O,...e.from.ref?{branch:e.from.ref}:{},...I?{sparsePath:I}:{}}),D=ln(v).data,Q=gM(v,D?.localPath);if(!Q)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:Q}),s?(n=c??Q,w?t=Z.isAbsolute(w)?w:Z.join(Q,w):H&&(t=Z.isAbsolute(H)?H:Z.join(Q,H))):w?t=Z.isAbsolute(w)?w:Z.join(Q,w):H?t=Z.isAbsolute(H)?H:Z.join(Q,H):t=Q}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,...p}=i,f=await Pe("lspGetSemantics",{...p,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:m,status:g}=ln(f),b=m,S=UM(b,e),C=hM(cf(b?.uri),t,n),k=sD(e,C),_=iD(oD(b),u);return{results:g==="error"?[]:Ii(_,"semantics",k),...S?{pagination:S}:{},diagnostics:[...o,...lf(f,"lspGetSemantics"),...QM(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:k}]}}function oD(e){if(!e)return[];let n=(BC(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=cf(e.uri);return n.map(o=>BC(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return jC(e)}function iD(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 sD(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}}async function aD(e){let t=un(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(m=>typeof m=="string"):void 0,o=$C(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 Zp({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(m){return{results:[],diagnostics:[x("invalidQuery",m instanceof Error?m.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}:nf(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?xc(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"?CM(e,i):{fields:{}},p={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:WC(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=PM(l?.pagination,d.pagination);return{results:Ii([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function cD(e){let t=un(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(m=>typeof m=="string"):void 0,o=$C(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 Zp({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(m){return{results:[],diagnostics:[x("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:nf(i),a=xM(t),c=s?.packets??[],l=HC(i.mode,t)?await FM(n,e,c,a,IM(e,t)):[],u=OM(c),d=kM(e,c,u,a,i.graphFacts,n),p=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[HC(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.']:[]],f={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:WC(i.graphFacts),caveats:p};return{results:Ii([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var UC,yM,RM,qC,vM,JC,ZC=y(()=>{"use strict";Rc();ja();Rt();Ha();za();IC();FC();UC=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],yM=new Set([...UC,"pagination","contentPagination","next"]);RM=25;qC=["manifests","files","dependencies","symbols","graphFacts"];vM=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"]);JC={repositories:jM,packages:$M,pullRequests:QC,commits:QC,diff:XM,artifacts:eD,semantics:rD,research:aD,graph:cD}});var lP={};hP(lP,{buildArtifactContinuations:()=>iP,runOqlSearch:()=>lD});import pt from"node:path";import{statSync as tP}from"node:fs";async function lD(e,t={}){let n;try{n=yR(e)}catch(o){if(o instanceof on)return Zd(o.diagnostics);throw o}if(tR(n))return QD(n,e,t);let r=await nP(n,e,t);return df(r.results),r}function df(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 nP(e,t,n,r){let o=GR(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return FD(o,s,e.id,r,n.dryRun,e);let a=await BD(e,o);MD(e,a.results),uD(e,a);let c=gD(e,a);hD(e,a.results);let l=zD(e,a.results);return Ua({queryId:e.id,queryIndex:r,results:a.results,...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:QR(o.plan.backendCalls),plan:s})}function uD(e,t){if(e.target==="content"||e.target==="code"&&t.pagination?.totalItemsKind==="files"&&typeof e.limit!="number")return;let n=typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!n||n<1||t.results.length<=n)return;let r=t.pagination?.totalItems??t.results.length,o=t.pagination?.currentPage??e.page??1;t.results=t.results.slice(0,n),t.pagination={...t.pagination,currentPage:o,itemsPerPage:t.pagination?.itemsPerPage??n,totalItems:r,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(r/n)),hasMore:!0}}function dD(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 pD(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function fD(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 mD(e){let t=fD(e),n=pD(e),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 ${eP(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 ${eP(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 eP(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function gD(e,t){let n={};t.pagination?.hasMore&&e.target!=="content"&&(n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:"More result pages remain.",confidence:"exact"}),t.diagnostics.some(o=>o.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(o=>o.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. ${mD(e)}`,confidence:"heuristic"});let r={query:e,fileFrom:_D(e)};for(let o of t.results){let i=o.kind==="record"?`record:${o.recordType}`:o.kind,s=RD[i];if(!s)continue;let a=s(o,r);a&&Object.keys(a).length&&(o.next=a)}return n}function hD(e,t){for(let n of t)n.proofGrade??=yD(e,n)}function yD(e,t){return t.kind==="code"?Fi(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Fi(e.where,"text")||Fi(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"?Ec(t.data)?"missing":"graph":t.recordType==="research"?Ec(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function Fi(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Fi(n,t)):e.kind==="not"?Fi(e.predicate,t):!1:!1}function Ec(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(!bD(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function bD(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function SD(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:dD(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"exact",...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 CD(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 rP(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 oP(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function iP(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=oP(e);i&&(o==="strings"?n["next.search"]={query:{schema:"oql",target:"code",from:{kind:"local",path:i},where:{kind:"regex",value:"https?://\\S+"},controls:{search:{maxMatchesPerFile:100,matchPage:1}}},why:"Grep this strings dump with local code search (ripgrep) \u2014 swap the regex/pattern for what you need (URLs, hosts, symbols); page noisy hits losslessly with matchPage. For a huge binary this beats reading the capped inline preview.",confidence:"heuristic"}:Object.assign(n,rP(i,"extracted")));let s=typeof r?.nextScanOffset=="number"?r.nextScanOffset:void 0;s!==void 0&&(n["next.artifactStrings"]={query:{...t.query,params:{...t.query.params??{},scanOffset:s}},why:"Scan the next window of printable strings.",confidence:"exact"});let a=r?.pagination&&typeof r.pagination=="object"?r.pagination:void 0,c=typeof a?.nextCharOffset=="number"?a.nextCharOffset:void 0;if(a?.hasMore===!0&&c!==void 0){let l=typeof a.charLength=="number"?a.charLength:void 0;n["next.artifactContent"]={query:{...t.query,params:{...t.query.params??{},charOffset:c,...l!==void 0?{charLength:l}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}return Object.keys(n).length?n:void 0}function PD(e){let t=oP(e);return t?rP(t,"materialized"):void 0}function xD(e,t){return sP(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function wD(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(Ec(r))return sP(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function sP(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!Ec(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=ED(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 ED(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"&&TD.has(o));return r.length>0?r:void 0}function kD(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=AD(e)??LD(t.query),i=OD(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:"exact",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function OD(e,t){if(e&&pt.isAbsolute(e))return e;if(t&&pt.isAbsolute(t)){let n=vD(t);return e?pt.resolve(n,e):t}return t??e}function vD(e){try{return tP(e).isDirectory()?e:pt.dirname(e)}catch{return pt.dirname(e)}}function AD(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function LD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function _D(e){let t=cP(e);if(!t)return;let n=aP(t).slice(0,-pt.sep.length);return r=>({kind:"local",path:pt.isAbsolute(r)?r:pt.join(n,r)})}function ID(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 FD(e,t,n,r,o,i){if(!e.executable){let s=e.plan.nodes.some(a=>a.route==="UNSUPPORTED");return o&&!s?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:e.plan.diagnostics,provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{}}:Zd(e.plan.diagnostics,t,n,r,ID(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:e.plan.diagnostics,provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{}}}function aP(e){let t=pt.resolve(e);try{if(tP(t).isDirectory())return`${t}${pt.sep}`}catch{}return`${pt.dirname(t)}${pt.sep}`}function cP(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function MD(e,t){let n=cP(e);if(!n)return;let r=aP(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function zD(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):ND.has(c)?o.add(c):GD.has(c)?o.add("data"):HD.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(!DD.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})]:[]}async function BD(e,t){if(e.target==="materialize")return wC(e);let n=JC[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?bi(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"?xC(e):hC(e)}async function QD(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await nP(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=UD(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&df(o.merged.results)}else for(let i of r)df(i.envelope.results);return o}function UD(e){let t=new Set;for(let c of e)for(let l of c.envelope.results)t.add(l.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=!1,a=!1;for(let c of e){for(let l of c.envelope.results){let u=$D(l);n.has(u)||(n.add(u),r.push(l))}o.push(...c.envelope.diagnostics),i.push(...c.envelope.provenance),c.envelope.evidence.kind==="candidate"&&(s=!0),jD(c.envelope)&&(a=!0)}return a&&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:Ua({results:r,...a?{pagination:{hasMore:!0}}:{},diagnostics:o,provenance:i,executable:e.every(c=>c.envelope.evidence.kind!=="unsupported"),approximate:s})}}function jD(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function $D(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var RD,TD,DD,ND,GD,HD,uP=y(()=>{"use strict";SR();zR();Rt();UR();ap();yC();TC();ZC();mi();RD={code:SD,content:CD,"record:artifact":iP,"record:materialized":PD,"record:semantics":kD,"record:research":xD,"record:graph":wD};TD=new Set(["symbols","files","dependencies","relations"]);DD=new Set(["kind","source","recordType","id","proofGrade"]),ND=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),GD=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),HD=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});async function lC(e){let t=qD(e),n=Ln.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(uP(),lP)),o=await r(n.data,{authInfo:e.authInfo});return VD(o)}function qD(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function VD(e){let t=WD(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function WD(e){return nR(e)?{results:e.children.map(t=>dP(t.envelope,t.queryId)),oql:e,mode:e.mode,...e.merged?{merged:e.merged}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[dP(e,e.queryId??"oqlSearch-1")],oql:e}}function dP(e,t){return{id:e.queryId??t,...KD(e),data:e}}function KD(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var Up=y(()=>{"use strict";Gr();mi()});Oc();me();ft();eo();jn();Lc();Bi();Ge();Il();Kl();kl();wt();Zl();Jl();Ps();iu();Ns();$o();su();au();Eo();cu();mu();lu();fu();Ss();gu();Qs();yu();Su();bu();hu();Ru();gt();Ko();Be();Gt();lr();wo();Ht();Ts();Au();Gu();ta();zu();Hu();ei();Qu();Bu();la();Uu();Ku();Yu();ni();Zu();ya();qo();ed();Sa();ld();ri();Ls();fd();oi();ii();md();li();si();Ed();Rd();Sd();di();Fr();La();Fd();fi();pi();vd();Up();bc();bc();Pi();Pi();Lp();Ip();Dn();Op();nc();en();On();Qp();Bl();Nl();zp();Hl();Ml();fe();import{completeMetadata as YD}from"@octocodeai/octocode-core";var Mi=null;function pP(){return Mi||(Mi=YD),Mi}async function l5(){return pP()}async function u5(){pP()}function d5(){return Mi}function p5(){Mi=null}Yp();Ri();Fe();Gr();xu();ud();Xu();Or();br();Lu();Od();Ae();function g5(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function h5(){try{return ge().local.enabled}catch{return!1}}function y5(){try{if(!ge().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}hp();Pa();Xo();Xl();gr();ci();Et();Mt();ac();Sp();kp();Ep();Cp();vs();yr();No();Hs();Qo();be();function S5(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=F.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={totalOccurrences:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}import{z}from"zod";var kc=z.object({text:z.string()}),XD=z.object({match:z.object({text:z.string()}).optional(),start:z.number(),end:z.number()}),JD=z.object({type:z.literal("match"),data:z.object({path:kc,lines:z.object({text:z.string()}),line_number:z.number(),absolute_offset:z.number(),submatches:z.array(XD)})}),ZD=z.object({type:z.literal("context"),data:z.object({path:kc,lines:z.object({text:z.string()}),line_number:z.number(),absolute_offset:z.number()})}),eN=z.object({type:z.literal("begin"),data:z.object({path:kc})}),tN=z.object({type:z.literal("end"),data:z.object({path:kc,stats:z.object({elapsed:z.object({human:z.string()}),searches:z.number(),searches_with_match:z.number()}).optional()})}),nN=z.object({type:z.literal("summary"),data:z.object({elapsed_total:z.object({human:z.string()}),stats:z.object({elapsed:z.object({human:z.string()}),searches:z.number(),searches_with_match:z.number(),bytes_searched:z.number(),bytes_printed:z.number(),matched_lines:z.number(),matches:z.number()})})}),x5=z.discriminatedUnion("type",[JD,ZD,eN,tN,nN]);je();qp();oe();Ws();ia();Fu();Vo();Du();Id();Wc();ji();tl();hl();mn();yl();import{securityRegistry as y6,ContentSanitizer as b6}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as S6}from"@octocodeai/octocode-engine/mask";import{configureSecurity as P6}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as A6}from"@octocodeai/octocode-core";import{z as _6}from"zod";export{lN as ALL_ERROR_CODES,cC as ALL_TOOLS,xw as BASE_SCHEMA,ea as BulkCloneRepoLocalSchema,Ci as BulkLspGetSemanticsQuerySchema,vc as CONFIG_ERRORS,Tm as CONFIG_FILE_NAME,Ro as CONFIG_FILE_PATH,go as CONFIG_SCHEMA_VERSION,Ys as CORE_ALLOWED_ENV_VARS,Lt as CREDENTIALS_FILE,yp as CircuitOpenError,Zo as CloneRepoQueryLocalSchema,Us as ContentBuilder,b6 as ContentSanitizer,zq as DEFAULTS,l4 as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,ls as DEFAULT_CONFIG,ho as DEFAULT_GITHUB_CONFIG,Kt as DEFAULT_LOCAL_CONFIG,yo as DEFAULT_LSP_CONFIG,Rf as DEFAULT_MATCH_SNIPPET_CHARS,Zn as DEFAULT_NETWORK_CONFIG,Ft as DEFAULT_OUTPUT_CONFIG,bn as DEFAULT_TOOLS_CONFIG,Hp as DEFAULT_TOOL_METADATA_GATEWAY,Dl as DESCRIPTIONS,mT as DIFF_PREVIEW_MAX_LINES,mS as DIRECT_TOOL_CATEGORIES,Z_ as DIRECT_TOOL_DEFINITIONS,Ot as DirectToolInputError,Yn as ENV_TOKEN_VARS,q as ERROR_CODES,Se as ERROR_MESSAGES,Xr as FETCH_ERRORS,jt as FILE_OPERATION_ERRORS,na as FileContentBulkQueryLocalSchema,nk as FileContentQueryBaseLocalSchema,xr as FileContentQueryLocalSchema,UY as GITHUB_CLONE_REPO,GY as GITHUB_FETCH_CONTENT,bf as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,NY as GITHUB_SEARCH_CODE,ot as GITHUB_SEARCH_DEFAULT_LIMIT,xe as GITHUB_SEARCH_MAX_LIMIT,sN as GITHUB_SEARCH_MAX_PAGES,BY as GITHUB_SEARCH_PULL_REQUESTS,zY as GITHUB_SEARCH_REPOSITORIES,Tn as GITHUB_STRUCTURE_DEFAULTS,aN as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,mf as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,HY as GITHUB_VIEW_REPO_STRUCTURE,e$ as GitHubCloneRepoOutputLocalSchema,ca as GitHubCodeSearchBulkQueryLocalSchema,q$ as GitHubCodeSearchOutputLocalSchema,aa as GitHubCodeSearchQueryLocalSchema,c$ as GitHubFetchContentOutputLocalSchema,Bs as GitHubProvider,ma as GitHubPullRequestSearchBulkQueryLocalSchema,wr as GitHubPullRequestSearchQueryLocalSchema,ha as GitHubReposSearchBulkQueryLocalSchema,ga as GitHubReposSearchSingleQueryLocalSchema,s1 as GitHubSearchPullRequestsOutputLocalSchema,M1 as GitHubSearchRepositoriesOutputLocalSchema,Ra as GitHubViewRepoStructureBulkQueryLocalSchema,X1 as GitHubViewRepoStructureOutputLocalSchema,ba as GitHubViewRepoStructureQueryLocalSchema,At as HOME,fz as IGNORED_FILE_EXTENSIONS,mz as IGNORED_FILE_NAMES,gz as IGNORED_FOLDER_NAMES,xt as KEY_FILE,KY as LOCAL_BINARY_INSPECT,hf as LOCAL_DEFAULT_FILES_PER_PAGE,VY as LOCAL_FETCH_CONTENT,qY as LOCAL_FIND_FILES,Bn as LOCAL_MAX_DEPTH,Gi as LOCAL_MAX_FILES_PER_PAGE,Ut as LOCAL_MAX_LIMIT,jY as LOCAL_RIPGREP,$ as LOCAL_TOOL_ERROR_CODES,Sf as LOCAL_TOOL_ERROR_REGISTRY,$Y as LOCAL_VIEW_STRUCTURE,WY as LSP_GET_SEMANTIC_CONTENT,ve as LSP_GET_SEMANTIC_CONTENT_TOOL_NAME,Ca as LocalBinaryInspectBulkQuerySchema,Tr as LocalBinaryInspectQuerySchema,Ta as LocalFetchContentBulkQuerySchema,vr as LocalFetchContentQuerySchema,Ea as LocalFindFilesBulkQuerySchema,Ar as LocalFindFilesQuerySchema,ka as LocalRipgrepBulkQuerySchema,tn as LocalRipgrepQuerySchema,PP as LocalToolErrorCategory,_a as LocalViewStructureBulkQuerySchema,Dr as LocalViewStructureQuerySchema,Y_ as LspGetSemanticsOutputSchema,Si as LspGetSemanticsQueryDisplaySchema,M_ as LspGetSemanticsQuerySchema,Hx as MAX_BRANCH_CACHE_SIZE,Qn as MAX_CHAR_LENGTH,yf as MAX_CONTEXT_LINES,Fg as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Wl as MAX_DIRECTORY_FILES,zi as MAX_MATCH_CONTENT_LENGTH,ir as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,Hi as MAX_PAGE_NUMBER,rr as MAX_RETRIES,tr as MAX_TIMEOUT,Ag as MAX_TOTAL_SIZE,or as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,nr as MIN_RETRIES,er as MIN_TIMEOUT,Tl as NETWORK_ERROR_PATTERNS,LS as NpmDeprecationOutputSchema,AS as NpmRegistrySearchSchema,tc as NpmSearchBulkQueryLocalSchema,C2 as NpmSearchOutputLocalSchema,ec as NpmSearchQueryLocalSchema,cc as NpmViewResultSchema,Fc as OCTOCODE_DIR,Ne as OCTOCODE_HOME,YY as OQL_SEARCH,Fn as OQL_SEARCH_TOOL_NAME,us as OctocodeConfigSchema,Fx as OctokitWithThrottling,Ln as OqlSearchInputSchema,QY as PACKAGE_SEARCH,Jr as PROMISE_ERRORS,Th as PROVIDER_CAPABILITIES,Mh as PROXY_ENV_VARS,pn as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,gf as PR_CONTENT_MAX_ITEMS_PER_PAGE,Nu as ProviderInitializationError,jU as QuickResult,bs as RATE_LIMIT_CONFIG,El as RATE_LIMIT_PATTERNS,Un as REPOSITORY_ERRORS,kt as RESOURCE_LIMITS,x5 as RipgrepJsonMessageSchema,qe as SEARCH_ERRORS,iS as SEMANTIC_CONTENT_TYPES,pj as SENSITIVE_ENV_VARS,hn as SESSION_FILE,SP as STARTUP_ERRORS,V as STATIC_TOOL_NAMES,yn as STATS_FILE,Zm as STATUS_TO_ERROR_CODE,js as StatusEmoji,oE as StatusEmojis,Yo as TOOLING_ALLOWED_ENV_VARS,CP as TOOL_ERRORS,RP as TOOL_METADATA_ERRORS,A as TOOL_NAMES,De as ToolError,Xe as ToolErrors,Yr as VALIDATION_ERRORS,ml as _getCacheState,vI as _packageNameToSearchKeywords,fl as _resetConfigCache,p5 as _resetMetadataState,E4 as _resetNpmRegistryUrlCache,wm as _resetSessionState,LH as _resetTokenResolvers,AH as _setTokenResolvers,jg as applyContentPagination,Wb as applyEntryFilters,Ak as applyExactMatchRanking,Rr as applyPagination,Fs as applyPartialContentFilter,Sh as applyStructurePagination,ES as assertCircuitAvailable,j as attachRawResponseChars,EB as buildBlockBoundaryHint,ku as buildChildProcessEnv,ng as buildCodeSearchQuery,Bo as buildDiffPreview,eI as buildDirectToolCommandPatterns,t4 as buildDirectToolExampleQuery,QA as buildEntryPaginationHints,Ey as buildGhSearchCodeFinalizer,xy as buildGithubFetchContentFinalizer,KI as buildPackagePagination,p$ as buildPaginationHints,og as buildPullRequestSearchQuery,rg as buildRepoSearchQuery,va as buildSearchResult,$p as buildToolErrorResult,_d as buildWalkWarnings,rT as byteSlice,ks as byteToCharIndex,Mg as charToByteIndex,cq as checkLargeOutputSafety,a4 as checkNpmAvailability,zI as checkNpmDeprecation,k4 as checkNpmRegistryReachable,kd as checkRegexSafety,G as clampedInt,_H as cleanup,iz as clearAllCache,az as clearLSPToolCache,sz as clearLocalToolCache,qH as clearOctokitInstances,NU as clearProviderCache,cz as clearRemoteAPICache,zh as cloneRepo,ra as collectFlatErrors,IE as commonDirPrefix,cp as compactLocation,Mn as compactResolvedSymbol,Gy as compareIsoDateDescending,A6 as completeMetadata,BE as computeQueryTimeout,km as configExists,d4 as configureCircuitBreaker,P6 as configureSecurity,Cr as contextLinesField,RB as convertByteMatchToChar,Dt as countLines,U as countSerializedChars,eu as createBasePRTransformation,Fo as createCacheMeta,ki as createCallItemKey,M as createErrorResult,Nt as createGitHubProviderError,zs as createGitHubProviderErrorFromResult,ct as createLazyProviderContext,Ng as createPaginationInfo,KE as createProviderExecutionContext,ie as createRelaxedBulkQuerySchema,Wo as createResponseFormat,UU as createResult,$s as createRoleBasedResult,GW as createSafeRegExp,_e as createSuccessResult,Wi as decrypt,Vf as deleteCredentials,xm as deleteSession,g5 as detectEnvironment,Vi as encrypt,OP as ensureBinary,Lf as ensureClone,wn as ensureCloneParentDir,$i as ensureHome,$t as ensureOctocodeDir,EP as ensureRepos,io as ensureTmp,kP as ensureTree,vP as ensureUnzip,xs as evictExpiredClones,Ao as evictExpiredTrees,se as executeBulkOperation,ny as executeCloneRepo,Kp as executeDirectTool,bb as executeFetchContent,Pb as executeFindFiles,fb as executeInspectBinary,Np as executeLspGetSemantics,xi as executeNpmCommand,lC as executeOqlSearchTool,Zt as executeProviderOperation,ty as executeProviderOperations,Ub as executeRipgrepSearch,Nb as executeRipgrepSearchInternal,Jb as executeViewStructure,jh as executeWithErrorIsolation,Ve as executeWithToolBoundary,qy as exploreMultipleRepositoryStructures,As as extractMatchingLines,mb as fallbackOnBestEffortFailure,wa as fetchContent,_g as fetchDirectoryContents,pu as fetchDirectoryContentsRecursivelyAPI,Ig as fetchFileContentToDisk,$g as fetchFileTimestamp,Vg as fetchGitHubFileContentAPI,mQ as fetchGitHubPullRequestByNumberAPI,ou as fetchGitHubPullRequestByNumberAPIInternal,hh as fetchHistory,wy as fetchMultipleGitHubFileContents,Cs as fetchRawGitHubFileContent,cn as fetchWithRetries,Wg as filterPatch,gO as filterStructure,pd as finalizeFetchContentResult,Cb as finalizeFindFilesResult,Mb as finalizeRipgrepResult,Xb as finalizeViewStructureResult,sc as findDirectToolDefinition,_r as findFiles,Ho as findNextBlockBoundary,mm as flushSession,gm as flushSessionSync,Ex as formatBytes,$U as formatCallToolResultForOutput,hS as formatDirectToolCommandPattern,Y2 as formatDirectToolMetadataSchemaText,Z2 as formatDirectToolOutputSchemaText,K2 as formatDirectToolSchemaText,oI as formatDirectToolValidationIssues,Lr as formatFileSize,oa as formatFinalizedResponse,Uo as formatPRForResponse,x1 as formatRepoLine,vp as gatherIncomingCallsRecursive,Ap as gatherOutgoingCallsRecursive,He as generateCacheKey,QQ as generatePaginationHints,Gs as generateStructurePaginationHints,Sl as getActiveProvider,Cl as getActiveProviderConfig,Ui as getAppDataPath,Of as getArchitecture,gB as getBulkDefaultCharLength,Dg as getByteLength,lz as getCacheStats,zw as getCacheTTL,Ql as getCloneBaseDir,Sg as getCloneDir,ms as getConfig,vm as getConfigPath,ge as getConfigSync,Bm as getConfigValue,gn as getCredentials,Jf as getCredentialsFilePath,Ji as getCredentialsSync,Af as getDefaultOctocodeHome,Bp as getDescription,X2 as getDirectToolAutoFilledFields,ic as getDirectToolCategory,e4 as getDirectToolDescription,SS as getDirectToolDisplayFields,J2 as getDirectToolOutputFields,xo as getDirectorySizeBytes,Gc as getEnvTokenSource,ag as getExtension,vh as getFileContent,Yi as getGhCliToken,jm as getGitHubToken,Ef as getLocalAppDataPath,y5 as getLspEnvironmentHint,Bw as getMaxCacheSizeBytes,Qw as getMaxCloneCount,d5 as getMetadataOrNull,Pp as getNpmRegistryUrl,Rn as getOctocodeDir,pe as getOctokit,hm as getOrCreateSession,et as getOutputCharLimit,ew as getOwnerQualifier,kf as getPlatformName,Pu as getProvider,le as getRawResponseChars,du as getRecursiveFetchFailureCount,Lh as getRepoStructure,tB as getReposBaseDir,hs as getServerConfig,ym as getSessionId,Zf as getToken,Ki as getTokenFromEnv,MH as getTokenSource,em as getTokenSync,qc as getTokenWithRefresh,Rg as getTreeBaseDir,Ul as getTreeDir,Ie as handleCatchError,re as handleGitHubAPIError,Ks as handleProviderError,Yf as hasCredentials,Xf as hasCredentialsSync,Hc as hasEnvToken,W$ as hasExpensiveContentRequest,Wh as hoistSharedFields,Qq as ignoreBestEffortFailure,Rm as incrementErrors,as as incrementGitHubCacheHits,cs as incrementGitHubCacheRateLimits,Cm as incrementPackageRegistryFailures,Sm as incrementRateLimitByProvider,is as incrementRateLimits,bm as incrementToolCalls,ss as incrementToolCharSavings,fA as inferLspSymbolName,Um as initialize,Ih as initializeProviders,u5 as initializeToolMetadata,sr as invalidateConfigCache,ro as invalidateCredentialsCache,ij as invokeCallbackSafely,Io as isCacheHit,Cg as isCacheValid,OS as isCircuitOpen,FH as isCloneEnabled,uc as isExactPackageName,En as isGitHubAPIError,DT as isGitHubAPISuccess,_c as isLinux,IH as isLocalEnabled,p2 as isLocalTool,oo as isMac,Go as isMidBlockCut,Pn as isNoResultsSearchError,VE as isProviderError,Js as isProviderSuccess,to as isRefreshTokenExpired,NT as isRepository,vt as isTokenExpired,Ac as isToolError,Gl as isToolInMetadata,fn as isWindows,Pr as lineNumberField,Wf as listStoredHosts,Kf as listStoredHostsSync,Om as loadConfig,So as loadConfigSync,l5 as loadToolContent,fy as mapCodeSearchProviderResult,dy as mapCodeSearchToolQuery,Ry as mapFileContentProviderResult,by as mapFileContentToolQuery,yy as mapPullRequestProviderResultData,hy as mapPullRequestToolQuery,gy as mapRepoSearchProviderRepositories,my as mapRepoSearchToolQuery,Cy as mapRepoStructureProviderResult,Sy as mapRepoStructureToolQuery,S6 as maskSensitiveData,jo as normalizeOwnerRepo,Ay as normalizePullRequestContentRequest,Rs as normalizeResponseHeaders,Ld as paginateEntries,ai as parseFileSize,Ce as parseGitHubProjectId,S5 as parseRipgrepJson,ne as paths,Db as preflightValidateRipgrepPattern,rI as prepareDirectToolInput,n4 as prepareDirectToolInputFromJsonText,qg as processFileContentAPI,Zs as providerSupports,jl as readCacheMeta,_t as readCredentialsStore,kS as recordCircuitFailure,Rp as recordCircuitSuccess,$m as recordPackageRegistryFailure,Yt as recordRateLimit,Zr as redactPath,tm as refreshAuthToken,Vh as relativizeResultPaths,ae as relaxedPageNumberField,pl as reloadConfig,ws as removeCloneDir,u4 as resetCircuitBreaker,Pm as resetSessionStats,Qc as resetTokenResolution,dl as resolveConfig,Po as resolveConfigSync,Ze as resolveDefaultBranch,_p as resolveFileAnchor,VS as resolveSymbolAnchor,Uc as resolveToken,Vt as resolveTokenFull,jc as resolveTokenWithRefresh,Qe as responseEnvelopeFields,Er as safeExec,Ue as safeParseOrError,jp as sanitizeCallToolResult,Tt as sanitizeStructuredContent,kh as searchCode,nn as searchContentRipgrep,dg as searchGitHubCodeAPI,mh as searchGitHubPullRequestsAPI,Rh as searchGitHubReposAPI,ky as searchMultipleGitHubCode,Ny as searchMultipleGitHubPullRequests,Uy as searchMultipleGitHubRepos,QS as searchNpmPackage,US as searchPackage,jS as searchPackages,Ah as searchPullRequests,Oh as searchRepos,y6 as securityRegistry,PB as serializeForPagination,Fy as shapePullRequestForContent,ko as shouldIgnoreDir,mr as shouldIgnoreFile,h5 as shouldUseMCPLsp,ig as shouldUseSearchForPRs,xB as sliceByCharRespectLines,Yl as sliceContent,Os as snapToSemanticBoundary,W2 as sortDirectToolNames,Dh as spawnCheckSuccess,fj as spawnCollectStdout,kn as spawnWithTimeout,Do as splitLines,nB as startCacheGC,rB as stopCacheGC,$c as storeCredentials,Ad as summarizeEntries,Yb as toEntryObject,Kb as toGroupedLists,Cf as toToolError,BT as transformCodeSearchResult,jT as transformFileContentResult,Ds as transformPullRequestItemFromREST,lh as transformPullRequestItemFromSearch,WT as transformPullRequestResult,QT as transformRepoSearchResult,YT as transformRepoStructureResult,Kg as trimDiffContext,rk as truncateSnippetChars,Je as updateSessionStats,Zi as updateToken,Xs as validateArgs,ps as validateConfig,Ke as validateToolPath,wh as viewGitHubRepositoryStructureAPI,Ia as viewStructure,ff as withBasicSecurityValidation,ze as withDataCache,JU as withResponseEnvelope,pf as withSecurityValidation,_o as writeCacheMeta,_6 as z};
|
|
57
|
+
`)}}async function mN(e){let t=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!t)return{results:[],diagnostics:[P("invalidQuery",'target:"artifacts" needs a local file `from` (path).',{backend:"localBinaryInspect"})],provenance:[]};let n=await ve("localBinaryInspect",{path:t,...Cn(e)}),{data:r,status:o}=Pn(n),i=uf(n,"localBinaryInspect");return o==="error"||!r?{results:[],diagnostics:i.length?i:[P("zeroMatches","localBinaryInspect returned no data.",{backend:"localBinaryInspect",severity:"info",blocksAnswer:!1})],provenance:[{backend:"localBinaryInspect",source:e.from}]}:{results:Ni([r],"artifact",e.from),diagnostics:[...i,...gN(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function gN(e,t){let n=e.pagination&&typeof e.pagination=="object"?e.pagination:void 0;return e.isPartial!==!0&&n?.hasMore!==!0?[]:[P("partialResult","Artifact text is paginated; follow the artifact continuation before treating the inline content as complete.",{backend:"localBinaryInspect",blocksAnswer:!0,continuation:hN(t,n)})]}function hN(e,t){if(!(t?.hasMore!==!0||typeof t.nextCharOffset!="number"))return{query:{...e,params:{...e.params??{},charOffset:t.nextCharOffset,...typeof t.charLength=="number"?{charLength:t.charLength}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}async function yN(e){let t,n,r=[],o=[],i=Cn(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.from.path,k=df(_);n=c??(k?de.resolve(_):void 0),t=a??(k?void 0:_)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let _=YP(e),k=_?de.isAbsolute(_)?_:de.join(e.from.localPath,_):void 0;s?(n=c??e.from.localPath,t=a??k):t=a??k??e.from.localPath}else if(e.from?.kind==="github"){let{owner:_,repo:k}=wc(e.from);if(!_||!k)return o.push(P("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let x=typeof i.uri=="string"?i.uri:void 0,N=YP(e),F=x&&!de.isAbsolute(x)?x:N,O=await ve("ghCloneRepo",{owner:_,repo:k,...e.from.ref?{branch:e.from.ref}:{},...F?{sparsePath:F}:{}}),B=Pn(O).data,G=$D(O,B?.localPath);if(!G)return o.push(P("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:G}),s?(n=c??G,x?t=de.isAbsolute(x)?x:de.join(G,x):N&&(t=de.isAbsolute(N)?N:de.join(G,N))):x?t=de.isAbsolute(x)?x:de.join(G,x):N?t=de.isAbsolute(N)?N:de.join(G,N):t=G}if(!t&&!n)return o.push(P("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...p}=i,f=await ve("lspGetSemantics",{...p,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:m,status:g}=Pn(f),b=m,w=nN(b,e),S=qD(_i(b?.uri),t,n),T=SN(e,S),A=RN(bN(b),u);return{results:g==="error"?[]:Ni(A,"semantics",T),...w?{pagination:w}:{},diagnostics:[...o,...uf(f,"lspGetSemantics"),...tN(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:T}]}}function bN(e){if(!e)return[];let n=(XP(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=_i(e.uri);return n.map(o=>XP(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return rC(e)}function RN(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 SN(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}}async function PN(e){let t=Cn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[P("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(m=>typeof m=="string"):void 0,o=oC(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[P("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 Jp({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(m){return{results:[],diagnostics:[P("invalidQuery",m instanceof Error?m.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}:tf(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?no(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"?XD(e,i):{fields:{}},p={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:sf(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=JD(l?.pagination,d.pagination);return{results:Ni([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function CN(e){let t=Cn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[P("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(m=>typeof m=="string"):void 0,o=oC(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[P("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 Jp({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(m){return{results:[],diagnostics:[P("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:tf(i),a=BP(t),c=s?.packets??[],l=lf(i.mode,t)?await WP(n,e,c,a,qP(e,t)):[],u=UP(c),d=jP(e,c,u,a,i.graphFacts,n),p=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[lf(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.']:[]],f={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:sf(i.graphFacts),caveats:p};return{results:Ni([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var nC,WD,iC,eC,cC,lC=y(()=>{"use strict";Ii();Ua();yt();Ga();Tr();Ha();NP();GP();af();VP();nC=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],WD=new Set([...nC,"pagination","contentPagination","next"]);iC=["manifests","files","dependencies","symbols","graphFacts"];eC=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/;cC={repositories:rN,packages:iN,pullRequests:ZP,commits:ZP,diff:dN,artifacts:mN,semantics:yN,research:PN,graph:CN}});var SC={};OC(SC,{buildArtifactContinuations:()=>hC,runOqlSearch:()=>xN});import St from"node:path";import{statSync as dC}from"node:fs";async function xN(e,t={}){let n;try{n=yR(e)}catch(o){if(o instanceof yn)return Xd(o.diagnostics);throw o}if(Jb(n))return sG(n,e,t);let r=await pC(n,e,t);return ff(r.results),r}function ff(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 pC(e,t,n,r){let o=HR(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return YN(o,s,e.id,r,n.dryRun,e);let a=await iG(e,o);ZN(e,a.results),wN(e,a),EN(a);let c=AN(e,a);_N(e,a.results);let l=oG(e,a.results),u=LN(a.results);return ja({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:jR(o.plan.backendCalls),plan:s})}function wN(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 EN(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}}function TN(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 kN(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function ON(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 vN(e){let t=ON(e),n=kN(e),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 ${uC(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 ${uC(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 uC(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function AN(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. ${vN(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:VN(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=MN[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function LN(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||fC(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function fC(e,t){return e.why===t.why&&e.confidence===t.confidence}function _N(e,t){for(let n of t)n.proofGrade??=IN(e,n)}function IN(e,t){return t.kind==="code"?Gi(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Gi(e.where,"text")||Gi(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"?Tc(t.data)?"missing":"graph":t.recordType==="research"?Tc(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function Gi(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Gi(n,t)):e.kind==="not"?Gi(e.predicate,t):!1:!1}function Tc(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(!FN(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function FN(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DN(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:TN(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"exact",...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 NN(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 mC(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 gC(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function hC(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=gC(e);i&&(o==="strings"?n["next.search"]={query:{schema:"oql",target:"code",from:{kind:"local",path:i},where:{kind:"regex",value:"https?://\\S+"},controls:{search:{maxMatchesPerFile:100,matchPage:1}}},why:"Grep this strings dump with local code search (ripgrep) \u2014 swap the regex/pattern for what you need (URLs, hosts, symbols); page noisy hits losslessly with matchPage. For a huge binary this beats reading the capped inline preview.",confidence:"heuristic"}:Object.assign(n,mC(i,"extracted")));let s=typeof r?.nextScanOffset=="number"?r.nextScanOffset:void 0;s!==void 0&&(n["next.artifactStrings"]={query:{...t.query,params:{...t.query.params??{},scanOffset:s}},why:"Scan the next window of printable strings.",confidence:"exact"});let a=r?.pagination&&typeof r.pagination=="object"?r.pagination:void 0,c=typeof a?.nextCharOffset=="number"?a.nextCharOffset:void 0;if(a?.hasMore===!0&&c!==void 0){let l=typeof a.charLength=="number"?a.charLength:void 0;n["next.artifactContent"]={query:{...t.query,params:{...t.query.params??{},charOffset:c,...l!==void 0?{charLength:l}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}return Object.keys(n).length?n:void 0}function GN(e){let t=gC(e);return t?mC(t,"materialized"):void 0}function HN(e,t){return yC(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function zN(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(Tc(r))return yC(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function yC(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!Tc(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=BN(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 BN(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"&&QN.has(o));return r.length>0?r:void 0}function jN(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=qN(e)??WN(t.query),i=UN(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:"exact",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function UN(e,t){if(e&&St.isAbsolute(e))return e;if(t&&St.isAbsolute(t)){let n=$N(t);return e?St.resolve(n,e):t}return t??e}function $N(e){try{return dC(e).isDirectory()?e:St.dirname(e)}catch{return St.dirname(e)}}function qN(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function WN(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function VN(e){let t=RC(e);if(!t)return;let n=bC(t).slice(0,-St.sep.length);return r=>({kind:"local",path:St.isAbsolute(r)?r:St.join(n,r)})}function KN(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 YN(e,t,n,r,o,i){let s=o&&i?XN(i):[],a=o&&i?JN(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}:{}}:Xd(e.plan.diagnostics,t,n,r,KN(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 XN(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[P("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function JN(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"}}}function bC(e){let t=St.resolve(e);try{if(dC(t).isDirectory())return`${t}${St.sep}`}catch{}return`${St.dirname(t)}${St.sep}`}function RC(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function ZN(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 oG(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):tG.has(c)?o.add(c):nG.has(c)?o.add("data"):rG.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(!eG.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?[P("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}async function iG(e,t){if(e.target==="materialize")return OP(e);let n=cC[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?Pi(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"?kP(e):SP(e)}async function sG(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await pC(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=aG(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&ff(o.merged.results)}else for(let i of r)ff(i.envelope.results);return o}function aG(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 p=dG(d);n.has(p)||(n.add(p),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),cG(s,u.envelope.nextHints),lG(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),uG(u.envelope)&&(l=!0)}return l&&o.push(P("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:ja({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 cG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||fC(o,r))&&(e[n]=r)}}function lG(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 uG(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function dG(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var MN,QN,eG,tG,nG,rG,PC=y(()=>{"use strict";SR();QR();yt();UR();ap();PP();vP();lC();zr();MN={code:DN,content:NN,"record:artifact":hC,"record:materialized":GN,"record:semantics":jN,"record:research":HN,"record:graph":zN};QN=new Set(["symbols","files","dependencies","relations"]);eG=new Set(["kind","source","recordType","id","proofGrade"]),tG=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),nG=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),rG=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});async function pP(e){let t=pG(e),n=Qn.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(PC(),SC)),o=await r(n.data,{authInfo:e.authInfo});return fG(o)}function pG(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function fG(e){let t=mG(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 mG(e){return Zb(e)?{results:e.children.map(t=>CC(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:xC(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[CC(e,e.queryId??"oqlSearch-1")]}}function CC(e,t){let n=xC(e);return{id:e.queryId??t,...hG(e),data:n}}function xC(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||gG(d,u)){let{why:p,confidence:f,...m}=l;s[c]=m,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function gG(e,t){return e.why===t.why&&e.confidence===t.confidence}function hG(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var jp=y(()=>{"use strict";Br();zr()});Oc();Se();Pt();uo();wn();Lc();co();je();Fl();Yl();Ol();It();tu();eu();Rs();au();Fs();Yo();cu();lu();Lo();uu();hu();du();gu();ys();yu();Hs();Ru();Cu();Su();bu();Pu();xt();xr();qe();Je();fr();vo();Kt();Cs();Au();Nu();ea();Hu();Gu();ri();Qu();zu();la();Bu();Vu();Ku();ii();Ju();ya();Xo();Zu();Sa();cd();si();Os();dd();ai();ci();pd();pi();li();wd();yd();bd();mi();Nr();gi();_d();yi();hi();kd();jp();bc();bc();Ti();Ti();Lp();Ip();Kr();Op();nc();gn();Nn();Bp();Bl();Gl();zp();zl();Dl();Re();import{completeMetadata as yG}from"@octocodeai/octocode-core";var Hi=null;function wC(){return Hi||(Hi=yG),Hi}async function K3(){return wC()}async function Y3(){wC()}function X3(){return Hi}function J3(){Hi=null}Kp();xi();Qe();Br();var eJ={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}"};ld();Yu();_r();Pr();Lu();Td();ot();function rJ(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function oJ(){try{return De().local.enabled}catch{return!1}}function iJ(){try{if(!De().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}hp();Ca();Tr();Jl();br();di();Mt();qt();ac();Sp();kp();Tp();Pp();Ts();Sr();Bo();Ds();Wo();we();function cJ(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=M.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={totalOccurrences:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}import{z}from"zod";var kc=z.object({text:z.string()}),bG=z.object({match:z.object({text:z.string()}).optional(),start:z.number(),end:z.number()}),RG=z.object({type:z.literal("match"),data:z.object({path:kc,lines:z.object({text:z.string()}),line_number:z.number(),absolute_offset:z.number(),submatches:z.array(bG)})}),SG=z.object({type:z.literal("context"),data:z.object({path:kc,lines:z.object({text:z.string()}),line_number:z.number(),absolute_offset:z.number()})}),PG=z.object({type:z.literal("begin"),data:z.object({path:kc})}),CG=z.object({type:z.literal("end"),data:z.object({path:kc,stats:z.object({elapsed:z.object({human:z.string()}),searches:z.number(),searches_with_match:z.number()}).optional()})}),xG=z.object({type:z.literal("summary"),data:z.object({elapsed_total:z.object({human:z.string()}),stats:z.object({elapsed:z.object({human:z.string()}),searches:z.number(),searches_with_match:z.number(),bytes_searched:z.number(),bytes_printed:z.number(),matched_lines:z.number(),matches:z.number()})})}),dJ=z.discriminatedUnion("type",[RG,SG,PG,CG,xG]);Be();Wp();ce();js();ia();Ks();Jo();Mu();Ld();al();ot();ul();yl();ot();bl();sr();Rl();import{securityRegistry as iZ,ContentSanitizer as sZ}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as cZ}from"@octocodeai/octocode-engine/mask";import{configureSecurity as uZ}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as SZ}from"@octocodeai/octocode-core";import{z as CZ}from"zod";export{AG as ALL_ERROR_CODES,dP as ALL_TOOLS,Xw as BASE_SCHEMA,Zs as BulkCloneRepoLocalSchema,Ei as BulkLspGetSemanticsQuerySchema,vc as CONFIG_ERRORS,NC as CONFIG_FILE_NAME,Fc as CONFIG_SCHEMA_VERSION,$s as CORE_ALLOWED_ENV_VARS,Bt as CREDENTIALS_FILE,yp as CircuitOpenError,ni as CloneRepoQueryLocalSchema,sZ as ContentSanitizer,$W as DEFAULTS,_Y as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,Af as DEFAULT_CONFIG,Gc as DEFAULT_GITHUB_CONFIG,tr as DEFAULT_LOCAL_CONFIG,Hc as DEFAULT_LSP_CONFIG,Pf as DEFAULT_MATCH_SNIPPET_CHARS,qi as DEFAULT_NETWORK_CONFIG,Tn as DEFAULT_OUTPUT_CONFIG,go as DEFAULT_TOOLS_CONFIG,Hp as DEFAULT_TOOL_METADATA_GATEWAY,Nl as DESCRIPTIONS,BE as DIFF_PREVIEW_MAX_LINES,mS as DIRECT_TOOL_CATEGORIES,ZI as DIRECT_TOOL_DEFINITIONS,Gt as DirectToolInputError,Vi as ENV_TOKEN_VARS,W as ERROR_CODES,Te as ERROR_MESSAGES,so as FETCH_ERRORS,rn as FILE_OPERATION_ERRORS,ta as FileContentBulkQueryLocalSchema,Fk as FileContentQueryBaseLocalSchema,kr as FileContentQueryLocalSchema,R5 as GITHUB_CLONE_REPO,m5 as GITHUB_FETCH_CONTENT,Sf as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,f5 as GITHUB_SEARCH_CODE,pt as GITHUB_SEARCH_DEFAULT_LIMIT,_e as GITHUB_SEARCH_MAX_LIMIT,kG as GITHUB_SEARCH_MAX_PAGES,y5 as GITHUB_SEARCH_PULL_REQUESTS,h5 as GITHUB_SEARCH_REPOSITORIES,Fn as GITHUB_STRUCTURE_DEFAULTS,OG as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,hf as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,g5 as GITHUB_VIEW_REPO_STRUCTURE,JU as GenericToolResultRowSchema,e1 as GitHubCloneRepoOutputLocalSchema,ca as GitHubCodeSearchBulkQueryLocalSchema,W1 as GitHubCodeSearchOutputLocalSchema,aa as GitHubCodeSearchQueryLocalSchema,c1 as GitHubFetchContentOutputLocalSchema,Gs as GitHubProvider,ma as GitHubPullRequestSearchBulkQueryLocalSchema,Or as GitHubPullRequestSearchQueryLocalSchema,ha as GitHubReposSearchBulkQueryLocalSchema,ga as GitHubReposSearchSingleQueryLocalSchema,aq as GitHubSearchPullRequestsOutputLocalSchema,Nq as GitHubSearchRepositoriesOutputLocalSchema,Ra as GitHubViewRepoStructureBulkQueryLocalSchema,Zq as GitHubViewRepoStructureOutputLocalSchema,ba as GitHubViewRepoStructureQueryLocalSchema,cr as HOME,fQ as IGNORED_FILE_EXTENSIONS,mQ as IGNORED_FILE_NAMES,gQ as IGNORED_FOLDER_NAMES,Lt as KEY_FILE,E5 as LOCAL_BINARY_INSPECT,bf as LOCAL_DEFAULT_FILES_PER_PAGE,x5 as LOCAL_FETCH_CONTENT,C5 as LOCAL_FIND_FILES,Xn as LOCAL_MAX_DEPTH,Qi as LOCAL_MAX_FILES_PER_PAGE,zt as LOCAL_MAX_LIMIT,S5 as LOCAL_RIPGREP,Q as LOCAL_TOOL_ERROR_CODES,Cf as LOCAL_TOOL_ERROR_REGISTRY,P5 as LOCAL_VIEW_STRUCTURE,Ke as LSP_GET_SEMANTICS_TOOL_NAME,w5 as LSP_GET_SEMANTIC_CONTENT,Pa as LocalBinaryInspectBulkQuerySchema,sW as LocalBinaryInspectOutputSchema,vr as LocalBinaryInspectQuerySchema,Ea as LocalFetchContentBulkQuerySchema,Ir as LocalFetchContentQuerySchema,Ta as LocalFindFilesBulkQuerySchema,GV as LocalFindFilesOutputSchema,Fr as LocalFindFilesQuerySchema,RV as LocalGetFileContentOutputSchema,ka as LocalRipgrepBulkQuerySchema,hn as LocalRipgrepQuerySchema,lK as LocalSearchCodeOutputSchema,FC as LocalToolErrorCategory,La as LocalViewStructureBulkQuerySchema,n2 as LocalViewStructureOutputSchema,Hr as LocalViewStructureQuerySchema,YI as LspGetSemanticsOutputSchema,wi as LspGetSemanticsQueryDisplaySchema,MI as LspGetSemanticsQuerySchema,fw as MAX_BRANCH_CACHE_SIZE,Jn as MAX_CHAR_LENGTH,Rf as MAX_CONTEXT_LINES,_g as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Kl as MAX_DIRECTORY_FILES,ji as MAX_MATCH_CONTENT_LENGTH,$c as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,Bi as MAX_PAGE_NUMBER,jc as MAX_RETRIES,Qc as MAX_TIMEOUT,Og as MAX_TOTAL_SIZE,Uc as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,Bc as MIN_RETRIES,zc as MIN_TIMEOUT,Tl as NETWORK_ERROR_PATTERNS,LS as NpmDeprecationOutputSchema,AS as NpmRegistrySearchSchema,tc as NpmSearchBulkQueryLocalSchema,j4 as NpmSearchOutputLocalSchema,ec as NpmSearchQueryLocalSchema,cc as NpmViewResultSchema,Yc as OCTOCODE_DIR,Ne as OCTOCODE_HOME,T5 as OQL_SEARCH,Un as OQL_SEARCH_TOOL_NAME,Hm as OctocodeConfigSchema,aw as OctokitWithThrottling,Qn as OqlSearchInputSchema,b5 as PACKAGE_SEARCH,ao as PROMISE_ERRORS,Ch as PROVIDER_CAPABILITIES,Ih as PROXY_ENV_VARS,xn as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,yf as PR_CONTENT_MAX_ITEMS_PER_PAGE,Du as ProviderInitializationError,gs as RATE_LIMIT_CONFIG,kl as RATE_LIMIT_PATTERNS,Zn as REPOSITORY_ERRORS,Dt as RESOURCE_LIMITS,dJ as RipgrepJsonMessageSchema,Xe as SEARCH_ERRORS,iS as SEMANTIC_CONTENT_TYPES,p$ as SENSITIVE_ENV_VARS,On as SESSION_FILE,_C as STARTUP_ERRORS,V as STATIC_TOOL_NAMES,vn as STATS_FILE,Xm as STATUS_TO_ERROR_CODE,eJ as StatusEmojis,ei as TOOLING_ALLOWED_ENV_VARS,IC as TOOL_ERRORS,LC as TOOL_METADATA_ERRORS,v as TOOL_NAMES,Me as ToolError,rt as ToolErrors,io as VALIDATION_ERRORS,lx as _getCacheState,vF as _packageNameToSearchKeywords,cx as _resetConfigCache,J3 as _resetMetadataState,KY as _resetNpmRegistryUrlCache,Gm as _resetSessionState,Lz as _resetTokenResolvers,Az as _setTokenResolvers,Qg as applyContentPagination,Ub as applyEntryFilters,cO as applyExactMatchRanking,Cr as applyPagination,Ls as applyPartialContentFilter,yh as applyStructurePagination,TS as assertCircuitAvailable,q as attachRawResponseChars,EB as buildBlockBoundaryHint,ku as buildChildProcessEnv,eg as buildCodeSearchQuery,qo as buildDiffPreview,eF as buildDirectToolCommandPatterns,wY as buildDirectToolExampleQuery,HL as buildEntryPaginationHints,Sy as buildGhSearchCodeFinalizer,yy as buildGithubFetchContentFinalizer,jO as buildMergedPagination,VF as buildPackagePagination,p1 as buildPaginationHints,BO as buildPartialFailureWarnings,YE as buildPullRequestSearchCacheKey,ng as buildPullRequestSearchQuery,tg as buildRepoSearchQuery,QO as buildResultPagination,va as buildSearchResult,qp as buildToolErrorResult,Ad as buildWalkWarnings,Ft as bulkOutputEnvelopeFields,LE as byteSlice,ws as byteToCharIndex,Ig as charToByteIndex,fW as checkLargeOutputSafety,AY as checkNpmAvailability,zF as checkNpmDeprecation,YY as checkNpmRegistryReachable,Ed as checkRegexSafety,H as clampedInt,Dn as cleanJsonObject,_z as cleanup,iQ as clearAllCache,aQ as clearLSPToolCache,sQ as clearLocalToolCache,qz as clearOctokitInstances,DU as clearProviderCache,cQ as clearRemoteAPICache,Gh as cloneRepo,ra as collectFlatErrors,ck as commonDirPrefix,cp as compactLocation,WF as compactPackageRepositories,$n as compactResolvedSymbol,_y as compareIsoDateDescending,SZ as completeMetadata,hk as computeQueryTimeout,YC as configExists,FY as configureCircuitBreaker,uZ as configureSecurity,wr as contextLinesField,bB as convertByteMatchToChar,Wt as countLines,j as countSerializedChars,nu as createBasePRTransformation,Ho as createCacheMeta,Li as createCallItemKey,D as createErrorResult,Vt as createGitHubProviderError,Ns as createGitHubProviderErrorFromResult,gt as createLazyProviderContext,Zl as createPaginationInfo,wk as createProviderExecutionContext,le as createRelaxedBulkQuerySchema,fn as createResponseFormat,QU as createResult,o2 as createSafeRegExp,He as createSuccessResult,Ji as decrypt,tm as deleteCredentials,Nm as deleteSession,rJ as detectEnvironment,Xi as encrypt,gx as ensureBinary,zf as ensureClone,In as ensureCloneParentDir,Ki as ensureHome,on as ensureOctocodeDir,fx as ensureRepos,bo as ensureTmp,mx as ensureTree,hx as ensureUnzip,Ss as evictExpiredClones,Mo as evictExpiredTrees,ue as executeBulkOperation,Xh as executeCloneRepo,Vp as executeDirectTool,mb as executeFetchContent,bb as executeFindFiles,sb as executeInspectBinary,Np as executeLspGetSemantics,ki as executeNpmCommand,pP as executeOqlSearchTool,mn as executeProviderOperation,Yh as executeProviderOperations,Hb as executeRipgrepSearch,Ib as executeRipgrepSearchInternal,Vb as executeViewStructure,Bh as executeWithErrorIsolation,Ze as executeWithToolBoundary,zy as exploreMultipleRepositoryStructures,ks as extractMatchingLines,ab as fallbackOnBestEffortFailure,wa as fetchContent,Ag as fetchDirectoryContents,mu as fetchDirectoryContentsRecursivelyAPI,Lg as fetchFileContentToDisk,Bg as fetchFileTimestamp,Ug as fetchGitHubFileContentAPI,fj as fetchGitHubPullRequestByNumberAPI,su as fetchGitHubPullRequestByNumberAPIInternal,fh as fetchHistory,by as fetchMultipleGitHubFileContents,bs as fetchRawGitHubFileContent,Sn as fetchWithRetries,$g as filterPatch,KO as filterStructure,ud as finalizeFetchContentResult,yb as finalizeFindFilesResult,Lb as finalizeRipgrepResult,Wb as finalizeViewStructureResult,sc as findDirectToolDefinition,Dr as findFiles,Uo as findNextBlockBoundary,Om as flushSession,vm as flushSessionSync,Zx as formatBytes,BU as formatCallToolResultForOutput,hS as formatDirectToolCommandPattern,RY as formatDirectToolMetadataSchemaText,CY as formatDirectToolOutputSchemaText,bY as formatDirectToolSchemaText,oF as formatDirectToolValidationIssues,Mr as formatFileSize,oa as formatFinalizedResponse,Vo as formatPRForResponse,wq as formatRepoLine,vp as gatherIncomingCallsRecursive,Ap as gatherOutgoingCallsRecursive,Ue as generateCacheKey,Qj as generatePaginationHints,Ms as generateStructurePaginationHints,Cl as getActiveProvider,xl as getActiveProviderConfig,dm as getAppDataPath,mm as getArchitecture,mB as getBulkDefaultCharLength,Fg as getByteLength,lQ as getCacheStats,mE as getCacheTTL,jl as getCloneBaseDir,bg as getCloneDir,Nf as getConfig,qc as getConfigFilePath,De as getConfigSync,ux as getConfigValue,kn as getCredentials,sm as getCredentialsFilePath,ts as getCredentialsSync,Hf as getDefaultOctocodeHome,Qp as getDescription,SY as getDirectToolAutoFilledFields,ic as getDirectToolCategory,xY as getDirectToolDescription,SS as getDirectToolDisplayFields,PY as getDirectToolOutputFields,Oo as getDirectorySizeBytes,dx as getEnvTokenSource,ig as getExtension,Th as getFileContent,Zi as getGhCliToken,Bm as getGitHubToken,pm as getLocalAppDataPath,iJ as getLspEnvironmentHint,gE as getMaxCacheSizeBytes,hE as getMaxCloneCount,X3 as getMetadataOrNull,Cp as getNpmRegistryUrl,ir as getOctocodeDir,be as getOctokit,Am as getOrCreateSession,ct as getOutputCharLimit,Ow as getOwnerQualifier,fm as getPlatformName,wu as getProvider,me as getRawResponseChars,fu as getRecursiveFetchFailureCount,Oh as getRepoStructure,tB as getReposBaseDir,Wi as getRuntimeSurface,fs as getServerConfig,Lm as getSessionId,am as getToken,Gf as getTokenFromEnv,Mz as getTokenSource,cm as getTokenSync,il as getTokenWithRefresh,yg as getTreeBaseDir,Ul as getTreeDir,ze as handleCatchError,ae as handleGitHubAPIError,Us as handleProviderError,om as hasCredentials,im as hasCredentialsSync,px as hasEnvToken,K1 as hasExpensiveContentRequest,Vs as hoistSharedFields,WW as ignoreBestEffortFailure,Im as incrementErrors,us as incrementGitHubCacheHits,ds as incrementGitHubCacheRateLimits,Mm as incrementPackageRegistryFailures,Fm as incrementRateLimitByProvider,cs as incrementRateLimits,_m as incrementToolCalls,ls as incrementToolCharSavings,cL as inferLspSymbolName,Qm as initialize,Ah as initializeProviders,Y3 as initializeToolMetadata,yo as invalidateConfigCache,mo as invalidateCredentialsCache,i$ as invokeCallbackSafely,Go as isCacheHit,Rg as isCacheValid,OS as isCircuitOpen,Fz as isCloneEnabled,uc as isExactPackageName,Mn as isGitHubAPIError,dT as isGitHubAPISuccess,ll as isLinux,Iz as isLocalEnabled,I4 as isLocalTool,cl as isMac,jo as isMidBlockCut,Ln as isNoResultsSearchError,Ci as isOqlEnabled,Ck as isProviderError,Xs as isProviderSuccess,po as isRefreshTokenExpired,pT as isRepository,Qt as isTokenExpired,Ac as isToolError,Hl as isToolInMetadata,Ro as isWindows,Er as lineNumberField,nm as listStoredHosts,rm as listStoredHostsSync,XC as loadConfig,Wc as loadConfigSync,K3 as loadToolContent,HT as makeToolResultRowSchema,ay as mapCodeSearchProviderResult,oy as mapCodeSearchToolQuery,fy as mapFileContentProviderResult,py as mapFileContentToolQuery,dy as mapPullRequestProviderResultData,uy as mapPullRequestToolQuery,ly as mapRepoSearchProviderRepositories,cy as mapRepoSearchToolQuery,gy as mapRepoStructureProviderResult,my as mapRepoStructureToolQuery,cZ as maskSensitiveData,Ko as normalizeOwnerRepo,wy as normalizePullRequestContentRequest,hs as normalizeResponseHeaders,vd as paginateEntries,ui as parseFileSize,ke as parseGitHubProjectId,cJ as parseRipgrepJson,ye as paths,_b as preflightValidateRipgrepPattern,rF as prepareDirectToolInput,EY as prepareDirectToolInputFromJsonText,jg as processFileContentAPI,Js as providerSupports,$l as readCacheMeta,jt as readCredentialsStore,kS as recordCircuitFailure,Rp as recordCircuitSuccess,jm as recordPackageRegistryFailure,un as recordRateLimit,lo as redactPath,lm as refreshAuthToken,Ws as relativizeResultPaths,pe as relaxedPageNumberField,ax as reloadConfig,Ps as removeCloneDir,IY as resetCircuitBreaker,Dm as resetSessionStats,tl as resetTokenResolution,ix as resolveConfig,Vc as resolveConfigSync,at as resolveDefaultBranch,Kc as resolveEnvToken,_p as resolveFileAnchor,Ys as resolveQueryId,XS as resolveSymbolAnchor,nl as resolveToken,an as resolveTokenFull,rl as resolveTokenWithRefresh,We as responseEnvelopeFields,Ar as safeExec,Ve as safeParseOrError,$p as sanitizeCallToolResult,Et as sanitizeStructuredContent,wh as searchCode,Nt as searchContentRipgrep,lg as searchGitHubCodeAPI,dh as searchGitHubPullRequestsAPI,hh as searchGitHubReposAPI,Py as searchMultipleGitHubCode,Ly as searchMultipleGitHubPullRequests,Ny as searchMultipleGitHubRepos,BS as searchNpmPackage,jS as searchPackage,qS as searchPackages,kh as searchPullRequests,Eh as searchRepos,iZ as securityRegistry,PB as serializeForPagination,_f as setRuntimeSurface,Oy as shapePullRequestForContent,_o as shouldIgnoreDir,yr as shouldIgnoreFile,oJ as shouldUseMCPLsp,rg as shouldUseSearchForPRs,CB as sliceByCharRespectLines,Xl as sliceContent,Es as snapToSemanticBoundary,yY as sortDirectToolNames,Fh as spawnCheckSuccess,f$ as spawnCollectStdout,Yt as spawnWithTimeout,Qo as splitLines,nB as startCacheGC,rB as stopCacheGC,ol as storeCredentials,Od as summarizeEntries,qb as toEntryObject,$b as toGroupedLists,xf as toToolError,hT as transformCodeSearchResult,RT as transformFileContentResult,Is as transformPullRequestItemFromREST,sh as transformPullRequestItemFromSearch,xT as transformPullRequestResult,yT as transformRepoSearchResult,ET as transformRepoStructureResult,qg as trimDiffContext,Mk as truncateSnippetChars,st as updateSessionStats,ns as updateToken,qs as validateArgs,Mf as validateConfig,tt as validateToolPath,Ph as viewGitHubRepositoryStructureAPI,_a as viewStructure,gf as withBasicSecurityValidation,$e as withDataCache,XU as withResponseEnvelope,mf as withSecurityValidation,No as writeCacheMeta,CZ as z};
|