@octocodeai/octocode-tools-core 18.2.0 → 18.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/direct.js CHANGED
@@ -18,7 +18,7 @@ Each operation has a strict input branch; fields from other operations are rejec
18
18
  Optionally choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; run the returned continuation. matchedLines are LSP anchors; match ranges and offsets are not. type:"directory" returns localPath when local access is enabled; otherwise use ghSearch operation:"tree".`,ghSearchHistory:'Search or list repository history. Choose operation:"pullRequests", "issues", or "commits"; fields from other operations are rejected. Pull-request search may be global, while issue and commit history require owner+repo. Search branches never accept detail identities, content selectors, or diff pagination. Follow a result with ghGetHistoryItem.',ghGetHistoryItem:'Retrieve exact GitHub history. Choose operation:"pullRequest" or "issue" with number, "commit" with ref, or "compare" with base+head. Every branch requires owner+repo and rejects fields from other branches. PR/issue content and commit/compare diffs keep their branch-specific page and character windows; copy returned continuations exactly.',npmSearch:"Resolve npm packages to source repositories. Set exactly one of packageName for exact lookup or keywords for discovery. Follow the repository into GitHub tools.",ghCloneRepo:"Best for repeated reads, local AST/regex, or LSP; use ghGetFileContent for one read. Discover a bounded sparsePath first; complete is relative to that requested scope. branch selects the ref and forceRefresh bypasses the cached clone. Pass results[].data.location.localPath to local tools.",localSearch:'Choose operation:"text" for lexical anchors, "structural" for AST matches, "files" for path or metadata discovery, and "tree" for directory orientation. Each operation has a strict branch, so do not mix fields across operations. Files/tree prune common generated and vendor directories by default; pass excludeDir:[] to prune nothing. Read exact hits with localGetFileContent and prove symbol identity with lspGetSemantics.',localAnalyzeGraph:"Map file topology, not symbol identity. dependencies/dependents need file; path needs file+target; deadCode/reachability accept roots; cycles needs no selector. Import edges and dead-code results are candidates\u2014verify changes and deletions with exact reads plus LSP.",localGetFileContent:`Read a known local path after search, find, or structure discovery. A path-only call returns a bounded standard-minified view. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
19
19
  Optionally choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; run the returned continuation. matchedLines are LSP anchors; match ranges and character offsets are not. Report fetched bytes only.`,lspGetSemantics:`Use a real search/read line anchor for semantic proof. references finds usages; callers incoming calls; callees outgoing calls; callHierarchy both. Fall back to references if call hierarchy is unavailable.
20
20
  documentSymbols/diagnostic need uri; workspaceSymbol needs symbolName; other operations need uri+symbolName+lineHint. orderHint resolves same-line names. format:"compact" saves tokens. Empty/unavailable results call for a new anchor or text search.`};import{z as or}from"zod";function M(e,t){return or.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,or.number().int().min(e).max(t))}var he=M(1,1e3).optional().default(1),ir=M(0,100).optional(),sr=M(1,1e9).optional(),Ye=or.preprocess(e=>typeof e=="number"&&Number.isFinite(e)?Math.max(e,0):e,or.number().nonnegative().refine(Number.isSafeInteger,"Expected a safe non-negative integer")),AR={responseCharOffset:Ye.optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:M(1,5e4).optional().describe("Full-response char window.")};function X(e,t={}){let{maxQueries:n=5}=t;return or.object({queries:or.array(e).min(1).max(n).describe("Parallel queries; response rows use matching zero-based indexes."),...AR}).strict()}import{z as dd}from"zod";function LR(e,t){return e?.description&&!t.description?t.describe(e.description):t}function md(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=LR(e.shape[r],o);return n}function _R(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function fd(e,t){if(!t?.length)return e;let n=new Set(t);return dd.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function oe(e,t={},n={}){let r=fd(e,n.omit);return _R(r,md(r,t)).strict()}function ce(e,t={},n={}){let r=fd(e,n.omit);return dd.object({...r.shape,...md(r,t)}).strict()}var Ri=oe(ja),Za=X(Ri);import{z as IR}from"zod";import{z as Et}from"zod";var gd=["fullContent","matchString","matchStringIsRegex","matchStringCaseSensitive","startLine","endLine"],kR=[...gd,"contextLines","charOffset","charLength","minify"];function yd(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)))}function Ci(e,t){return e.description?t.describe(e.description):t}function Se(e,t){let n=e[t];if(!n)throw new TypeError(`Expected schema field: ${t}`);return n}function Re(e,t){return Se(e,t).nonoptional()}function hd(e,t){let n=yd(e.shape,[...gd,...t?["type"]:[]]),r=t?{type:t}:{},o=Ci(Se(e.shape,"fullContent"),Et.literal(!1).optional()),i=Ci(Se(e.shape,"fullContent"),Et.literal(!0)),s=Et.object({...n,...r,fullContent:o}).strict(),a=Et.object({...n,...r,fullContent:i}).strict(),c=Et.object({...n,...r,fullContent:o,matchString:Re(e.shape,"matchString"),matchStringIsRegex:Se(e.shape,"matchStringIsRegex"),matchStringCaseSensitive:Se(e.shape,"matchStringCaseSensitive")}).strict(),l=Et.object({...n,...r,fullContent:o,startLine:Re(e.shape,"startLine"),endLine:Re(e.shape,"endLine")}).strict().superRefine((u,p)=>{typeof u.startLine=="number"&&typeof u.endLine=="number"&&u.endLine<u.startLine&&p.addIssue({code:"custom",path:["endLine"],message:"Set endLine greater than or equal to startLine."})});return[s,a,c,l]}function xi(e,t={}){if(!t.githubDirectoryMode)return Et.union(hd(e));let n=Ci(Se(e.shape,"type"),Et.literal("file").optional()),r=Ci(Se(e.shape,"type"),Et.literal("directory")),o=yd(e.shape,[...kR,"type"]),i=Et.object({...o,type:r}).strict();return Et.union([...hd(e,n),i])}var OR=IR.enum(["none","standard","symbols"]).optional(),bd={startLine:sr,endLine:sr,contextLines:ir,charOffset:Ye.optional(),charLength:M(1,5e4).optional(),minify:OR},vR=ce(fi,bd),Xr=oe(fi,bd),Ja=X(xi(vR,{githubDirectoryMode:!0}));function ec(e){return typeof e=="string"&&e.trim().length>0}function qa(e){return Array.isArray(e)&&e.some(ec)}function FR(e){return e.operation==="code"?qa(e.keywords)||["owner","path","extension","filename","language"].some(t=>ec(e[t])):e.operation==="repositories"?qa(e.keywords)||qa(e.topics)||["owner","language","stars","forks","goodFirstIssues","updated","created","size","visibility","license"].some(t=>ec(e[t]))||typeof e.archived=="boolean":!0}var ar=za.superRefine((e,t)=>{FR(e)||t.addIssue({code:"custom",path:["operation"],message:`${e.operation} needs at least one search term or scope filter`})}),tc=X(ar,{maxQueries:5});import{z as MR}from"zod";var Sd={limit:M(1,100).optional(),page:he.default(1),match:MR.enum(["file","path"]).default("file")},NR=oe(rn,Sd),DR=X(ce(rn,Sd));import{z as nc}from"zod";var Rd={type:nc.enum(["prs","commits","issues"]).optional(),prNumber:M(1,1e9).optional(),issueNumber:M(1,1e9).optional(),pageSize:M(1,100).optional().default(30),match:nc.array(nc.enum(["title","body","comments"])).optional(),page:he.default(1),filePage:M(1,1e3).optional(),commentPage:M(1,1e3).optional(),commitPage:M(1,1e3).optional(),charOffset:Ye.optional(),commentBodyOffset:Ye.optional(),charLength:M(1,5e4).optional()},HR=ce(hi,Rd),rc=oe(hi,Rd),GR=X(HR);import{z as Ei}from"zod";import{z as $e}from"zod";function lr(e,t,n){let r=e.safeParse(t);if(!r.success)for(let o of r.error.issues)n.addIssue({code:"custom",message:o.message,path:o.path})}function Cd(e){let t=e;for(;t instanceof $e.ZodOptional||t instanceof $e.ZodDefault;)t=t.unwrap();if(!(t instanceof $e.ZodObject))throw new TypeError("Expected an object schema");return t}function xd(e){let t=e;for(;t instanceof $e.ZodOptional||t instanceof $e.ZodDefault;)t=t.unwrap();if(!(t instanceof $e.ZodArray))throw new TypeError("Expected an array schema");return t}function ur(e,t){return e.description?t.describe(e.description):t}var wd={pageSize:M(1,100).optional().default(30),page:M(1,1e3).optional()},Pd={...wd,filePage:M(1,1e3).optional(),commentPage:M(1,1e3).optional(),commitPage:M(1,1e3).optional(),charOffset:Ye.optional(),commentBodyOffset:Ye.optional(),charLength:M(1,1e5).optional()},L0=oe(_n,Pd).superRefine((e,t)=>lr(_n,e,t)),cr=ce(_n,Pd),Td=Se(cr.shape,"content"),Ed=Cd(Td),Ad=Se(Ed.shape,"patches"),an=Cd(Ad),Ld=ur(Se(an.shape,"mode"),$e.literal("selected")),zR=ur(Se(an.shape,"mode"),$e.literal("all")),QR=ur(Se(an.shape,"files"),xd(Se(an.shape,"files")).min(1)),UR=ur(Se(an.shape,"ranges"),xd(Se(an.shape,"ranges")).min(1)),jR=$e.object({mode:Ld,files:QR,ranges:Se(an.shape,"ranges")}).strict(),$R=$e.object({mode:Ld,files:Se(an.shape,"files"),ranges:UR}).strict(),WR=$e.object({mode:zR}).strict(),VR=Ed.extend({patches:ur(Ad,$e.union([jR,$R,WR]).optional())}),ic=cr.omit({prNumber:!0,filePage:!0,commentPage:!0,commitPage:!0,content:!0,matchString:!0,commentBodyOffset:!0,charOffset:!0,charLength:!0}),KR=ic.superRefine((e,t)=>lr(_n,e,t)),Pi=cr.omit({keywords:!0,concise:!0,state:!0,assignee:!0,author:!0,commenter:!0,mentions:!0,"review-requested":!0,"reviewed-by":!0,label:!0,checks:!0,review:!0,head:!0,base:!0,created:!0,updated:!0,closed:!0,"merged-at":!0,comments:!0,reactions:!0,draft:!0,match:!0,sort:!0,order:!0,page:!0,archived:!0}).extend({owner:Re(cr.shape,"owner"),repo:Re(cr.shape,"repo"),prNumber:Re(cr.shape,"prNumber"),content:ur(Td,VR.optional())}),XR=Pi.superRefine((e,t)=>lr(_n,e,t)),_0=X($e.union([KR,XR])),_d={...wd,commentPage:M(1,1e3).optional(),charOffset:Ye.optional(),commentBodyOffset:Ye.optional(),charLength:M(1,1e5).optional()},k0=oe(kn,_d).superRefine((e,t)=>lr(kn,e,t)),oc=ce(kn,_d),Yr=oc.omit({issueNumber:!0,commentPage:!0,content:!0,matchString:!0,commentBodyOffset:!0,charOffset:!0,charLength:!0}),YR=Yr.superRefine((e,t)=>lr(kn,e,t)),Ti=oc.omit({keywords:!0,concise:!0,state:!0,assignee:!0,author:!0,commenter:!0,mentions:!0,label:!0,created:!0,updated:!0,closed:!0,comments:!0,reactions:!0,match:!0,sort:!0,order:!0,page:!0,archived:!0}).extend({issueNumber:Re(oc.shape,"issueNumber")}),ZR=Ti.superRefine((e,t)=>lr(kn,e,t)),I0=X($e.union([YR,ZR])),kd={page:he.default(1),pageSize:M(1,100).optional().default(30),filePage:he.optional(),charOffset:Ye.optional(),charLength:M(1,1e5).optional()};function JR(e,t){(e.base&&!e.head||e.head&&!e.base)&&t.addIssue({code:"custom",path:[e.base?"head":"base"],message:"compare mode requires base and head together"})}var O0=oe(gi,kd).superRefine(JR),wi=ce(gi,kd),sc=wi.omit({base:!0,head:!0}),qR=sc,pr=wi.omit({branch:!0,since:!0,until:!0,author:!0,committer:!0,page:!0}).extend({base:Re(wi.shape,"base"),head:Re(wi.shape,"head")}),eC=pr,v0=X($e.union([qR,eC]));var On=e=>Ei.literal(e).describe("Required operation selector."),dr=e=>Re(e,"owner"),mr=e=>Re(e,"repo"),tC=ic.extend({operation:On("pullRequests")}).strict(),nC=Yr.extend({operation:On("issues"),owner:dr(Yr.shape),repo:mr(Yr.shape)}).strict(),ac=sc.omit({includeDiff:!0,filePage:!0,charOffset:!0,charLength:!0}),rC=ac.extend({operation:On("commits"),owner:dr(ac.shape),repo:mr(ac.shape)}).strict(),fr=Ei.discriminatedUnion("operation",[tC,nC,rC]).describe("Search or list GitHub pull requests, issues, or commits using one strict operation branch."),pc=X(fr),cc=Pi.omit({prNumber:!0}),oC=cc.extend({operation:On("pullRequest"),owner:dr(cc.shape),repo:mr(cc.shape),number:Pi.shape.prNumber}).strict(),lc=Ti.omit({issueNumber:!0}),iC=lc.extend({operation:On("issue"),owner:dr(lc.shape),repo:mr(lc.shape),number:Ti.shape.issueNumber}).strict(),uc=pr.omit({base:!0,head:!0}),sC=uc.extend({operation:On("commit"),owner:dr(uc.shape),repo:mr(uc.shape),ref:Ei.string().min(1).describe("Commit SHA or ref to retrieve exactly.")}).strict(),aC=pr.extend({operation:On("compare"),owner:dr(pr.shape),repo:mr(pr.shape)}).strict(),Wt=Ei.discriminatedUnion("operation",[oC,iC,sC,aC]).describe("Retrieve one GitHub pull request, issue, commit, or ref comparison using one strict operation branch."),dc=X(Wt);import{z as Id}from"zod";var Od={limit:M(1,100).optional(),page:he.default(1),match:Id.array(Id.enum(["name","description","readme"])).optional()},cC=oe(jt,Od),lC=X(ce(jt,Od));var vd={maxDepth:M(0,20).optional(),page:he.default(1),itemsPerPage:M(1,200).optional()},pC=oe(Ln,vd),dC=X(ce(Ln,vd));import{z as Fn}from"zod";var Fd={page:he,pageSize:M(1,100).optional().describe("Packages returned per keyword-discovery page."),keywords:Fn.array(Fn.string()).optional()};function mc(e,t){let n=Array.isArray(e.keywords)?e.keywords.join(" ").trim():e.keywords?.trim();!e.packageName?.trim()&&!n&&t.addIssue({code:"custom",path:["packageName"],message:"provide packageName or keywords"}),e.packageName?.trim()&&n&&t.addIssue({code:"custom",path:["keywords"],message:"provide packageName or keywords, not both"}),e.packageName?.trim()&&e.pageSize!==void 0&&t.addIssue({code:"custom",path:["pageSize"],message:"pageSize is only available for keyword discovery"})}var fc=oe(yi,Fd).superRefine(mc),Ai=ce(yi,Fd,{strict:!0}),Md=Ai.omit({packageName:!0,keywords:!0,pageSize:!0}).shape,mC=Fn.object({...Md,packageName:Re(Ai.shape,"packageName")}).strict().superRefine((e,t)=>mc(e,t)),fC=Fn.object({...Md,keywords:Fn.array(Fn.string()).min(1).describe(Se(Ai.shape,"keywords").description??""),pageSize:Se(Ai.shape,"pageSize")}).strict().superRefine((e,t)=>mc(e,t)),hc=X(Fn.union([mC,fC]),{maxQueries:5});import{z as hC}from"zod";var gC=hC.enum(["none","standard","symbols"]).optional(),Nd={startLine:sr,endLine:sr,contextLines:ir.default(5),charOffset:Ye.optional(),charLength:M(1,5e4).optional(),minify:gC},yC=ce(bi,Nd),Zr=oe(bi,Nd),gc=X(xi(yC),{maxQueries:5});import{z as yc}from"zod";var Dd={maxDepth:M(0,100).optional(),minDepth:M(0,100).optional(),limit:M(1,1e4).optional(),page:he.default(1),itemsPerPage:M(1,50).optional(),excludeDir:yc.array(yc.string()).optional()},Hd=yc.object(Object.fromEntries(Object.entries(vt.shape).filter(([e])=>e!=="regexType")));function bC(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 SC=ce(Hd,Dd),RC=oe(Hd,Dd).superRefine(bC),CC=X(SC,{maxQueries:5});var Sc=X(sn,{maxQueries:5});import{z as cn}from"zod";var xC=["paginated","discovery","detailed","structural"],wC=["semanticRanking"],Gd={mode:cn.enum(xC).optional().default("paginated"),searchText:cn.string().optional(),output:cn.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content"),pattern:cn.string().optional(),maxDepth:M(0,20).optional(),rule:cn.string().optional(),captureText:cn.boolean().optional(),contextLines:ir,matchContentLength:M(1,1e5).optional().default(500),maxMatchesPerFile:M(1,1e5).optional(),maxFiles:M(1,1e5).optional(),matchPage:he.optional(),itemsPerPage:M(1,1e3).optional(),page:he.default(1),unique:cn.enum(["off","list","count"]).optional().default("off")},PC={...Gd,semanticRanking:cn.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},TC=ce(at,PC),EC=oe(at,Gd,{strict:!0,omit:wC}),hr=EC.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let n=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(n){let r=n[0].slice(2);t.addIssue({code:"custom",message:`\`${n[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),AC=X(TC,{maxQueries:5});import{z as Bd}from"zod";var zd={excludeDir:Bd.array(Bd.string()).optional(),maxDepth:M(0,20).optional(),limit:M(1,1e4).optional(),page:he.default(1),itemsPerPage:M(1,50).optional()},LC=ce(Ft,zd),_C=oe(Ft,zd),kC=X(LC,{maxQueries:5});import{z as Ud}from"zod";function Rc(e,t){let{pageSize:n,reverse:r,...o}=e,i={...o,...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{sortReverse:r}:{}};return t==="paginated"||t==="discovery"||t==="detailed"?{...i,mode:t}:{...i,mode:"paginated",output:t}}var[IC,OC,vC,FC,MC]=Xa.options,Qd=Ud.enum(["content","files","countMatches"]).optional().default("content").describe("Structural result shape; content is the default."),gr=Ud.union([IC,OC.extend({resultView:Qd}),vC.extend({resultView:Qd}),FC,MC]),Cc=X(gr,{maxQueries:5});import{z as ln}from"zod";var NC=M(1,1e9),DC=M(0,1e5).optional(),HC=["structured","compact"],jd={type:ln.enum(pd).default("definition"),symbolName:ln.string().min(1).max(1024).optional(),lineHint:NC.optional(),orderHint:DC,depth:M(0,20).optional(),includeDeclaration:ln.boolean().optional().default(!0),page:he,pageSize:M(1,100).optional(),contextLines:M(0,100).optional(),format:ln.enum(HC).optional().default("structured")},un=ce(Si,jd),GC=["definition","references","callers","callees","callHierarchy","hover","typeDefinition","implementation","supertypes","subtypes"],BC=["documentSymbols","diagnostic"],zC=un.extend({type:ln.enum(GC).optional(),uri:Re(un.shape,"uri"),symbolName:Re(un.shape,"symbolName"),lineHint:Re(un.shape,"lineHint")}),QC=un.extend({type:ln.enum(BC),uri:Re(un.shape,"uri")}),UC=un.extend({type:ln.literal("workspaceSymbol"),symbolName:Re(un.shape,"symbolName")}),Jr=oe(Si,jd),xc=X(ln.union([zC,QC,UC]),{maxQueries:5});var qr=[{name:mt,title:"GitHub Search",description:je.ghSearch,schema:ar,inputSchema:tc},{name:re.GITHUB_FETCH_CONTENT,title:"GitHub File Content Fetch",description:je.ghGetFileContent,schema:Xr,inputSchema:Ja},{name:de,title:"GitHub History Search",description:je.ghSearchHistory,schema:fr,inputSchema:pc},{name:fe,title:"GitHub History Item",description:je.ghGetHistoryItem,schema:Wt,inputSchema:dc},{name:re.PACKAGE_SEARCH,title:"Package Search",description:je.npmSearch,schema:fc,inputSchema:hc},{name:re.GITHUB_CLONE_REPO,title:"Clone / Fetch GitHub Repository Locally",description:je.ghCloneRepo,schema:Ri,inputSchema:Za},{name:Ue,title:"Local Search",description:je.localSearch,schema:gr,inputSchema:Cc},{name:Mt,title:"Local Analyze Graph",description:je.localAnalyzeGraph,schema:sn,inputSchema:Sc},{name:re.LOCAL_FETCH_CONTENT,title:"Local Fetch Content",description:je.localGetFileContent,schema:Zr,inputSchema:gc},{name:be,title:"Get Semantic Content",description:je.lspGetSemantics,schema:Jr,inputSchema:xc}];var wc=["GitHub","Local Code","Package","Other"],$d=new Map([mt,de,fe,re.GITHUB_FETCH_CONTENT,re.GITHUB_CLONE_REPO,Ue,Mt,re.LOCAL_FETCH_CONTENT,be,re.PACKAGE_SEARCH].map((e,t)=>[e,t])),ft=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},jC=["goal","reasoning"],eo=new Set([...jC]);function $C(e){return{name:e.name,title:e.title,description:e.description,schema:e.schema,inputSchema:e.inputSchema}}var Tc=qr.map(e=>$C(e)),Wd=[...Tc];function We(e){return Tc.find(t=>t.name===e)}function Pc(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===re.PACKAGE_SEARCH?"Package":"Other"}function WC(e){return[...e].sort((t,n)=>{let r=wc.indexOf(Pc(t)),o=wc.indexOf(Pc(n));if(r!==o)return r-o;let i=$d.get(t)??Number.MAX_SAFE_INTEGER,s=$d.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}import{z as Vd}from"zod";var VC=["goal","reasoning"];function KC(e){let t=We(e);if(!t)return"{}";try{return JSON.stringify(Vd.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Vd.toJSONSchema(t.schema,{io:"input"}),null,2)}}function XC(e){return JSON.stringify(e??{},null,2)}function YC(e){return We(e)?[...VC]:[]}function ZC(e,t){return We(e)?.description??e}import{z as Xd}from"zod";function to(e){let t=We(e);if(!t)return[];let n=Xd.toJSONSchema(t.schema,{io:"input"});if(!Nt(n))return[];let r=Lc(n),o=ex(r),i=tx(r,o);return Ec(o,i)}function Yd(e,t){let n=We(e);if(!n)return new Set;let r=Xd.toJSONSchema(n.schema,{io:"input"});if(!Nt(r))return new Set;let o=Lc(r),i=o.filter(a=>JC(a,t)),s=i.length>0?i:o;return new Set(s.flatMap(a=>ht(a.properties)?Object.keys(a.properties):[]))}function JC(e,t){if(!ht(e.properties))return!0;for(let[n,r]of Object.entries(t)){let o=e.properties[n];if(Nt(o)&&("const"in o&&r!==o.const||Array.isArray(o.enum)&&!o.enum.some(i=>i===r)))return!1}return!0}function qC(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 Li(e){if("const"in e)return`enum(${String(e.const)})`;if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Nt(e.items)?e.items:void 0;return`array<${n?Li(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Nt).map(Li).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 Lc(e){return ht(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(Nt).flatMap(n=>Lc(n))}function ex(e){let t=new Map;for(let n of e)if(ht(n.properties))for(let[r,o]of Object.entries(n.properties)){if(!Nt(o))continue;let i=t.get(r)??[];i.push(o),t.set(r,i)}return Object.fromEntries([...t].map(([n,r])=>{let o=r.filter(s=>"const"in s).map(s=>s.const);return o.length===r.length?[n,{enum:[...new Set(o)],description:n==="operation"?"Required operation selector.":r[0]?.description}]:new Set(r.map(Li)).size>1?[n,{anyOf:r}]:[n,r[0]??{}]}))}function tx(e,t){if(e.length===0)return new Set;let n=e.map(o=>new Set(Array.isArray(o.required)?o.required:[])),r=[...n[0]??new Set].filter(o=>n.every(i=>i.has(o)));return new Set(r.filter(o=>!eo.has(o)&&!Ac(t[o])))}function Ec(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&eo.has(o))continue;let s=Nt(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Li(s),constraints:qC(s),description:typeof s.description=="string"?s.description:void 0}),ht(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!Ac(s.properties?.[u]):!1):[]);r.push(...Ec(s.properties,l,a))}let c=s.type==="array"&&Nt(s.items)?s.items:void 0;if(c&&ht(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!Ac(c.properties?.[u]):!1):[]);r.push(...Ec(c.properties,l,a))}}return r}function Zd(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[Kd(e,n)]}return Kd(e,t)}function Kd(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 ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nt(e){return ht(e)}function Ac(e){return Nt(e)&&"default"in e}function Jd(e){return e!==mt?[]:[{label:"code search",query:{operation:"code",keywords:["localSearch"],owner:"bgauryy",repo:"octocode",pageSize:5}},{label:"repository search",query:{operation:"repositories",keywords:["code research"],language:"TypeScript",pageSize:5}},{label:"repository tree",query:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}]}function qd(e){let t=Jd(e);return t.length>0?t:e===de?[{label:"PR search (list)",query:{operation:"pullRequests",owner:"bgauryy",repo:"octocode",keywords:["localSearch"],concise:!0,pageSize:5}},{label:"issue search (list)",query:{operation:"issues",owner:"bgauryy",repo:"octocode",keywords:["schema"],state:"open",pageSize:5}},{label:"commit history",query:{operation:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"6m",pageSize:10}}]:e===re.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===Ue?[{label:"text anchors",query:{operation:"text",path:"/ABS/repo/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural matches",query:{operation:"structural",path:"/ABS/repo/src",pattern:"eval($X)",langType:"typescript"}},{label:"file discovery",query:{operation:"files",path:"/ABS/repo",names:["package.json"],entryType:"f"}},{label:"tree orientation",query:{operation:"tree",path:"/ABS/repo/src",maxDepth:2}}]:e===re.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"/ABS/repo/packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"/ABS/repo/packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===Mt?[{label:"dead code from detected entrypoints",query:{operation:"deadCode",path:"/ABS/repo",limit:20}},{label:"cycles",query:{operation:"cycles",path:"/ABS/repo",limit:20}},{label:"dependencies of one file",query:{operation:"dependencies",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"dependents of one file",query:{operation:"dependents",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"shortest dependency path",query:{operation:"path",path:"/ABS/repo",file:"src/index.ts",target:"src/responses.ts"}},{label:"reachability from detected entrypoints",query:{operation:"reachability",path:"/ABS/repo",limit:20}}]:e===re.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===fe?[{label:"pull request detail",query:{operation:"pullRequest",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,patches:{mode:"all"}}}},{label:"issue detail",query:{operation:"issue",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,comments:{discussion:!0}}}},{label:"exact commit",query:{operation:"commit",owner:"bgauryy",repo:"octocode",ref:"main"}},{label:"compare two refs (base...head)",query:{operation:"compare",owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===re.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{keywords:["schema","validation"],page:1}}]:e===be?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function em(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function nx(e){let t=qd(e);if(t.length>0)return t.map(r=>({...r,command:em(e,r.query)}));let n=ox(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:em(e,n)}]}function rx(e){return nx(e)[0]?.query??{}}function ox(e){if(!We(e))return{};let t=to(e),n=t.filter(i=>!i.name.includes(".")),r=ix(n),o={};for(let i of r)o[i.name]=Zd(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===be&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}var tm=4,_c=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]]),nm=new Set(["page","itemsPerPage","limit","pageSize","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function ix(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&&sx(i)).sort(ax),o=Math.max(tm,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=>!nm.has(i.name)).filter(i=>i.type!=="boolean").slice(0,tm)}function sx(e){return nm.has(e.name)||e.type==="boolean"?!1:cx(e)?_c.has(e.name):!0}function ax(e,t){let n=_c.get(e.name)??Number.MAX_SAFE_INTEGER,r=_c.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function cx(e){return e.constraints?.includes("default ")===!0}import{z as im}from"zod";import{z as lx}from"zod";function _i(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rm(e){return _i(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(_i).flatMap(rm)}function ux(e){let t=We(e)?.schema;if(!t)return new Map;let n=lx.toJSONSchema(t),r=new Map;for(let o of rm(n)){if(!_i(o.properties))continue;let i=o.properties.operation;if(!_i(i)||typeof i.const!="string")continue;let s=r.get(i.const)??new Set;for(let a of Object.keys(o.properties))["goal","reasoning","operation"].includes(a)||s.add(a);r.set(i.const,s)}return new Map([...r].map(([o,i])=>[o,[...i]]))}function kc(e){if(e==="ghSearch"){let[t,...n]=ai(e);return[...t?[t]:[],"code and repositories need at least one search term or scope filter.",...n]}return e==="localSearch"?["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."]:e==="ghSearchHistory"?["Choose pullRequests, issues, or commits; fields cannot cross operations.","issues and commits require owner+repo; pullRequests may search globally.","Search/list operations reject exact identities, content, and diff pagination."]:e==="ghGetHistoryItem"?["Every operation requires owner+repo.","pullRequest and issue need number; commit needs ref; compare needs base+head.","Fields and pagination axes cannot cross operations."]:ai(e)}function om(e){let t=ux(e);return(e==="ghSearchHistory"?[{name:"pullRequests",when:"Search or list pull requests",requires:["operation"],example:{operation:"pullRequests",keywords:["schema"]}},{name:"issues",when:"Search or list issues",requires:["operation","owner","repo"],example:{operation:"issues",owner:"o",repo:"r"}},{name:"commits",when:"List commit history",requires:["operation","owner","repo"],example:{operation:"commits",owner:"o",repo:"r"}}]:e==="ghGetHistoryItem"?[{name:"pullRequest",when:"Retrieve one pull request",requires:["operation","owner","repo","number"],example:{operation:"pullRequest",owner:"o",repo:"r",number:1}},{name:"issue",when:"Retrieve one issue",requires:["operation","owner","repo","number"],example:{operation:"issue",owner:"o",repo:"r",number:1}},{name:"commit",when:"Retrieve one commit",requires:["operation","owner","repo","ref"],example:{operation:"commit",owner:"o",repo:"r",ref:"main"}},{name:"compare",when:"Compare two refs",requires:["operation","owner","repo","base","head"],example:{operation:"compare",owner:"o",repo:"r",base:"main",head:"next"}}]:Ia(e)).map(r=>({...r,...e==="localSearch"&&r.name==="structural"?{requires:["operation","path"]}:{},...e==="lspGetSemantics"&&r.name==="workspace"?{requires:["type","symbolName"]}:{},...t.has(r.name)?{fields:t.get(r.name)}:{}}))}function px(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new ft("Tool input must be valid JSON.")}return sm(e,r,n)}function sm(e,t,n={}){let r=fx(e,t,n),o=We(e);if(!o)throw new ft(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new ft("Check the query fields.",[...dx(e),...mx(i.error)]);return i.data}function dx(e){if(e==="npmSearch")return kc(e).slice(0,1);if(e==="localSearch"){let t=om(e).map(n=>n.name);return t.length>0?[`operation must be one of ${t.map((n,r)=>r===t.length-1&&t.length>1?`or ${n}`:n).join(", ")}.`]:[]}if(e==="lspGetSemantics"){let t=kc(e);return t.length>0?[t.join(" ")]:[]}return[]}function mx(e){let t=n=>{let r=n.errors;if(n.code!=="invalid_union"||!Array.isArray(r))return[n];let o=r.filter(s=>Array.isArray(s));return o.length===0?[n]:o.reduce((s,a)=>a.length<s.length?a:s).map(s=>({...s,path:[...n.path,...s.path]}))};return e.issues.flatMap(t).map(n=>`${n.path.length>0?n.path.join("."):"input"}: ${n.message}`)}function fx(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(ht(t)&&Array.isArray(t.queries))r=t.queries;else if(ht(t))r=[t];else throw new ft('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new ft("At least one query is required.");let o=ht(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>hx(e,Rx(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function hx(e,t,n){let r={...t},o=n.sourceLabel??"direct tool execution",i=gx(e,o);return(typeof r.goal!="string"||r.goal.trim().length===0)&&(r.goal=i),(typeof r.reasoning!="string"||r.reasoning.trim().length===0)&&(r.reasoning=`Executed via ${o} tool command`),r}function gx(e,t){return`Execute ${e} via ${t}`}function yx(e,t){let n=e.length+1,r=t.length+1,o=Array.from({length:n*r},()=>0);for(let i=0;i<n;i++)o[i*r]=i;for(let i=0;i<r;i++)o[i]=i;for(let i=1;i<n;i++)for(let s=1;s<r;s++){let a=e[i-1]===t[s-1]?0:1;o[i*r+s]=Math.min(o[(i-1)*r+s]+1,o[i*r+s-1]+1,o[(i-1)*r+s-1]+a)}return o[n*r-1]}function bx(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),l=yx(n,c);if(c.includes(n)||n.includes(c)){l<o&&(r=a,o=l);continue}if(n.length<3)continue;let u=Math.max(2,Math.floor(a.length/3));l<=u&&l<s&&(i=a,s=l)}return r??i}var Sx={npmSearch:{name:"packageName"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri",itemsPerPage:"pageSize",limit:""},localGetFileContent:{filePath:"path"},localSearch:{itemsPerPage:"pageSize",maxResults:["maxFiles","limit","pageSize"],keywords:"searchText",language:"langType",regexType:"regex",sortBy:"sort",sortReverse:"reverse"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:"minify"},ghSearch:{itemsPerPage:"pageSize",limit:"",topicsToSearch:"topics"},localAnalyzeGraph:{itemsPerPage:"pageSize",maxResults:"limit",maxDepth:"depth"}};function Rx(e,t,n,r={}){if(!ht(t))throw new ft("Tool input must be a JSON object or an array of objects.");let o=new Set([...to(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...am(We(e)?.schema),...eo]),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)){let a=Yd(e,t),c=s.map(l=>{let u=Sx[e]?.[l],d=(Array.isArray(u)?u:u===void 0?[]:[u]).find(m=>a.has(m))??bx(l,a);return d?`'${l}' \u2192 did you mean '${d}'?`:""}).filter(Boolean);throw new ft(`Unknown field(s): ${s.join(", ")}`,[...c,`Remove unknown field(s) from query ${n+1}: ${s.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return i}function am(e){if(!e)return[];if(e instanceof im.ZodObject)return Object.keys(e.shape);let t=e.options,n=e instanceof im.ZodUnion?e.options:Array.isArray(t)?t:[];return n.length>0?[...new Set(n.flatMap(r=>am(r)))]:[]}function pn(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function yr(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 ki(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var no=new Map,Cx=300*1e3;function xx(e){let t=pn(e),n=no.get(t);return!n||Date.now()-n.cachedAt>=Cx?!1:n.credentials?!yr(n.credentials):!0}function Ic(e){e?no.delete(pn(e)):no.clear()}function cm(e){let t=pn(e);if(xx(t))return no.get(t).credentials}function lm(e,t){let n=pn(e);no.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as dm,readFileSync as mm,writeFileSync as fm,unlinkSync as oD,statSync as _x,chmodSync as kx}from"node:fs";import{createCipheriv as Ix,createDecipheriv as Ox,randomBytes as hm}from"node:crypto";import{existsSync as wx,mkdirSync as Px}from"node:fs";import{join as gt}from"node:path";import{getOctocodeHome as Tx}from"@octocodeai/config";var Ex=448;function ro(){return Tx(process.env)}function Dt(){return Je}var Je=ro(),Vt={home:Je,config:gt(Je,".octocoderc"),credentials:gt(Je,"credentials.json"),key:gt(Je,".key"),session:gt(Je,"session.json"),stats:gt(Je,"stats.json"),tmp:gt(Je,"tmp"),clone:gt(Je,"tmp","clone"),tree:gt(Je,"tmp","tree"),response:gt(Je,"tmp","response"),repos:gt(Je,"tmp","clone"),cliConfig:gt(Je,"config.json"),lspConfig:gt(Je,"lsp-servers.json")};function um(){wx(Vt.home)||Px(Vt.home,{recursive:!0,mode:Ex})}import{z as Oe}from"zod";var Ax=Oe.object({token:Oe.string(),tokenType:Oe.literal("oauth"),scopes:Oe.array(Oe.string()).optional(),refreshToken:Oe.string().optional(),expiresAt:Oe.string().optional(),refreshTokenExpiresAt:Oe.string().optional()}),Lx=Oe.object({hostname:Oe.string(),username:Oe.string(),token:Ax,gitProtocol:Oe.enum(["ssh","https"]),createdAt:Oe.string(),updatedAt:Oe.string()}),pm=Oe.object({version:Oe.number(),credentials:Oe.record(Oe.string(),Lx)});var gm=Vt.home,oo=Vt.credentials,Nn=Vt.key,ym="aes-256-gcm",vx=16;function Dn(){um()}function bm(){if(Dn(),dm(Nn))return _x(Nn).mode&511&63&&kx(Nn,384),Buffer.from(mm(Nn,"utf8"),"hex");let e=hm(32);return fm(Nn,e.toString("hex"),{mode:384}),e}function Oc(e){let t=bm(),n=hm(vx),r=Ix(ym,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 vc(e){let t=bm(),[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=Ox(ym,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function Ii(){if(Dn(),!dm(oo))return{version:1,credentials:{}};try{let e=mm(oo,"utf8"),t=vc(e),n=JSON.parse(t),r=pm.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Sm(e){Dn();let t=Oc(JSON.stringify(e,null,2));fm(oo,t,{mode:384})}import{refreshToken as Fx}from"@octokit/oauth-methods";import{request as Mx}from"@octokit/request";var io="178c6fc778ccc68e1d6a",br="github.com";function Nx(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 Dx(e){return e==="github.com"||e===br?"https://api.github.com":`https://${e}/api/v3`}async function Rm(e,t=br,n=io){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(ki(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Fx({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:Mx.defaults({baseUrl:Dx(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?Nx(o.message):"Token refresh failed"}}}async function Cm(e,t=br,n=io){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!yr(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Rm(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as Bx}from"@octocodeai/config";import{execFile as Hx}from"child_process";var Gx=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Fc(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=Gx.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Hx("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Mc=null;function xm(e){Mc=e}function zx(){if(!Mc)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Mc}async function Oi(e){let t=e?.hostname??br,n=e?.clientId??io,r=e?.getGhCliToken??Fc,o=Bx();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await zx().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)}
21
- `)}return null}async function wm(e){let t=pn(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Ii();return r.credentials[t]=n,Sm(r),Ic(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Nc(e="github.com",t){let n=pn(e);if(!t?.bypassCache){let i=cm(n);if(i!==void 0)return i}let o=Ii().credentials[n]||null;return lm(n,o),o}async function Pm(e,t){let n=await Nc(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await wm(n),!0):!1}async function Tm(e,t){return Cm({getCredentials:Nc,updateToken:Pm},e,t)}xm({getTokenWithRefresh:Tm});import vi from"node:os";import $D from"node:path";var $x=vi.platform()==="win32",Wx=vi.platform()==="darwin",Vx=vi.platform()==="linux",Kx=vi.homedir();import{randomUUID as SH}from"node:crypto";import{existsSync as km,readFileSync as Im,writeFileSync as qx,unlinkSync as rH,renameSync as ew}from"node:fs";import{isPersistentStorageEnabled as Om,isStatsEnabled as vm}from"@octocodeai/config";import{z as Y}from"zod";var Xx=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),Yx=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),Fi=Y.record(Y.string(),Y.number()).default({}),Zx=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:Fi,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:Fi}),Mi=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:Fi,charsSavedByTool:Y.record(Y.string(),Xx).default({}),githubCacheHits:Yx.default({hits:{},rateLimits:0}),packageRegistryFailures:Fi,totalUsage:Zx.optional()}),Em=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:Mi.optional()}),Am=Y.object({version:Y.literal(1),stats:Mi});function Lm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Jx(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:Lm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Lm(o),packageRegistryFailuresByRegistry:o}}function dn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Jx(t)}}function Sr(){return dn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var so=Vt.session,ao=Vt.stats;function _m(e,t){let n=`${e}.tmp`;qx(n,JSON.stringify(t,null,2),{mode:384}),ew(n,e)}function tw(e){let t=JSON.parse(e),n=Am.safeParse(t);if(n.success)return dn(n.data.stats);let r=Mi.safeParse(t);return r.success?dn(r.data):null}function nw(){if(!km(ao))return Sr();try{let e=Im(ao,"utf8");return tw(e)??Sr()}catch{return Sr()}}function Dc(e){if(!Om())return;Dn(),vm()&&_m(ao,{version:e.version,stats:dn(e.stats)});let{stats:t,...n}=e;_m(so,n)}function Fm(){if(!Om()||!km(so))return null;try{let e=Im(so,"utf8"),t=JSON.parse(e),n=Em.safeParse(t);return n.success?{...n.data,stats:vm()?nw():Sr()}:null}catch{return null}}var rw=6e4,mn=null,co=!1,Hc=null,Mm=!1,Nm=null,Dm=null,Hm=null,Gc=!1;function ow(){Mm||(Mm=!0,Nm=()=>{Ni()},Dm=()=>{Ni()},Hm=()=>{Ni()},process.on("exit",Nm),process.on("SIGINT",Dm),process.on("SIGTERM",Hm))}function iw(){Hc||(Hc=setInterval(()=>{co&&mn&&(Dc(mn),co=!1)},rw),Hc.unref())}function Gm(){if(mn)return mn;let e=Fm();return e&&(mn=e),e}function Bm(e){mn=e,co=!0,ow(),iw()}function Ni(){if(!Gc&&co&&mn){Gc=!0;try{Dc(mn),co=!1}catch{}finally{Gc=!1}}}function sw(e){return dn(e)}function aw(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 zm(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 cw(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 fn(e){let t=Gm();if(!t)return{success:!1,session:null};let n=sw(t.stats),r=dn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:zm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:aw(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:cw(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:zm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Bm(o),{success:!0,session:o}}function Bc(e=1){return fn({rateLimits:e})}function zc(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return fn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function Qc(e,t=1){return fn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function Uc(e=1){return fn({githubCacheHits:{hits:{},rateLimits:e}})}import{z as Ce}from"zod";var lw=Ce.looseObject({$schema:Ce.string().optional(),version:Ce.number().int().optional(),github:Ce.record(Ce.string(),Ce.unknown()).optional(),local:Ce.record(Ce.string(),Ce.unknown()).optional(),tools:Ce.record(Ce.string(),Ce.unknown()).optional(),network:Ce.record(Ce.string(),Ce.unknown()).optional(),lsp:Ce.record(Ce.string(),Ce.unknown()).optional(),output:Ce.record(Ce.string(),Ce.unknown()).optional()});import{existsSync as uw,readdirSync as pw,lstatSync as dw}from"node:fs";import{join as mw}from"node:path";function Di(e){if(!uw(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=pw(r)}catch{continue}for(let i of o){let s=mw(r,i);try{let a=dw(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}import{getConfigSync as wf}from"@octocodeai/config";var Hn="18.2.0";var jc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},lo={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"}},uo={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})`}},hw={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"}},hn={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}`}},gn={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"}},Ve={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}`}},gw={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}`}},po={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},yw={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}`}},oG={...jc,...lo,...uo,...hw,...hn,...gn,...Ve,...gw,...po,...yw};import{maskSensitiveData as EP}from"@octocodeai/octocode-engine/mask";import{mkdirSync as gf,readFileSync as hP,renameSync as Sf,rmSync as Rf,statSync as gP,writeFileSync as yP}from"node:fs";import{join as Jc}from"node:path";import{isPersistentStorageEnabled as bP}from"@octocodeai/config";import{existsSync as go,readFileSync as Lw,writeFileSync as _w,mkdirSync as kw,rmSync as ho,readdirSync as Iw,statSync as Ow}from"node:fs";import{join as yn}from"node:path";import{join as Hi}from"node:path";import{createHash as Qm}from"node:crypto";function Gi(e){return Hi(e,"tmp","clone")}function Bi(e){return Hi(e,"tmp","tree")}function bw(e){return e?`__sp_${Qm("sha256").update(e).digest("hex").substring(0,6)}`:""}function Sw(e){if(!/[\\/]/.test(e))return e;let t=Qm("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function $c(e,t,n,r,o){let i=`${Sw(r)}${bw(o)}`;return Hi(Gi(e),t,n,i)}function mo(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new Error("Tree cache identity must be a 40-character commit SHA.");return Hi(Bi(e),t,n,r.toLowerCase())}import{readFileSync as Rw,readdirSync as Cw,renameSync as xw,rmSync as $m,statSync as Wm,writeFileSync as ww}from"node:fs";import{join as Rr}from"node:path";var Pw=900*1e3,Um=300*1e3,Vm=".octocode-lock.json";function Tw(e){return typeof e=="object"&&e!==null}function jm(e){try{return Cw(e)}catch{return[]}}function Wc(e,t=process.pid,n=Date.now()){try{ww(Rr(e,Vm),JSON.stringify({pid:t,createdAt:n}),{encoding:"utf8",mode:384})}catch{}}function Ew(e){try{let t=JSON.parse(Rw(Rr(e,Vm),"utf8"));return!Tw(t)||!Number.isInteger(t.pid)||t.pid<=0||typeof t.createdAt!="number"?null:{pid:t.pid,createdAt:t.createdAt}}catch{return null}}function Aw(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function zi(e,t=Date.now()){let n,r=Ew(e);if(r){if(n=r.createdAt,t-n<=Um||Aw(r.pid))return!1}else{try{n=Wm(e).mtimeMs}catch{return!1}if(t-n<=Um)return!1}let o=`${e}.stale-${process.pid}-${t}`;try{return xw(e,o),$m(o,{recursive:!0,force:!0}),!0}catch{return!1}}function Vc(e,t=Date.now()){let n=Rr(e,"tmp","clone-tmp"),r=0;for(let i of jm(n)){let s=Rr(n,i);try{let a=Wm(s);if(t-a.mtimeMs<=Pw)continue;$m(s,{recursive:!0,force:!0}),r++}catch{}}let o=Rr(e,"tmp","clone-locks");for(let i of jm(o))zi(Rr(o,i),t)&&r++;return r}var vw=1440*60*1e3,Fw=2*1024*1024*1024,Mw=50,Xm=".octocode-clone-meta.json";function Nw(e){return typeof e=="object"&&e!==null}function Dw(e){if(!Nw(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 Kc(e){let t=yn(e,Xm);if(!go(t))return null;try{return Dw(JSON.parse(Lw(t,"utf-8")))}catch{return null}}function Cr(e,t){try{_w(yn(e,Xm),JSON.stringify(t,null,2),"utf-8")}catch{}}function Ym(e){return Date.now()<new Date(e.expiresAt).getTime()}function xr(e){let t=Kc(e);return t?Ym(t)?go(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Hw(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return vw}function Gw(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Fw}function Bw(){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 Mw}function wr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Hw()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function bn(e){let t=yn(e,"..");try{go(t)||kw(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 Qi(e){try{go(e)&&ho(e,{recursive:!0,force:!0})}catch{}}function fo(e){try{return Ow(e).isDirectory()}catch{return!1}}function Gn(e){try{return Iw(e)}catch{return[]}}function*Zm(e){for(let t of Gn(e)){let n=yn(e,t);if(fo(n))for(let r of Gn(n)){let o=yn(n,r);if(fo(o))for(let i of Gn(o)){let s=yn(o,i);fo(s)&&(yield s)}}}}function Km(e){for(let t of[...Gn(e)]){let n=yn(e,t);if(fo(n)){for(let r of[...Gn(n)]){let o=yn(n,r);if(fo(o)&&Gn(o).length===0)try{ho(o,{recursive:!0,force:!0})}catch{}}if(Gn(n).length===0)try{ho(n,{recursive:!0,force:!0})}catch{}}}}function zw(e){let t=0;for(let n of Zm(e))try{let r=Kc(n);(!r||!Ym(r))&&(ho(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Qw(e){let t=[];for(let n of Zm(e)){let r=Kc(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??Di(n)})}return t}function Uw(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{ho(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Jm(e){if(!go(e))return 0;let t=0;try{t+=zw(e)}catch{return t}Km(e);let n=Uw(Qw(e),Gw(),Bw());return t+=n,n>0&&Km(e),t}function Ui(e){return Jm(Gi(e))}function Pr(e){return Jm(Bi(e))}import jw from"crypto";var $w="v2",Ww=new Set([]);function Vw(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(Ww.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Ee(e,t,n){let r=Xc(Vw(t)),o=n?`${n}:${r}`:r,i=jw.createHash("sha256").update(o).digest("hex");return`${$w}-${e}:${i}`}function Xc(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=>Xc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Xc(i,t)}`}).join(",")}}`)}import Kw from"node-cache";var Xw=300*1e3,At=new Kw({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),qe={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},qm={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},ct=new Map;function Yw(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Zw(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Bn(e){let t=Yw(e);if(!(!t||!Zw(t)))try{Qc(t,1)}catch{}}function ji(){let e=Date.now();for(let[t,n]of ct.entries())e-n.startedAt>Xw&&ct.delete(t)}function $i(e){return qm[e]||qm.default}function zn(e,t,n){try{return At.set(e,t,n),qe.sets++,qe.totalKeys=At.keys().length,!0}catch{try{let r=At.keys();for(let o of r)At.get(o);return At.set(e,t,n),qe.sets++,qe.totalKeys=At.keys().length,!0}catch{return!1}}}import{createHash as Jw}from"node:crypto";import{chmod as ef,mkdir as nf,readFile as rf,readdir as qw,rename as tf,rm as eP,stat as Yc,writeFile as of}from"node:fs/promises";import{join as yo}from"node:path";import{isPersistentStorageEnabled as tP}from"@octocodeai/config";var sf=1,af=5*1024*1024,nP=5e3,rP=256*1024*1024,oP=1440*60*1e3,iP=900*1e3,cf=".last-gc",lt={hits:0,misses:0,sets:0,errors:0,evictions:0};function Wi(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Zc(){if(!tP())return!1;let e=process.env.OCTOCODE_DISK_CACHE?.trim().toLowerCase();return!(e==="false"||e==="0")}function lf(e=ro()){return yo(e,"tmp","response")}function sP(e){return(e.match(/^v\d+-([^:]+):/)?.[1]??"default").replace(/[^a-zA-Z0-9._-]/g,"_")}function uf(e,t=ro()){let n=Jw("sha256").update(e).digest("hex");return yo(lf(t),sP(e),n.slice(0,2),`${n}.json`)}function pf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aP(e,t){let n;try{n=JSON.parse(e)}catch{return null}return!pf(n)||n.version!==sf||n.key!==t||typeof n.createdAt!="number"||typeof n.expiresAt!="number"||typeof n.staleUntil!="number"||!("value"in n)||n.etag!==void 0&&typeof n.etag!="string"?null:n}async function Sn(e){try{await eP(e,{force:!0,recursive:!0})}catch{}}async function Vi(e,t={}){if(!Zc())return;let n=uf(e);try{let r=await Yc(n);if(!r.isFile()||r.size>Wi("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",af)){await Sn(n),lt.errors++;return}let o=aP(await rf(n,"utf8"),e);if(!o){await Sn(n),lt.errors++;return}let i=Date.now();if(i>=o.staleUntil){await Sn(n),lt.evictions++,lt.misses++;return}if(i>=o.expiresAt&&!t.allowStale){lt.misses++;return}return lt.hits++,{value:o.value,...o.etag?{etag:o.etag}:{},state:i<o.expiresAt?"fresh":"stale",expiresAt:o.expiresAt}}catch(r){r.code!=="ENOENT"&&lt.errors++,lt.misses++;return}}async function bo(e,t,n,r={}){if(!Zc())return!1;let o=Date.now(),i=Math.max(1,n*1e3),s=Math.max(i,(r.staleTtlSeconds??n)*1e3),a={version:sf,key:e,createdAt:o,expiresAt:o+i,staleUntil:o+s,value:t,...r.etag?{etag:r.etag}:{}},c;try{c=JSON.stringify(a)}catch{return lt.errors++,!1}if(c===void 0||Buffer.byteLength(c)>Wi("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",af))return!1;let l=uf(e),u=yo(l,".."),p=`${l}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{await nf(u,{recursive:!0,mode:448}),await ef(u,448),await of(p,c,{encoding:"utf8",mode:384}),await ef(p,384);try{await tf(p,l)}catch(d){let m=d.code;if(m!=="EEXIST"&&m!=="EPERM")throw d;await Sn(l),await tf(p,l)}return lt.sets++,!0}catch{return lt.errors++,await Sn(p),!1}}async function cP(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=await qw(r,{withFileTypes:!0})}catch{continue}for(let i of o){let s=yo(r,i.name);i.isDirectory()?n.push(s):i.isFile()&&i.name!==cf&&t.push(s)}}return t}async function lP(e,t,n){if(!Zc())return 0;let r=lf(e),o=yo(r,cf);if(n)try{let p=await Yc(o);if(t-p.mtimeMs<oP)return 0}catch{}let i=0,s=await cP(r),a=Wi("OCTOCODE_DISK_CACHE_MAX_ENTRIES",nP),c=Wi("OCTOCODE_DISK_CACHE_MAX_SIZE",rP),l=[],u=0;for(let p of s)try{let d=await Yc(p);if(p.includes(".tmp-")){t-d.mtimeMs>iP&&(await Sn(p),i++);continue}let m=await rf(p,"utf8"),f;try{f=JSON.parse(m)}catch{f=null}if(!pf(f)||typeof f.staleUntil!="number"||t>=f.staleUntil){await Sn(p),i++;continue}l.push({path:p,size:d.size,modified:d.mtimeMs}),u+=d.size}catch{}for(l.sort((p,d)=>p.modified-d.modified);l.length>a||u>c;){let p=l.shift();if(!p)break;await Sn(p.path),u-=p.size,i++}try{await nf(r,{recursive:!0,mode:448}),await of(o,String(t),{encoding:"utf8",mode:384})}catch{lt.errors++}return lt.evictions+=i,i}function df(e=ro(),t=Date.now()){return lP(e,t,!1)}import{AsyncLocalStorage as uP}from"node:async_hooks";var Ki=new uP;async function mf(e){let t={hit:!1};return{value:await Ki.run({root:t,depth:0,role:"response"},e),cacheHit:t.hit}}function Xi(e,t="response"){let n=Ki.getStore();return n?Ki.run({root:n.root,depth:n.depth+1,role:t},e):e()}function Kt(){let e=Ki.getStore();e&&e.depth<=1&&e.role==="response"&&(e.root.hit=!0)}function pP(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return $i(n?.[1]??"default")}async function Fe(e,t,n={}){return Xi(()=>dP(e,t,n),n.cacheRole)}async function dP(e,t,n){if(n.skipCache)return await t();if(!n.forceRefresh){try{let a=At.get(e);if(a!==void 0)return qe.hits++,Bn(e),Kt(),a}catch{}let s=await Vi(e);if(s?.state==="fresh")return qe.hits++,Bn(e),Kt(),zn(e,s.value,Math.max(1,(s.expiresAt-Date.now())/1e3)),s.value}ji();let r=ct.get(e);if(r)return r.promise;let o=Symbol(e),i=(async()=>{try{let s=await t();if(n.forceRefresh||qe.misses++,(n.shouldCache??(()=>!0))(s)){let c=pP(e,n.ttl);zn(e,s,c),await bo(e,s,c)}return s}finally{ct.get(e)?.requestId===o&&ct.delete(e)}})();return ct.set(e,{promise:i,startedAt:Date.now(),requestId:o}),i}import mP from"node-cache";var ff=86400;function hf(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return $i(n?.[1]??"default")}var Yi=new mP({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function Zi(e,t,n={}){return Xi(()=>fP(e,t,n),n.cacheRole)}async function fP(e,t,n){if(n.skipCache)return(await t({})).value;let r;if(!n.forceRefresh){try{let a=At.get(e);if(a!==void 0)return qe.hits++,Bn(e),Kt(),a}catch{}if(r=await Vi(e,{allowStale:!0}),r?.state==="fresh")return qe.hits++,Bn(e),Kt(),zn(e,r.value,Math.max(1,(r.expiresAt-Date.now())/1e3)),r.etag&&Yi.set(e,{data:r.value,etag:r.etag}),r.value}ji();let o=ct.get(e);if(o)return o.promise;let i=Symbol(e),s=(async()=>{try{let c=(n.forceRefresh?void 0:Yi.get(e))??(r?{data:r.value,etag:r.etag}:void 0),l=await t({ifNoneMatch:!n.forceRefresh&&c?.etag?c.etag:void 0});if(l.notModified&&c){qe.hits++,Bn(e),Kt();let p=hf(e,n.ttl);return zn(e,c.data,p),await bo(e,c.data,p,{...c.etag?{etag:c.etag}:{},staleTtlSeconds:ff}),c.data}if(n.forceRefresh||qe.misses++,(n.shouldCache??(()=>!0))(l.value)){let p=hf(e,n.ttl);zn(e,l.value,p),Yi.set(e,{data:l.value,etag:l.etag}),await bo(e,l.value,p,{...l.etag?{etag:l.etag}:{},staleTtlSeconds:ff})}return l.value}finally{ct.get(e)?.requestId===i&&ct.delete(e)}})();return ct.set(e,{promise:s,startedAt:Date.now(),requestId:i}),s}var yf=1440*60*1e3,sB=60*1e3,SP=900*1e3,RP=".last-cache-maintenance",CP=".cache-maintenance.lock";var Ji=new Map;function Cf(e){return Jc(e,"tmp")}function xf(e){return Jc(Cf(e),RP)}function xP(e){try{let t=Number(hP(xf(e),"utf8"));return Number.isFinite(t)&&t>=0?t:null}catch{return null}}function bf(e,t=Date.now()){let n=xP(e);return n===null?0:Math.min(yf,Math.max(0,n+yf-t))}function wP(e,t){let n=Cf(e),r=Jc(n,CP);try{gf(n,{recursive:!0,mode:448})}catch{return null}let o=()=>{try{return gf(r,{mode:448}),!0}catch{return!1}};if(o())return r;try{if(t-gP(r).mtimeMs<=SP)return null;let i=`${r}.stale-${process.pid}-${t}`;Sf(r,i),Rf(i,{recursive:!0,force:!0})}catch{return null}return o()?r:null}function PP(e,t){let n=xf(e),r=`${n}.tmp-${process.pid}-${t}`;yP(r,String(t),{encoding:"utf8",mode:384}),Sf(r,n)}async function TP(e,t){if(bf(e,t)>0)return!1;let n=wP(e,t);if(!n)return!1;try{if(bf(e,t)>0)return!1;try{return Ui(e),Pr(e),Vc(e,t),await df(e,t),PP(e,t),!0}catch{return!1}}finally{try{Rf(n,{recursive:!0,force:!0})}catch{}}}function qi(e,t=Date.now()){if(!bP())return Promise.resolve(!1);let n=Ji.get(e);if(n)return n;let r=TP(e,t).finally(()=>{Ji.get(e)===r&&Ji.delete(e)});return Ji.set(e,r),r}var Ro=null,So=null,AP=Oi;var LP=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function Pf(){try{let e=await AP({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:LP.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Tf(){if(Ro!==null)return;if(So!==null)return So;let e=(async()=>{let t=wf(),n=await Pf();Ro={version:Hn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone&&t.storage.mode==="persistent",tokenSource:n.source},await qi(Dt())})();So=e;try{await e}catch(t){throw So===e&&(Ro=null,So=null),t}}function es(){if(!Ro){let e=EP(jc.NOT_INITIALIZED.message);throw new Error(e)}return Ro}async function qc(){return(await Pf()).token}function Ef(){let e=es();return e.enableLocal&&e.enableClone}function el(){return"github"}function tl(){let e=wf().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as oT}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as _P}from"node:module";var kP=_P(import.meta.url),Af="@octocodeai/octocode-engine",IP=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??kP(Af),ts,OP=IP,nl=class extends Error{constructor(n){super(`Failed to load native dependency ${Af}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function ee(){if(ts)return ts;try{return ts=OP(),ts}catch(e){throw new nl(e)}}var D={applyContentViewMinification(e,t){return ee().applyContentViewMinification(e,t)},applyMinification(e,t){return ee().applyMinification(e,t)},minifyContent(e,t){return ee().minifyContent(e,t)},minifyContentSync(e,t){return ee().minifyContentSync(e,t)},minifyContentResult(e,t){return ee().minifyContentResult(e,t)},minifyMarkdownCore(e){return ee().minifyMarkdownCore(e)},extractSignatures(e,t){return ee().extractSignatures(e,t)},extractJsSymbols(e,t){return ee().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ee().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ee().extractGraphFacts(e,t)},scanGraphFacts(e){return ee().scanGraphFacts(e)},getSupportedJsTsExtensions(){return ee().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ee().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ee().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ee().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ee().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return ee().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return ee().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return ee().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ee().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ee().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ee().parseRipgrepJson(e,t)},searchRipgrep(e){return ee().searchRipgrep(e)},queryFileSystem(e){return ee().queryFileSystem(e)},extractMatchingLines(e,t,n){return ee().extractMatchingLines(e,t,n)},filterPatch(e,t){return ee().filterPatch(e,t)},computeLineDiff(e,t){return ee().computeLineDiff(e,t)},charToByteOffset(e,t){return ee().charToByteOffset(e,t)},byteToCharOffset(e,t){return ee().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ee().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ee().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ee().SIGNATURES_ONLY_HINT}};import{Octokit as vP}from"octokit";import{throttling as FP}from"@octokit/plugin-throttling";import{createHash as MP}from"crypto";function Rn(e){(e.provider?fn({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Bc(1)).session&&e.provider==="github"&&Uc(1)}function Lf(e){fn({packageRegistryFailures:{[e]:1}})}function vf(e){return MP("sha256").update(e).digest("hex").substring(0,16)}async function ve(e){let t=e?.token??await qc(),n=t?vf(t):"anon",r=es().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var NP=vP.plugin(FP),DP=300*1e3,rl=50,HP=60*1e3;function Ff(e){return Date.now()-e.createdAt>DP}var Xt=new Map,Co=null;function Mf(){for(let[e,t]of Xt.entries())Ff(t)&&Xt.delete(e);if(Xt.size>rl){let e=Xt.size-rl,t=0;for(let[n]of Xt){if(t>=e)break;Xt.delete(n),t++}}}function GP(){Co||(Co=setInterval(Mf,HP),typeof Co=="object"&&"unref"in Co&&Co.unref())}var _f=3,kf=60;function If(e,t,n){Rn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var BP=()=>({onRateLimit:(e,t,n,r)=>(If("primary",e,t),r<_f&&e<kf),onSecondaryRateLimit:(e,t,n,r)=>(If("secondary",e,t),r<_f&&e<kf)});function zP(e){let t=es(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Hn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:BP(),log:r,...e&&{auth:e}};return new NP(o)}async function j(e){GP();let t=e?.token??await qc(),n=t?vf(t):"ANONYMOUS",r=Xt.get(n);if(r&&!Ff(r))return r.client;Xt.size>=rl&&Mf();let o=zP(t??void 0);return Xt.set(n,{client:o,createdAt:Date.now()}),o}var QP=200,UP=300*1e3,Tr=new Map;async function Me(e,t,n){let o=`${await ve(n)}:${e}/${t}`,i=Tr.get(o);if(i&&i.expiresAt>Date.now())return i.branch;i&&Tr.delete(o);let s=await j(n);try{let{data:c}=await s.rest.repos.get({owner:e,repo:t}),l=c.default_branch;return Of(o,l),l}catch{}let a=["main","master"];for(let c of a)try{return await s.rest.repos.getBranch({owner:e,repo:t,branch:c}),Of(o,c),c}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Of(e,t){if(Tr.size>=QP){let n=Tr.keys().next().value;n!==void 0&&Tr.delete(n)}Tr.set(e,{branch:t,expiresAt:Date.now()+UP})}import{RequestError as Df}from"octokit";var V={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"},_e={[V.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."},[V.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."},[V.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},[V.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)."},[V.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."},[V.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."},[V.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."},[V.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."},[V.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."},[V.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Nf={401:V.AUTH_REQUIRED,403:V.FORBIDDEN_PERMISSIONS,404:V.NOT_FOUND,422:V.INVALID_REQUEST,502:V.SERVER_UNAVAILABLE,503:V.SERVER_UNAVAILABLE,504:V.SERVER_UNAVAILABLE},ol={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},il={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ns={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var jP=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function Ht(e){if(!(e instanceof Df)||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 jP.some(o=>r.includes(o))})}function J(e){return e instanceof Df?$P(e):e instanceof Error?qP(e):{error:typeof e=="string"?e:_e[V.UNKNOWN].message,type:"unknown"}}function $P(e){let{status:t,message:n,response:r}=e;if(t===403)return VP(n,r);if(t===429)return WP(n,r);let o=Nf[t];return o?JP(o,t):Er(V.UNKNOWN,{error:n||_e[V.UNKNOWN].message,status:t})}function sl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function WP(e,t){let n=t?.headers,r=sl(n,"retry-after"),o=sl(n,"x-ratelimit-reset"),i=sl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ns.RESET_BUFFER_SECONDS,0):void 0);return Rn({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Er(V.RATE_LIMIT_PRIMARY,{error:e||_e[V.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:_e[V.RATE_LIMIT_PRIMARY].suggestion})}function VP(e,t){let n=t?.headers;if(il.SECONDARY.test(e))return KP(n);let r=n?.["x-ratelimit-remaining"],o=ZP(t);return r!==void 0&&String(r)==="0"||o?XP(n):YP(n)}function KP(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ns.SECONDARY_FALLBACK_SECONDS:t;return Rn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Er(V.RATE_LIMIT_SECONDARY,{error:_e[V.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:_e[V.RATE_LIMIT_SECONDARY].suggestion})}function XP(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)+ns.RESET_BUFFER_SECONDS,0):void 0,i=r?_e[V.RATE_LIMIT_PRIMARY].messageWithTime(r,o):_e[V.RATE_LIMIT_PRIMARY].messageWithoutTime;return Rn({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Er(V.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:_e[V.RATE_LIMIT_PRIMARY].suggestion})}function YP(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=_e[V.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=eT(String(t),String(n))),Er(V.FORBIDDEN_PERMISSIONS,{error:_e[V.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function ZP(e){return e?.data?.errors?.some(n=>n.type===il.GRAPHQL_TYPE)??!1}function JP(e,t){let n=_e[e];return Er(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function qP(e){return ol.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:_e[V.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:_e[V.NETWORK_CONNECTION_FAILED].suggestion}:ol.TIMEOUT.some(t=>e.message.includes(t))?{error:_e[V.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:_e[V.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Er(e,t){return{type:"http",...t}}function eT(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?_e[V.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):_e[V.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Hf(e){return`user:${e}`}var tT=/[@/]/,nT=/^[A-Za-z0-9_-]+$/;function al(e){return e.startsWith('"')||nT.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var Yt=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(Hf(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=tT.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var rT=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,cl=class extends Yt{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(al))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(rT):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 Yt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(al)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars");let n=t;return typeof n.size=="string"&&this.queryParts.push(`size:${n.size}`),typeof n.created=="string"&&this.queryParts.push(`created:${n.created}`),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`),typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function ul(e){return new cl().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function pl(e){return new ll().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var dl=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function ml(e){return new dl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function fl(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var hl=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function gl(e){return new hl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function yl(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as WB,DISCOVERY_IGNORED_FILE_NAMES as VB,DISCOVERY_IGNORED_FOLDER_NAMES as KB,getDiscoveryExtension as Gf,shouldIgnoreDiscoveryDir as xo,shouldIgnoreDiscoveryFile as Ar}from"@octocodeai/octocode-engine/security";var Bf=Symbol.for("octocode.rawResponseChars");function G(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function zf(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?zf(t):G(t);if(n===void 0)return e;try{Object.defineProperty(e,Bf,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ie(e){if(!(typeof e!="object"||e===null))return zf(e[Bf])}function Lr(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function Qf(e){let t=Lr(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function _r(e){let t=Lr(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function Uf(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var jf=30;async function $f(e,t,n){let r=await ve(t),o=Ee("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await Fe(o,async()=>await iT(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function iT(e,t){try{let n=await j(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(g=>g&&g.trim()).length===0)return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let r=ul(e);if(!r.trim())return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:jf,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 sT(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,p=Math.min(u,1e3),d=Math.ceil(p/o),m=Math.min(i,Math.max(1,d)),f=m<d,h=Math.min(p,d*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:m,totalPages:d,perPage:o,totalMatches:p,reportedTotalMatches:u,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:u>p,hasMore:f,...f?{nextPage:m+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Lr(a.headers),rawResponseChars:G(a.data)}}catch(n){if(Ht(n)){let o=Math.min(typeof e.limit=="number"?e.limit:jf,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 J(n)}}async function sT(e,t){let n=aT(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(m=>!Ar(m.path)),c=0,l=0,u=await Promise.allSettled(a.map(async m=>{s.add(m.path);let f=[],h=await Promise.allSettled((m.text_matches||[]).map(async C=>{let P=C.fragment,T=oT.sanitizeContent(P||"",m.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${m.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${m.path}: ${k}`));try{let k=await D.minifyContent(P||"",m.path);P=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let E=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:P||"",positions:Uf(C.fragment||"",E,P||"")}})),y=h.filter(C=>C.status==="fulfilled").map(C=>C.value),g=h.filter(C=>C.status==="rejected").length;g>0&&(l+=g);let S=m,R=Array.from(new Set(f));return{path:m.path,matches:y,url:m.html_url,repository:{nameWithOwner:m.repository.full_name,url:m.repository.url,pushedAt:m.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...R.length>0&&{minificationType:R.join(",")}}})),p=u.filter(m=>m.status==="fulfilled").map(m=>m.value);c=u.filter(m=>m.status==="rejected").length;let d={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let m=n.full_name.split("/");return m.length===2&&m[0]&&m[1]?{owner:m[0],repo:m[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(d.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&&(d.matchLocations=Array.from(r)),d.minified=!o,d.minificationFailed=o,i.length>0&&(d.minificationTypes=Array.from(new Set(i))),d}function aT(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 Wf=30;function Vf(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 Kf(e,t,n){let r=await ve(t),o=e,i=Ee("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:o.size,created:o.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await Fe(i,async()=>await lT(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function cT(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(m){if(m?.status!==404)return J(m);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(h){return J(h)}}let a=i.map(m=>{let h=m.full_name.split("/"),y=h[0]||"",g=h[1]||"";return{owner:y,repo:g,defaultBranch:m.default_branch,stars:m.stargazers_count||0,description:m.description?m.description:"No description",url:m.html_url,createdAt:m.created_at,updatedAt:m.updated_at,pushedAt:m.pushed_at,visibility:m.visibility,...m.topics&&m.topics.length>0&&{topics:m.topics},...m.forks_count&&m.forks_count>0&&{forksCount:m.forks_count},...m.open_issues_count&&m.open_issues_count>0&&{openIssuesCount:m.open_issues_count},...m.language&&{language:m.language},...Vf(m)}}),c=a.length,l=c===n,u=(r-1)*n+c,p=s??u+(l?1:0),d=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:p,reachableTotalMatches:u,totalMatchesKind:d,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:G(i)}}async function lT(e,t){try{let n=await j(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=e,i=!!(e.stars||e.updated||e.language||e.match||o.forks||o.goodFirstIssues||o.created||o.size||o.license||o.visibility||o.archived!==void 0||e.sort&&!["best-match","updated"].includes(e.sort)),s=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&!i&&s)return await cT({owner:s,sort:e.sort,limit:e.limit,page:e.page},n);let a=pl(e);if(!a.trim())return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let c=Math.min(e.limit||Wf,100),l=e.page||1,u={q:a,per_page:c,page:l},p=["stars","forks","help-wanted-issues","updated"];e.sort&&p.includes(e.sort)&&(u.sort=e.sort);let d=await n.rest.search.repos(u),m=d.data.items.map(C=>{let T=C.full_name.split("/"),E=T[0]||"",k=T[1]||"";return{owner:E,repo:k,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},...Vf(C)}}),f=d.data.total_count,h=Math.min(f,1e3),y=Math.ceil(h/c),g=Math.min(l,Math.max(1,y)),S=g<y,R=Math.min(h,y*c);return{data:{repositories:m,pagination:{currentPage:g,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:f,reachableTotalMatches:R,totalMatchesKind:"reported",totalMatchesCapped:f>h,hasMore:S,...S?{nextPage:g+1}:{}}},status:200,headers:Lr(d.headers),rawResponseChars:G(d.data)}}catch(n){if(Ht(n)){let r=Math.min(e.limit||Wf,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 J(n)}}function Lt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}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 uT(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 Zt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:uT(e)}}function rs(e){return pT(e)?Zt({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 pT(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||dT(n)}function dT(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function wo(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...e?.totalMatchesKind==="lowerBound"?{totalMatchesKind:"lowerBound"}:{},...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function mT(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,...wo(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function fT(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,...wo(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Xf(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,goal:e.goal,reasoning:e.reasoning},a=await $f(s,t);return Lt(a)?Zt(a):a.data?{data:mT(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??G(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Yf(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,goal:e.goal,reasoning:e.reasoning},r=await Kf(n,t);return"error"in r?rs(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:fT(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??G(r.data)}}import{RequestError as Rl}from"octokit";var I={...re,LOCAL_SEARCH:"localSearch",GITHUB_SEARCH_CODE:"github.code",GITHUB_VIEW_REPO_STRUCTURE:"github.tree",GITHUB_SEARCH_REPOSITORIES:"github.repositories",LOCAL_RIPGREP:"local.text",LOCAL_VIEW_STRUCTURE:"local.tree",LOCAL_FIND_FILES:"local.files"};function bl(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 paths are case-sensitive. Verify exact casing with ghSearch operation:"tree".'),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Sl(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(m=>m.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(m=>m.name===s?!1:!!m.name.startsWith(p+".")).forEach(m=>l.push(m.path)),l.length===0&&p.length>=3&&c.filter(f=>{let h=f.name.replace(/\.[^/.]+$/,"");return h!==p&&h.length>=3&&(p.startsWith(h)||h.startsWith(p))}).forEach(f=>l.push(f.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}async function gT(e,t,n,r,o,i,s,a){let c=await Me(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=J(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,d=await Sl(e,r,o,i,s||c);return d.length>0&&(u.hints=[...u.hints||[],...bl(i,d)]),{...u,...p&&{scopesSuggestion:p}}}async function yT(e,t,n,r,o,i){let s=J(t),a=await Sl(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...bl(o,a)]),s}async function Zf(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:hn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:hn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:hn.DECODE_FAILED.message,type:"unknown",status:422}}}async function Jf(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"?Zf(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return J(i)}}async function bT(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 Me(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(d=>d.name===a&&d.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let p=await Jf(e,t,n,u.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return J(s)}}async function Po(e,t,n={}){try{let r=await j(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(m){if(m instanceof Rl&&m.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(m instanceof Rl&&m.status===404)if(a){let f=await gT(r,m,c,o,i,s,a,t);if("result"in f)l=f.result,u=f.actualBranch;else return f}else return await yT(r,m,o,i,s,a);else{if(m instanceof Rl&&m.status===413)return await bT(r,o,i,s,a||u,t);throw m}}let p=l.data,d=_r(l.headers);if(Array.isArray(p))return{error:hn.PATH_IS_DIRECTORY.message(I.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let m=typeof p.content=="string"?p.content:"",f=p.size??0,h;if(m.length>0)h=await Zf(m,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)h=await Jf(r,o,i,p.sha,s);else return{error:hn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in h)return h;if(!u&&!a)try{u=await Me(o,i,t)}catch{}return{data:{rawContent:h.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:G(p),...d?{etag:d}:{}}}return{error:hn.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return J(r)}}import{ContentSanitizer as El}from"@octocodeai/octocode-engine/contentSanitizer";function os(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Gt(e){return os(e).length}function is(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(`
21
+ `)}return null}async function wm(e){let t=pn(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Ii();return r.credentials[t]=n,Sm(r),Ic(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Nc(e="github.com",t){let n=pn(e);if(!t?.bypassCache){let i=cm(n);if(i!==void 0)return i}let o=Ii().credentials[n]||null;return lm(n,o),o}async function Pm(e,t){let n=await Nc(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await wm(n),!0):!1}async function Tm(e,t){return Cm({getCredentials:Nc,updateToken:Pm},e,t)}xm({getTokenWithRefresh:Tm});import vi from"node:os";import $D from"node:path";var $x=vi.platform()==="win32",Wx=vi.platform()==="darwin",Vx=vi.platform()==="linux",Kx=vi.homedir();import{randomUUID as SH}from"node:crypto";import{existsSync as km,readFileSync as Im,writeFileSync as qx,unlinkSync as rH,renameSync as ew}from"node:fs";import{isPersistentStorageEnabled as Om,isStatsEnabled as vm}from"@octocodeai/config";import{z as Y}from"zod";var Xx=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),Yx=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),Fi=Y.record(Y.string(),Y.number()).default({}),Zx=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:Fi,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:Fi}),Mi=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:Fi,charsSavedByTool:Y.record(Y.string(),Xx).default({}),githubCacheHits:Yx.default({hits:{},rateLimits:0}),packageRegistryFailures:Fi,totalUsage:Zx.optional()}),Em=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:Mi.optional()}),Am=Y.object({version:Y.literal(1),stats:Mi});function Lm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Jx(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:Lm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Lm(o),packageRegistryFailuresByRegistry:o}}function dn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Jx(t)}}function Sr(){return dn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var so=Vt.session,ao=Vt.stats;function _m(e,t){let n=`${e}.tmp`;qx(n,JSON.stringify(t,null,2),{mode:384}),ew(n,e)}function tw(e){let t=JSON.parse(e),n=Am.safeParse(t);if(n.success)return dn(n.data.stats);let r=Mi.safeParse(t);return r.success?dn(r.data):null}function nw(){if(!km(ao))return Sr();try{let e=Im(ao,"utf8");return tw(e)??Sr()}catch{return Sr()}}function Dc(e){if(!Om())return;Dn(),vm()&&_m(ao,{version:e.version,stats:dn(e.stats)});let{stats:t,...n}=e;_m(so,n)}function Fm(){if(!Om()||!km(so))return null;try{let e=Im(so,"utf8"),t=JSON.parse(e),n=Em.safeParse(t);return n.success?{...n.data,stats:vm()?nw():Sr()}:null}catch{return null}}var rw=6e4,mn=null,co=!1,Hc=null,Mm=!1,Nm=null,Dm=null,Hm=null,Gc=!1;function ow(){Mm||(Mm=!0,Nm=()=>{Ni()},Dm=()=>{Ni()},Hm=()=>{Ni()},process.on("exit",Nm),process.on("SIGINT",Dm),process.on("SIGTERM",Hm))}function iw(){Hc||(Hc=setInterval(()=>{co&&mn&&(Dc(mn),co=!1)},rw),Hc.unref())}function Gm(){if(mn)return mn;let e=Fm();return e&&(mn=e),e}function Bm(e){mn=e,co=!0,ow(),iw()}function Ni(){if(!Gc&&co&&mn){Gc=!0;try{Dc(mn),co=!1}catch{}finally{Gc=!1}}}function sw(e){return dn(e)}function aw(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 zm(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 cw(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 fn(e){let t=Gm();if(!t)return{success:!1,session:null};let n=sw(t.stats),r=dn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:zm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:aw(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:cw(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:zm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Bm(o),{success:!0,session:o}}function Bc(e=1){return fn({rateLimits:e})}function zc(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return fn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function Qc(e,t=1){return fn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function Uc(e=1){return fn({githubCacheHits:{hits:{},rateLimits:e}})}import{z as Ce}from"zod";var lw=Ce.looseObject({$schema:Ce.string().optional(),version:Ce.number().int().optional(),github:Ce.record(Ce.string(),Ce.unknown()).optional(),local:Ce.record(Ce.string(),Ce.unknown()).optional(),tools:Ce.record(Ce.string(),Ce.unknown()).optional(),network:Ce.record(Ce.string(),Ce.unknown()).optional(),lsp:Ce.record(Ce.string(),Ce.unknown()).optional(),output:Ce.record(Ce.string(),Ce.unknown()).optional()});import{existsSync as uw,readdirSync as pw,lstatSync as dw}from"node:fs";import{join as mw}from"node:path";function Di(e){if(!uw(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=pw(r)}catch{continue}for(let i of o){let s=mw(r,i);try{let a=dw(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}import{getConfigSync as wf}from"@octocodeai/config";var Hn="18.3.0";var jc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},lo={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"}},uo={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})`}},hw={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"}},hn={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}`}},gn={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"}},Ve={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}`}},gw={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}`}},po={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},yw={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}`}},oG={...jc,...lo,...uo,...hw,...hn,...gn,...Ve,...gw,...po,...yw};import{maskSensitiveData as EP}from"@octocodeai/octocode-engine/mask";import{mkdirSync as gf,readFileSync as hP,renameSync as Sf,rmSync as Rf,statSync as gP,writeFileSync as yP}from"node:fs";import{join as Jc}from"node:path";import{isPersistentStorageEnabled as bP}from"@octocodeai/config";import{existsSync as go,readFileSync as Lw,writeFileSync as _w,mkdirSync as kw,rmSync as ho,readdirSync as Iw,statSync as Ow}from"node:fs";import{join as yn}from"node:path";import{join as Hi}from"node:path";import{createHash as Qm}from"node:crypto";function Gi(e){return Hi(e,"tmp","clone")}function Bi(e){return Hi(e,"tmp","tree")}function bw(e){return e?`__sp_${Qm("sha256").update(e).digest("hex").substring(0,6)}`:""}function Sw(e){if(!/[\\/]/.test(e))return e;let t=Qm("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function $c(e,t,n,r,o){let i=`${Sw(r)}${bw(o)}`;return Hi(Gi(e),t,n,i)}function mo(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new Error("Tree cache identity must be a 40-character commit SHA.");return Hi(Bi(e),t,n,r.toLowerCase())}import{readFileSync as Rw,readdirSync as Cw,renameSync as xw,rmSync as $m,statSync as Wm,writeFileSync as ww}from"node:fs";import{join as Rr}from"node:path";var Pw=900*1e3,Um=300*1e3,Vm=".octocode-lock.json";function Tw(e){return typeof e=="object"&&e!==null}function jm(e){try{return Cw(e)}catch{return[]}}function Wc(e,t=process.pid,n=Date.now()){try{ww(Rr(e,Vm),JSON.stringify({pid:t,createdAt:n}),{encoding:"utf8",mode:384})}catch{}}function Ew(e){try{let t=JSON.parse(Rw(Rr(e,Vm),"utf8"));return!Tw(t)||!Number.isInteger(t.pid)||t.pid<=0||typeof t.createdAt!="number"?null:{pid:t.pid,createdAt:t.createdAt}}catch{return null}}function Aw(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function zi(e,t=Date.now()){let n,r=Ew(e);if(r){if(n=r.createdAt,t-n<=Um||Aw(r.pid))return!1}else{try{n=Wm(e).mtimeMs}catch{return!1}if(t-n<=Um)return!1}let o=`${e}.stale-${process.pid}-${t}`;try{return xw(e,o),$m(o,{recursive:!0,force:!0}),!0}catch{return!1}}function Vc(e,t=Date.now()){let n=Rr(e,"tmp","clone-tmp"),r=0;for(let i of jm(n)){let s=Rr(n,i);try{let a=Wm(s);if(t-a.mtimeMs<=Pw)continue;$m(s,{recursive:!0,force:!0}),r++}catch{}}let o=Rr(e,"tmp","clone-locks");for(let i of jm(o))zi(Rr(o,i),t)&&r++;return r}var vw=1440*60*1e3,Fw=2*1024*1024*1024,Mw=50,Xm=".octocode-clone-meta.json";function Nw(e){return typeof e=="object"&&e!==null}function Dw(e){if(!Nw(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 Kc(e){let t=yn(e,Xm);if(!go(t))return null;try{return Dw(JSON.parse(Lw(t,"utf-8")))}catch{return null}}function Cr(e,t){try{_w(yn(e,Xm),JSON.stringify(t,null,2),"utf-8")}catch{}}function Ym(e){return Date.now()<new Date(e.expiresAt).getTime()}function xr(e){let t=Kc(e);return t?Ym(t)?go(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Hw(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return vw}function Gw(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Fw}function Bw(){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 Mw}function wr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Hw()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function bn(e){let t=yn(e,"..");try{go(t)||kw(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 Qi(e){try{go(e)&&ho(e,{recursive:!0,force:!0})}catch{}}function fo(e){try{return Ow(e).isDirectory()}catch{return!1}}function Gn(e){try{return Iw(e)}catch{return[]}}function*Zm(e){for(let t of Gn(e)){let n=yn(e,t);if(fo(n))for(let r of Gn(n)){let o=yn(n,r);if(fo(o))for(let i of Gn(o)){let s=yn(o,i);fo(s)&&(yield s)}}}}function Km(e){for(let t of[...Gn(e)]){let n=yn(e,t);if(fo(n)){for(let r of[...Gn(n)]){let o=yn(n,r);if(fo(o)&&Gn(o).length===0)try{ho(o,{recursive:!0,force:!0})}catch{}}if(Gn(n).length===0)try{ho(n,{recursive:!0,force:!0})}catch{}}}}function zw(e){let t=0;for(let n of Zm(e))try{let r=Kc(n);(!r||!Ym(r))&&(ho(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Qw(e){let t=[];for(let n of Zm(e)){let r=Kc(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??Di(n)})}return t}function Uw(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{ho(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Jm(e){if(!go(e))return 0;let t=0;try{t+=zw(e)}catch{return t}Km(e);let n=Uw(Qw(e),Gw(),Bw());return t+=n,n>0&&Km(e),t}function Ui(e){return Jm(Gi(e))}function Pr(e){return Jm(Bi(e))}import jw from"crypto";var $w="v2",Ww=new Set([]);function Vw(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(Ww.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Ee(e,t,n){let r=Xc(Vw(t)),o=n?`${n}:${r}`:r,i=jw.createHash("sha256").update(o).digest("hex");return`${$w}-${e}:${i}`}function Xc(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=>Xc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Xc(i,t)}`}).join(",")}}`)}import Kw from"node-cache";var Xw=300*1e3,At=new Kw({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),qe={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},qm={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},ct=new Map;function Yw(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Zw(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Bn(e){let t=Yw(e);if(!(!t||!Zw(t)))try{Qc(t,1)}catch{}}function ji(){let e=Date.now();for(let[t,n]of ct.entries())e-n.startedAt>Xw&&ct.delete(t)}function $i(e){return qm[e]||qm.default}function zn(e,t,n){try{return At.set(e,t,n),qe.sets++,qe.totalKeys=At.keys().length,!0}catch{try{let r=At.keys();for(let o of r)At.get(o);return At.set(e,t,n),qe.sets++,qe.totalKeys=At.keys().length,!0}catch{return!1}}}import{createHash as Jw}from"node:crypto";import{chmod as ef,mkdir as nf,readFile as rf,readdir as qw,rename as tf,rm as eP,stat as Yc,writeFile as of}from"node:fs/promises";import{join as yo}from"node:path";import{isPersistentStorageEnabled as tP}from"@octocodeai/config";var sf=1,af=5*1024*1024,nP=5e3,rP=256*1024*1024,oP=1440*60*1e3,iP=900*1e3,cf=".last-gc",lt={hits:0,misses:0,sets:0,errors:0,evictions:0};function Wi(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Zc(){if(!tP())return!1;let e=process.env.OCTOCODE_DISK_CACHE?.trim().toLowerCase();return!(e==="false"||e==="0")}function lf(e=ro()){return yo(e,"tmp","response")}function sP(e){return(e.match(/^v\d+-([^:]+):/)?.[1]??"default").replace(/[^a-zA-Z0-9._-]/g,"_")}function uf(e,t=ro()){let n=Jw("sha256").update(e).digest("hex");return yo(lf(t),sP(e),n.slice(0,2),`${n}.json`)}function pf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aP(e,t){let n;try{n=JSON.parse(e)}catch{return null}return!pf(n)||n.version!==sf||n.key!==t||typeof n.createdAt!="number"||typeof n.expiresAt!="number"||typeof n.staleUntil!="number"||!("value"in n)||n.etag!==void 0&&typeof n.etag!="string"?null:n}async function Sn(e){try{await eP(e,{force:!0,recursive:!0})}catch{}}async function Vi(e,t={}){if(!Zc())return;let n=uf(e);try{let r=await Yc(n);if(!r.isFile()||r.size>Wi("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",af)){await Sn(n),lt.errors++;return}let o=aP(await rf(n,"utf8"),e);if(!o){await Sn(n),lt.errors++;return}let i=Date.now();if(i>=o.staleUntil){await Sn(n),lt.evictions++,lt.misses++;return}if(i>=o.expiresAt&&!t.allowStale){lt.misses++;return}return lt.hits++,{value:o.value,...o.etag?{etag:o.etag}:{},state:i<o.expiresAt?"fresh":"stale",expiresAt:o.expiresAt}}catch(r){r.code!=="ENOENT"&&lt.errors++,lt.misses++;return}}async function bo(e,t,n,r={}){if(!Zc())return!1;let o=Date.now(),i=Math.max(1,n*1e3),s=Math.max(i,(r.staleTtlSeconds??n)*1e3),a={version:sf,key:e,createdAt:o,expiresAt:o+i,staleUntil:o+s,value:t,...r.etag?{etag:r.etag}:{}},c;try{c=JSON.stringify(a)}catch{return lt.errors++,!1}if(c===void 0||Buffer.byteLength(c)>Wi("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",af))return!1;let l=uf(e),u=yo(l,".."),p=`${l}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{await nf(u,{recursive:!0,mode:448}),await ef(u,448),await of(p,c,{encoding:"utf8",mode:384}),await ef(p,384);try{await tf(p,l)}catch(d){let m=d.code;if(m!=="EEXIST"&&m!=="EPERM")throw d;await Sn(l),await tf(p,l)}return lt.sets++,!0}catch{return lt.errors++,await Sn(p),!1}}async function cP(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=await qw(r,{withFileTypes:!0})}catch{continue}for(let i of o){let s=yo(r,i.name);i.isDirectory()?n.push(s):i.isFile()&&i.name!==cf&&t.push(s)}}return t}async function lP(e,t,n){if(!Zc())return 0;let r=lf(e),o=yo(r,cf);if(n)try{let p=await Yc(o);if(t-p.mtimeMs<oP)return 0}catch{}let i=0,s=await cP(r),a=Wi("OCTOCODE_DISK_CACHE_MAX_ENTRIES",nP),c=Wi("OCTOCODE_DISK_CACHE_MAX_SIZE",rP),l=[],u=0;for(let p of s)try{let d=await Yc(p);if(p.includes(".tmp-")){t-d.mtimeMs>iP&&(await Sn(p),i++);continue}let m=await rf(p,"utf8"),f;try{f=JSON.parse(m)}catch{f=null}if(!pf(f)||typeof f.staleUntil!="number"||t>=f.staleUntil){await Sn(p),i++;continue}l.push({path:p,size:d.size,modified:d.mtimeMs}),u+=d.size}catch{}for(l.sort((p,d)=>p.modified-d.modified);l.length>a||u>c;){let p=l.shift();if(!p)break;await Sn(p.path),u-=p.size,i++}try{await nf(r,{recursive:!0,mode:448}),await of(o,String(t),{encoding:"utf8",mode:384})}catch{lt.errors++}return lt.evictions+=i,i}function df(e=ro(),t=Date.now()){return lP(e,t,!1)}import{AsyncLocalStorage as uP}from"node:async_hooks";var Ki=new uP;async function mf(e){let t={hit:!1};return{value:await Ki.run({root:t,depth:0,role:"response"},e),cacheHit:t.hit}}function Xi(e,t="response"){let n=Ki.getStore();return n?Ki.run({root:n.root,depth:n.depth+1,role:t},e):e()}function Kt(){let e=Ki.getStore();e&&e.depth<=1&&e.role==="response"&&(e.root.hit=!0)}function pP(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return $i(n?.[1]??"default")}async function Fe(e,t,n={}){return Xi(()=>dP(e,t,n),n.cacheRole)}async function dP(e,t,n){if(n.skipCache)return await t();if(!n.forceRefresh){try{let a=At.get(e);if(a!==void 0)return qe.hits++,Bn(e),Kt(),a}catch{}let s=await Vi(e);if(s?.state==="fresh")return qe.hits++,Bn(e),Kt(),zn(e,s.value,Math.max(1,(s.expiresAt-Date.now())/1e3)),s.value}ji();let r=ct.get(e);if(r)return r.promise;let o=Symbol(e),i=(async()=>{try{let s=await t();if(n.forceRefresh||qe.misses++,(n.shouldCache??(()=>!0))(s)){let c=pP(e,n.ttl);zn(e,s,c),await bo(e,s,c)}return s}finally{ct.get(e)?.requestId===o&&ct.delete(e)}})();return ct.set(e,{promise:i,startedAt:Date.now(),requestId:o}),i}import mP from"node-cache";var ff=86400;function hf(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return $i(n?.[1]??"default")}var Yi=new mP({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function Zi(e,t,n={}){return Xi(()=>fP(e,t,n),n.cacheRole)}async function fP(e,t,n){if(n.skipCache)return(await t({})).value;let r;if(!n.forceRefresh){try{let a=At.get(e);if(a!==void 0)return qe.hits++,Bn(e),Kt(),a}catch{}if(r=await Vi(e,{allowStale:!0}),r?.state==="fresh")return qe.hits++,Bn(e),Kt(),zn(e,r.value,Math.max(1,(r.expiresAt-Date.now())/1e3)),r.etag&&Yi.set(e,{data:r.value,etag:r.etag}),r.value}ji();let o=ct.get(e);if(o)return o.promise;let i=Symbol(e),s=(async()=>{try{let c=(n.forceRefresh?void 0:Yi.get(e))??(r?{data:r.value,etag:r.etag}:void 0),l=await t({ifNoneMatch:!n.forceRefresh&&c?.etag?c.etag:void 0});if(l.notModified&&c){qe.hits++,Bn(e),Kt();let p=hf(e,n.ttl);return zn(e,c.data,p),await bo(e,c.data,p,{...c.etag?{etag:c.etag}:{},staleTtlSeconds:ff}),c.data}if(n.forceRefresh||qe.misses++,(n.shouldCache??(()=>!0))(l.value)){let p=hf(e,n.ttl);zn(e,l.value,p),Yi.set(e,{data:l.value,etag:l.etag}),await bo(e,l.value,p,{...l.etag?{etag:l.etag}:{},staleTtlSeconds:ff})}return l.value}finally{ct.get(e)?.requestId===i&&ct.delete(e)}})();return ct.set(e,{promise:s,startedAt:Date.now(),requestId:i}),s}var yf=1440*60*1e3,sB=60*1e3,SP=900*1e3,RP=".last-cache-maintenance",CP=".cache-maintenance.lock";var Ji=new Map;function Cf(e){return Jc(e,"tmp")}function xf(e){return Jc(Cf(e),RP)}function xP(e){try{let t=Number(hP(xf(e),"utf8"));return Number.isFinite(t)&&t>=0?t:null}catch{return null}}function bf(e,t=Date.now()){let n=xP(e);return n===null?0:Math.min(yf,Math.max(0,n+yf-t))}function wP(e,t){let n=Cf(e),r=Jc(n,CP);try{gf(n,{recursive:!0,mode:448})}catch{return null}let o=()=>{try{return gf(r,{mode:448}),!0}catch{return!1}};if(o())return r;try{if(t-gP(r).mtimeMs<=SP)return null;let i=`${r}.stale-${process.pid}-${t}`;Sf(r,i),Rf(i,{recursive:!0,force:!0})}catch{return null}return o()?r:null}function PP(e,t){let n=xf(e),r=`${n}.tmp-${process.pid}-${t}`;yP(r,String(t),{encoding:"utf8",mode:384}),Sf(r,n)}async function TP(e,t){if(bf(e,t)>0)return!1;let n=wP(e,t);if(!n)return!1;try{if(bf(e,t)>0)return!1;try{return Ui(e),Pr(e),Vc(e,t),await df(e,t),PP(e,t),!0}catch{return!1}}finally{try{Rf(n,{recursive:!0,force:!0})}catch{}}}function qi(e,t=Date.now()){if(!bP())return Promise.resolve(!1);let n=Ji.get(e);if(n)return n;let r=TP(e,t).finally(()=>{Ji.get(e)===r&&Ji.delete(e)});return Ji.set(e,r),r}var Ro=null,So=null,AP=Oi;var LP=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function Pf(){try{let e=await AP({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:LP.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Tf(){if(Ro!==null)return;if(So!==null)return So;let e=(async()=>{let t=wf(),n=await Pf();Ro={version:Hn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone&&t.storage.mode==="persistent",tokenSource:n.source},await qi(Dt())})();So=e;try{await e}catch(t){throw So===e&&(Ro=null,So=null),t}}function es(){if(!Ro){let e=EP(jc.NOT_INITIALIZED.message);throw new Error(e)}return Ro}async function qc(){return(await Pf()).token}function Ef(){let e=es();return e.enableLocal&&e.enableClone}function el(){return"github"}function tl(){let e=wf().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as oT}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as _P}from"node:module";var kP=_P(import.meta.url),Af="@octocodeai/octocode-engine",IP=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??kP(Af),ts,OP=IP,nl=class extends Error{constructor(n){super(`Failed to load native dependency ${Af}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function ee(){if(ts)return ts;try{return ts=OP(),ts}catch(e){throw new nl(e)}}var D={applyContentViewMinification(e,t){return ee().applyContentViewMinification(e,t)},applyMinification(e,t){return ee().applyMinification(e,t)},minifyContent(e,t){return ee().minifyContent(e,t)},minifyContentSync(e,t){return ee().minifyContentSync(e,t)},minifyContentResult(e,t){return ee().minifyContentResult(e,t)},minifyMarkdownCore(e){return ee().minifyMarkdownCore(e)},extractSignatures(e,t){return ee().extractSignatures(e,t)},extractJsSymbols(e,t){return ee().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ee().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ee().extractGraphFacts(e,t)},scanGraphFacts(e){return ee().scanGraphFacts(e)},getSupportedJsTsExtensions(){return ee().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ee().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ee().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ee().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ee().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return ee().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return ee().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return ee().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ee().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ee().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ee().parseRipgrepJson(e,t)},searchRipgrep(e){return ee().searchRipgrep(e)},queryFileSystem(e){return ee().queryFileSystem(e)},extractMatchingLines(e,t,n){return ee().extractMatchingLines(e,t,n)},filterPatch(e,t){return ee().filterPatch(e,t)},computeLineDiff(e,t){return ee().computeLineDiff(e,t)},charToByteOffset(e,t){return ee().charToByteOffset(e,t)},byteToCharOffset(e,t){return ee().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ee().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ee().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ee().SIGNATURES_ONLY_HINT}};import{Octokit as vP}from"octokit";import{throttling as FP}from"@octokit/plugin-throttling";import{createHash as MP}from"crypto";function Rn(e){(e.provider?fn({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Bc(1)).session&&e.provider==="github"&&Uc(1)}function Lf(e){fn({packageRegistryFailures:{[e]:1}})}function vf(e){return MP("sha256").update(e).digest("hex").substring(0,16)}async function ve(e){let t=e?.token??await qc(),n=t?vf(t):"anon",r=es().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var NP=vP.plugin(FP),DP=300*1e3,rl=50,HP=60*1e3;function Ff(e){return Date.now()-e.createdAt>DP}var Xt=new Map,Co=null;function Mf(){for(let[e,t]of Xt.entries())Ff(t)&&Xt.delete(e);if(Xt.size>rl){let e=Xt.size-rl,t=0;for(let[n]of Xt){if(t>=e)break;Xt.delete(n),t++}}}function GP(){Co||(Co=setInterval(Mf,HP),typeof Co=="object"&&"unref"in Co&&Co.unref())}var _f=3,kf=60;function If(e,t,n){Rn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var BP=()=>({onRateLimit:(e,t,n,r)=>(If("primary",e,t),r<_f&&e<kf),onSecondaryRateLimit:(e,t,n,r)=>(If("secondary",e,t),r<_f&&e<kf)});function zP(e){let t=es(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Hn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:BP(),log:r,...e&&{auth:e}};return new NP(o)}async function j(e){GP();let t=e?.token??await qc(),n=t?vf(t):"ANONYMOUS",r=Xt.get(n);if(r&&!Ff(r))return r.client;Xt.size>=rl&&Mf();let o=zP(t??void 0);return Xt.set(n,{client:o,createdAt:Date.now()}),o}var QP=200,UP=300*1e3,Tr=new Map;async function Me(e,t,n){let o=`${await ve(n)}:${e}/${t}`,i=Tr.get(o);if(i&&i.expiresAt>Date.now())return i.branch;i&&Tr.delete(o);let s=await j(n);try{let{data:c}=await s.rest.repos.get({owner:e,repo:t}),l=c.default_branch;return Of(o,l),l}catch{}let a=["main","master"];for(let c of a)try{return await s.rest.repos.getBranch({owner:e,repo:t,branch:c}),Of(o,c),c}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Of(e,t){if(Tr.size>=QP){let n=Tr.keys().next().value;n!==void 0&&Tr.delete(n)}Tr.set(e,{branch:t,expiresAt:Date.now()+UP})}import{RequestError as Df}from"octokit";var V={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"},_e={[V.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."},[V.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."},[V.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},[V.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)."},[V.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."},[V.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."},[V.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."},[V.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."},[V.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."},[V.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Nf={401:V.AUTH_REQUIRED,403:V.FORBIDDEN_PERMISSIONS,404:V.NOT_FOUND,422:V.INVALID_REQUEST,502:V.SERVER_UNAVAILABLE,503:V.SERVER_UNAVAILABLE,504:V.SERVER_UNAVAILABLE},ol={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},il={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ns={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var jP=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function Ht(e){if(!(e instanceof Df)||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 jP.some(o=>r.includes(o))})}function J(e){return e instanceof Df?$P(e):e instanceof Error?qP(e):{error:typeof e=="string"?e:_e[V.UNKNOWN].message,type:"unknown"}}function $P(e){let{status:t,message:n,response:r}=e;if(t===403)return VP(n,r);if(t===429)return WP(n,r);let o=Nf[t];return o?JP(o,t):Er(V.UNKNOWN,{error:n||_e[V.UNKNOWN].message,status:t})}function sl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function WP(e,t){let n=t?.headers,r=sl(n,"retry-after"),o=sl(n,"x-ratelimit-reset"),i=sl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ns.RESET_BUFFER_SECONDS,0):void 0);return Rn({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Er(V.RATE_LIMIT_PRIMARY,{error:e||_e[V.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:_e[V.RATE_LIMIT_PRIMARY].suggestion})}function VP(e,t){let n=t?.headers;if(il.SECONDARY.test(e))return KP(n);let r=n?.["x-ratelimit-remaining"],o=ZP(t);return r!==void 0&&String(r)==="0"||o?XP(n):YP(n)}function KP(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ns.SECONDARY_FALLBACK_SECONDS:t;return Rn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Er(V.RATE_LIMIT_SECONDARY,{error:_e[V.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:_e[V.RATE_LIMIT_SECONDARY].suggestion})}function XP(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)+ns.RESET_BUFFER_SECONDS,0):void 0,i=r?_e[V.RATE_LIMIT_PRIMARY].messageWithTime(r,o):_e[V.RATE_LIMIT_PRIMARY].messageWithoutTime;return Rn({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Er(V.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:_e[V.RATE_LIMIT_PRIMARY].suggestion})}function YP(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=_e[V.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=eT(String(t),String(n))),Er(V.FORBIDDEN_PERMISSIONS,{error:_e[V.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function ZP(e){return e?.data?.errors?.some(n=>n.type===il.GRAPHQL_TYPE)??!1}function JP(e,t){let n=_e[e];return Er(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function qP(e){return ol.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:_e[V.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:_e[V.NETWORK_CONNECTION_FAILED].suggestion}:ol.TIMEOUT.some(t=>e.message.includes(t))?{error:_e[V.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:_e[V.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Er(e,t){return{type:"http",...t}}function eT(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?_e[V.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):_e[V.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Hf(e){return`user:${e}`}var tT=/[@/]/,nT=/^[A-Za-z0-9_-]+$/;function al(e){return e.startsWith('"')||nT.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var Yt=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(Hf(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=tT.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var rT=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,cl=class extends Yt{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(al))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(rT):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 Yt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(al)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars");let n=t;return typeof n.size=="string"&&this.queryParts.push(`size:${n.size}`),typeof n.created=="string"&&this.queryParts.push(`created:${n.created}`),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`),typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function ul(e){return new cl().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function pl(e){return new ll().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var dl=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function ml(e){return new dl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function fl(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var hl=class extends Yt{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function gl(e){return new hl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function yl(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as WB,DISCOVERY_IGNORED_FILE_NAMES as VB,DISCOVERY_IGNORED_FOLDER_NAMES as KB,getDiscoveryExtension as Gf,shouldIgnoreDiscoveryDir as xo,shouldIgnoreDiscoveryFile as Ar}from"@octocodeai/octocode-engine/security";var Bf=Symbol.for("octocode.rawResponseChars");function G(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function zf(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?zf(t):G(t);if(n===void 0)return e;try{Object.defineProperty(e,Bf,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ie(e){if(!(typeof e!="object"||e===null))return zf(e[Bf])}function Lr(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function Qf(e){let t=Lr(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function _r(e){let t=Lr(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function Uf(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var jf=30;async function $f(e,t,n){let r=await ve(t),o=Ee("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await Fe(o,async()=>await iT(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function iT(e,t){try{let n=await j(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(g=>g&&g.trim()).length===0)return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let r=ul(e);if(!r.trim())return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:jf,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 sT(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,p=Math.min(u,1e3),d=Math.ceil(p/o),m=Math.min(i,Math.max(1,d)),f=m<d,h=Math.min(p,d*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:m,totalPages:d,perPage:o,totalMatches:p,reportedTotalMatches:u,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:u>p,hasMore:f,...f?{nextPage:m+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Lr(a.headers),rawResponseChars:G(a.data)}}catch(n){if(Ht(n)){let o=Math.min(typeof e.limit=="number"?e.limit:jf,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 J(n)}}async function sT(e,t){let n=aT(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(m=>!Ar(m.path)),c=0,l=0,u=await Promise.allSettled(a.map(async m=>{s.add(m.path);let f=[],h=await Promise.allSettled((m.text_matches||[]).map(async C=>{let P=C.fragment,T=oT.sanitizeContent(P||"",m.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${m.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${m.path}: ${k}`));try{let k=await D.minifyContent(P||"",m.path);P=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let E=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:P||"",positions:Uf(C.fragment||"",E,P||"")}})),y=h.filter(C=>C.status==="fulfilled").map(C=>C.value),g=h.filter(C=>C.status==="rejected").length;g>0&&(l+=g);let S=m,R=Array.from(new Set(f));return{path:m.path,matches:y,url:m.html_url,repository:{nameWithOwner:m.repository.full_name,url:m.repository.url,pushedAt:m.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...R.length>0&&{minificationType:R.join(",")}}})),p=u.filter(m=>m.status==="fulfilled").map(m=>m.value);c=u.filter(m=>m.status==="rejected").length;let d={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let m=n.full_name.split("/");return m.length===2&&m[0]&&m[1]?{owner:m[0],repo:m[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(d.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&&(d.matchLocations=Array.from(r)),d.minified=!o,d.minificationFailed=o,i.length>0&&(d.minificationTypes=Array.from(new Set(i))),d}function aT(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 Wf=30;function Vf(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 Kf(e,t,n){let r=await ve(t),o=e,i=Ee("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:o.size,created:o.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await Fe(i,async()=>await lT(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function cT(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(m){if(m?.status!==404)return J(m);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(h){return J(h)}}let a=i.map(m=>{let h=m.full_name.split("/"),y=h[0]||"",g=h[1]||"";return{owner:y,repo:g,defaultBranch:m.default_branch,stars:m.stargazers_count||0,description:m.description?m.description:"No description",url:m.html_url,createdAt:m.created_at,updatedAt:m.updated_at,pushedAt:m.pushed_at,visibility:m.visibility,...m.topics&&m.topics.length>0&&{topics:m.topics},...m.forks_count&&m.forks_count>0&&{forksCount:m.forks_count},...m.open_issues_count&&m.open_issues_count>0&&{openIssuesCount:m.open_issues_count},...m.language&&{language:m.language},...Vf(m)}}),c=a.length,l=c===n,u=(r-1)*n+c,p=s??u+(l?1:0),d=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:p,reachableTotalMatches:u,totalMatchesKind:d,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:G(i)}}async function lT(e,t){try{let n=await j(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=e,i=!!(e.stars||e.updated||e.language||e.match||o.forks||o.goodFirstIssues||o.created||o.size||o.license||o.visibility||o.archived!==void 0||e.sort&&!["best-match","updated"].includes(e.sort)),s=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&!i&&s)return await cT({owner:s,sort:e.sort,limit:e.limit,page:e.page},n);let a=pl(e);if(!a.trim())return{error:Ve.QUERY_EMPTY.message,type:"http",status:400};let c=Math.min(e.limit||Wf,100),l=e.page||1,u={q:a,per_page:c,page:l},p=["stars","forks","help-wanted-issues","updated"];e.sort&&p.includes(e.sort)&&(u.sort=e.sort);let d=await n.rest.search.repos(u),m=d.data.items.map(C=>{let T=C.full_name.split("/"),E=T[0]||"",k=T[1]||"";return{owner:E,repo:k,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},...Vf(C)}}),f=d.data.total_count,h=Math.min(f,1e3),y=Math.ceil(h/c),g=Math.min(l,Math.max(1,y)),S=g<y,R=Math.min(h,y*c);return{data:{repositories:m,pagination:{currentPage:g,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:f,reachableTotalMatches:R,totalMatchesKind:"reported",totalMatchesCapped:f>h,hasMore:S,...S?{nextPage:g+1}:{}}},status:200,headers:Lr(d.headers),rawResponseChars:G(d.data)}}catch(n){if(Ht(n)){let r=Math.min(e.limit||Wf,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 J(n)}}function Lt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}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 uT(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 Zt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:uT(e)}}function rs(e){return pT(e)?Zt({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 pT(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||dT(n)}function dT(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function wo(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...e?.totalMatchesKind==="lowerBound"?{totalMatchesKind:"lowerBound"}:{},...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function mT(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,...wo(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function fT(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,...wo(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Xf(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,goal:e.goal,reasoning:e.reasoning},a=await $f(s,t);return Lt(a)?Zt(a):a.data?{data:mT(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??G(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Yf(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,goal:e.goal,reasoning:e.reasoning},r=await Kf(n,t);return"error"in r?rs(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:fT(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??G(r.data)}}import{RequestError as Rl}from"octokit";var I={...re,LOCAL_SEARCH:"localSearch",GITHUB_SEARCH_CODE:"github.code",GITHUB_VIEW_REPO_STRUCTURE:"github.tree",GITHUB_SEARCH_REPOSITORIES:"github.repositories",LOCAL_RIPGREP:"local.text",LOCAL_VIEW_STRUCTURE:"local.tree",LOCAL_FIND_FILES:"local.files"};function bl(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 paths are case-sensitive. Verify exact casing with ghSearch operation:"tree".'),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Sl(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(m=>m.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(m=>m.name===s?!1:!!m.name.startsWith(p+".")).forEach(m=>l.push(m.path)),l.length===0&&p.length>=3&&c.filter(f=>{let h=f.name.replace(/\.[^/.]+$/,"");return h!==p&&h.length>=3&&(p.startsWith(h)||h.startsWith(p))}).forEach(f=>l.push(f.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}async function gT(e,t,n,r,o,i,s,a){let c=await Me(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=J(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,d=await Sl(e,r,o,i,s||c);return d.length>0&&(u.hints=[...u.hints||[],...bl(i,d)]),{...u,...p&&{scopesSuggestion:p}}}async function yT(e,t,n,r,o,i){let s=J(t),a=await Sl(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...bl(o,a)]),s}async function Zf(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:hn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:hn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:hn.DECODE_FAILED.message,type:"unknown",status:422}}}async function Jf(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"?Zf(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return J(i)}}async function bT(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 Me(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(d=>d.name===a&&d.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let p=await Jf(e,t,n,u.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return J(s)}}async function Po(e,t,n={}){try{let r=await j(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(m){if(m instanceof Rl&&m.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(m instanceof Rl&&m.status===404)if(a){let f=await gT(r,m,c,o,i,s,a,t);if("result"in f)l=f.result,u=f.actualBranch;else return f}else return await yT(r,m,o,i,s,a);else{if(m instanceof Rl&&m.status===413)return await bT(r,o,i,s,a||u,t);throw m}}let p=l.data,d=_r(l.headers);if(Array.isArray(p))return{error:hn.PATH_IS_DIRECTORY.message(I.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let m=typeof p.content=="string"?p.content:"",f=p.size??0,h;if(m.length>0)h=await Zf(m,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)h=await Jf(r,o,i,p.sha,s);else return{error:hn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in h)return h;if(!u&&!a)try{u=await Me(o,i,t)}catch{}return{data:{rawContent:h.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:G(p),...d?{etag:d}:{}}}return{error:hn.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return J(r)}}import{ContentSanitizer as El}from"@octocodeai/octocode-engine/contentSanitizer";function os(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Gt(e){return os(e).length}function is(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(`
22
22
  `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var ST=/\.(?:md|markdown|mdx)$/i;function RT(e){return ST.test(e.split(/[?#]/,1)[0]??e)}function qf(e,t){return RT(t)?xT(CT(e)):null}function ss(e,t){let n=qf(e,t);if(n===null||n.length===0)return null;let r=[];return th(n,r),r.join(`
23
23
  `)}function eh(e,t){let n=qf(e,t);return n===null?null:n.map(nh)}function CT(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 xT(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 th(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}`),th(n.children,t)}}function nh(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(nh)}}import{getConfigSync as wT,DEFAULT_OUTPUT_CONFIG as PT}from"@octocodeai/config";function Qn(){try{return wT().output.pagination.defaultCharLength}catch{return PT.pagination.defaultCharLength}}function Cl(e,t){return D.byteToCharOffset(e,t)}function rh(e,t){return D.charToByteOffset(e,t)}function oh(e){return D.charToByteOffset(e,e.length)}function xl(e,t,n,r){return D.sliceContent(e,t,n,r)}function as(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=oh(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,p,d,m,f,h;if(o==="bytes"){let y=Math.min(t,s),g=Math.min(y+n,s);p=Cl(e,y),d=Cl(e,g),d<i&&rh(e,d)<g&&(d+=1);let S=xl(e,p,d-p);c=S.text,p=S.charOffset,d=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,m=u<s;let R=r.actualOffset??y;f=Math.floor(R/a)+1,h=Math.max(f,Math.ceil(s/a))}else{let y=xl(e,t,n);c=y.text,p=y.charOffset,d=y.charOffset+y.charLength,l=y.byteOffset,u=y.byteOffset+y.byteLength,m=d<i;let g=r.actualOffset??p;f=Math.floor(g/a)+1,h=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:m?u:void 0,charOffset:p,charLength:c.length,totalChars:i,nextCharOffset:m?d:void 0,hasMore:m,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:h}}function wl(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}var TT=8e3,ET="__octocode_generic__.unknown";function AT(e){return e&&e.trim().length>0?e:ET}async function ih(e,t){return(await D.getSemanticBoundaryOffsets(e,AT(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function LT(e,t){let n=e.indexOf(`
24
24
  `,t);return n===-1?void 0:n+1}function cs(e){let t=e.trimEnd().split(`
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
8
  import{withSecurityValidation as SC,withBasicSecurityValidation as RC}from"@octocodeai/octocode-engine/security";function em(e,t,n){let r=SC(e,(o,i)=>t(o,i),n);return(o,i)=>r(o,{authInfo:i?.http?.authInfo,sessionId:i?.sessionId,signal:i?.mcpReq.signal})}function tm(e,t,n){let r=RC((o,i)=>e(o,i),t,n);return(o,i)=>r(o,{signal:i?.mcpReq.signal})}var Re=30,ue=100,dF=10,mF=100,nm=200,Qn=20,rm=100,ji=20,Qi=50,Ve=1e4,dn=20,G=1e3,om=100,fr=5e4,im=8e3,mn=1e5,sm=500;var Tc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},yo={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"}},bo={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})`}},CC={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"}},fn={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}`}},hn={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},Ke={QUERY_EMPTY:{code:"SEARCH_QUERY_EMPTY",message:"Search query cannot be empty"},NO_VALID_PARAMETERS:{code:"SEARCH_NO_VALID_PARAMETERS",message:"No valid search parameters provided"},PR_REQUIRED_PARAMS:{code:"SEARCH_PR_REQUIRED_PARAMS",message:"Owner, repo, and prNumber are required parameters"},PR_SINGLE_VALUES:{code:"SEARCH_PR_SINGLE_VALUES",message:"Owner and repo must be single values"},PULL_REQUEST_SEARCH_FAILED:{code:"SEARCH_PR_SEARCH_FAILED",message:e=>`Pull request search failed: ${e}`},PULL_REQUEST_LIST_FAILED:{code:"SEARCH_PR_LIST_FAILED",message:e=>`Pull request list failed: ${e}`},PULL_REQUEST_FETCH_FAILED:{code:"SEARCH_PR_FETCH_FAILED",message:(e,t)=>`Failed to fetch pull request #${e}: ${t}`}},xC={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}`}},So={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},wC={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}`}},hF={...Tc,...yo,...bo,...CC,...fn,...hn,...Ke,...xC,...So,...wC};var j={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"},PC=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(PC||{}),am={[j.PATH_VALIDATION_FAILED]:{code:j.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[j.FILE_ACCESS_FAILED]:{code:j.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[j.FILE_READ_FAILED]:{code:j.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[j.FILE_TOO_LARGE]:{code:j.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[j.BINARY_FILE_UNSUPPORTED]:{code:j.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[j.NO_MATCHES]:{code:j.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[j.OUTPUT_TOO_LARGE]:{code:j.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[j.COMMAND_NOT_AVAILABLE]:{code:j.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[j.COMMAND_EXECUTION_FAILED]:{code:j.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[j.COMMAND_TIMEOUT]:{code:j.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[j.TOOL_EXECUTION_FAILED]:{code:j.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[j.LSP_SERVER_UNAVAILABLE]:{code:j.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:'No language server available for semantic analysis \u2014 use localSearch operation:"text" or "structural", then localGetFileContent',recoverability:"user-action-required"}};var Ge=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=am[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
9
  Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function Ec(e){return e instanceof Ge}function cm(e,t=j.TOOL_EXECUTION_FAILED,n){if(Ec(e))return e;if(e instanceof Error)return new Ge(t,e.message,n,e);let r=String(e);return new Ge(t,r,n)}import{redactPath as Ro}from"@octocodeai/octocode-engine/pathUtils";var Xe={pathValidationFailed:(e,t,n)=>new Ge(j.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Ro(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Ro(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path with localSearch operation:"files".`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localSearch operation:"tree".`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Ge(j.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Ge(j.FILE_READ_FAILED,`Failed to read file: ${Ro(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Ge(j.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)}). Use startLine/endLine, matchString, or charOffset/charLength to read a bounded slice.`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Ge(j.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Ro(e)}. Use localSearch operation:"text" for embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Ge(j.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Ge(j.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 Ge(j.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Ge(j.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as Pw}from"octokit";import{throttling as Tw}from"@octokit/plugin-throttling";import{createHash as Ew}from"crypto";function Bt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function Zt(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 Co(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var xo=new Map,TC=300*1e3;function EC(e){let t=Bt(e),n=xo.get(t);return!n||Date.now()-n.cachedAt>=TC?!1:n.credentials?!Zt(n.credentials):!0}function wo(e){e?xo.delete(Bt(e)):xo.clear()}function lm(e){let t=Bt(e);if(EC(t))return xo.get(t).credentials}function um(e,t){let n=Bt(e);xo.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as Ki,readFileSync as fm,writeFileSync as hm,unlinkSync as mm,statSync as OC,chmodSync as vC}from"node:fs";import{createCipheriv as FC,createDecipheriv as MC,randomBytes as gm}from"node:crypto";import{existsSync as Ui,mkdirSync as $i}from"node:fs";import{join as gt}from"node:path";import{getOctocodeHome as AC}from"@octocodeai/config";var Wi=448;function gn(){return AC(process.env)}function At(){return Ye}var Ye=gn(),ze={home:Ye,config:gt(Ye,".octocoderc"),credentials:gt(Ye,"credentials.json"),key:gt(Ye,".key"),session:gt(Ye,"session.json"),stats:gt(Ye,"stats.json"),tmp:gt(Ye,"tmp"),clone:gt(Ye,"tmp","clone"),tree:gt(Ye,"tmp","tree"),response:gt(Ye,"tmp","response"),repos:gt(Ye,"tmp","clone"),cliConfig:gt(Ye,"config.json"),lspConfig:gt(Ye,"lsp-servers.json")};function Vi(){Ui(ze.home)||$i(ze.home,{recursive:!0,mode:Wi})}function LC(){pm()}function Ac(){Vi(),Ui(ze.tmp)||$i(ze.tmp,{recursive:!0,mode:Wi})}function pm(){Ac(),Ui(ze.clone)||$i(ze.clone,{recursive:!0,mode:Wi})}function _C(){Ac(),Ui(ze.tree)||$i(ze.tree,{recursive:!0,mode:Wi})}import{z as Ne}from"zod";var kC=Ne.object({token:Ne.string(),tokenType:Ne.literal("oauth"),scopes:Ne.array(Ne.string()).optional(),refreshToken:Ne.string().optional(),expiresAt:Ne.string().optional(),refreshTokenExpiresAt:Ne.string().optional()}),IC=Ne.object({hostname:Ne.string(),username:Ne.string(),token:kC,gitProtocol:Ne.enum(["ssh","https"]),createdAt:Ne.string(),updatedAt:Ne.string()}),dm=Ne.object({version:Ne.number(),credentials:Ne.record(Ne.string(),IC)});var Lc=ze.home,qt=ze.credentials,zt=ze.key,ym="aes-256-gcm",NC=16;function yn(){Vi()}function bm(){if(yn(),Ki(zt))return OC(zt).mode&511&63&&vC(zt,384),Buffer.from(fm(zt,"utf8"),"hex");let e=gm(32);return hm(zt,e.toString("hex"),{mode:384}),e}function Xi(e){let t=bm(),n=gm(NC),r=FC(ym,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 Yi(e){let t=bm(),[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=MC(ym,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function Jt(){if(yn(),!Ki(qt))return{version:1,credentials:{}};try{let e=fm(qt,"utf8"),t=Yi(e),n=JSON.parse(t),r=dm.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function _c(e){yn();let t=Xi(JSON.stringify(e,null,2));hm(qt,t,{mode:384})}function Sm(){try{Ki(qt)&&mm(qt),Ki(zt)&&mm(zt)}catch{}}import{refreshToken as DC}from"@octokit/oauth-methods";import{request as HC}from"@octokit/request";var hr="178c6fc778ccc68e1d6a",bn="github.com";function GC(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 BC(e){return e==="github.com"||e===bn?"https://api.github.com":`https://${e}/api/v3`}async function kc(e,t=bn,n=hr){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(Co(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await DC({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:HC.defaults({baseUrl:BC(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?GC(o.message):"Token refresh failed"}}}async function Rm(e,t=bn,n=hr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!Zt(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await kc(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as QC}from"@octocodeai/config";import{execFile as zC}from"child_process";var jC=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];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=jC.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;zC("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var qi=null;function Cm(e){qi=e}function Ic(){qi=null}function UC(){if(!qi)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return qi}async function Sn(e){let t=e?.hostname??bn,n=e?.clientId??hr,r=e?.getGhCliToken??Zi,o=QC();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await UC().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
10
- `)}return null}async function Oc(e=bn){let t=await Sn({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function vc(e=bn,t=hr){let n=await Sn({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}async function Fc(e){let t=Bt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Jt();return r.credentials[t]=n,_c(r),wo(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Un(e="github.com",t){let n=Bt(e);if(!t?.bypassCache){let i=lm(n);if(i!==void 0)return i}let o=Jt().credentials[n]||null;return um(n,o),o}function Ji(e="github.com"){let t=Bt(e);return Jt().credentials[t]||null}async function xm(e="github.com"){let t=Bt(e),n=!1,r=Jt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Sm():_c(r),n=!0),wo(t),{success:n,deletedFromFile:n}}async function wm(){let e=Jt();return Object.keys(e.credentials)}function Pm(){let e=Jt();return Object.keys(e.credentials)}async function Tm(e="github.com"){return await Un(e)!==null}function Em(e="github.com"){return Ji(e)!==null}async function es(e,t){let n=await Un(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Fc(n),!0):!1}function Am(){return qt}async function Lm(e="github.com"){let t=await Un(e);return!t||!t.token||Zt(t)?null:t.token.token}function _m(e="github.com"){let t=Ji(e);return!t||!t.token||Zt(t)?null:t.token.token}async function km(e,t){return kc({getCredentials:Un,updateToken:es},e,t)}async function Mc(e,t){return Rm({getCredentials:Un,updateToken:es},e,t)}Cm({getTokenWithRefresh:Mc});import yr from"node:os";import Im from"node:path";var Po=yr.platform()==="win32",Nc=yr.platform()==="darwin",Dc=yr.platform()==="linux",gr=yr.homedir();function Om(){return Po?process.env.APPDATA||Im.join(gr,"AppData","Roaming"):gr}function vm(){return Po?process.env.LOCALAPPDATA||Im.join(gr,"AppData","Local"):gr}function Fm(){return Nc?"macOS":Po?"Windows":Dc?"Linux":yr.platform()}function Mm(){return yr.arch()}import{randomUUID as rx}from"node:crypto";import{existsSync as Hc,readFileSync as Bm,writeFileSync as XC,unlinkSync as YC,renameSync as ZC}from"node:fs";import{isPersistentStorageEnabled as zm,isStatsEnabled as jm}from"@octocodeai/config";import{z as Y}from"zod";var $C=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),WC=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),ts=Y.record(Y.string(),Y.number()).default({}),VC=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:ts,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:ts}),ns=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:ts,charsSavedByTool:Y.record(Y.string(),$C).default({}),githubCacheHits:WC.default({hits:{},rateLimits:0}),packageRegistryFailures:ts,totalUsage:VC.optional()}),Nm=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:ns.optional()}),Dm=Y.object({version:Y.literal(1),stats:ns});function Hm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function KC(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:Hm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Hm(o),packageRegistryFailuresByRegistry:o}}function Rn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:KC(t)}}function Cn(){return Rn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var $n=ze.session,Wn=ze.stats;function Gm(e,t){let n=`${e}.tmp`;XC(n,JSON.stringify(t,null,2),{mode:384}),ZC(n,e)}function qC(e){let t=JSON.parse(e),n=Dm.safeParse(t);if(n.success)return Rn(n.data.stats);let r=ns.safeParse(t);return r.success?Rn(r.data):null}function JC(){if(!Hc(Wn))return Cn();try{let e=Bm(Wn,"utf8");return qC(e)??Cn()}catch{return Cn()}}function rs(e){if(!zm())return;yn(),jm()&&Gm(Wn,{version:e.version,stats:Rn(e.stats)});let{stats:t,...n}=e;Gm($n,n)}function Qm(){if(!zm()||!Hc($n))return null;try{let e=Bm($n,"utf8"),t=JSON.parse(e),n=Nm.safeParse(t);return n.success?{...n.data,stats:jm()?JC():Cn()}:null}catch{return null}}function Um(){let e=!1;for(let t of[$n,Wn])if(Hc(t))try{YC(t),e=!0}catch{return!1}return e}var ex=6e4,Lt=null,xn=!1,br=null,Gc=!1,To=null,Eo=null,Ao=null,os=!1;function tx(){Gc||(Gc=!0,To=()=>{Lo()},Eo=()=>{Lo()},Ao=()=>{Lo()},process.on("exit",To),process.on("SIGINT",Eo),process.on("SIGTERM",Ao))}function Bc(){To&&(process.removeListener("exit",To),To=null),Eo&&(process.removeListener("SIGINT",Eo),Eo=null),Ao&&(process.removeListener("SIGTERM",Ao),Ao=null),Gc=!1}function nx(){br||(br=setInterval(()=>{xn&&Lt&&(rs(Lt),xn=!1)},ex),br.unref())}function zc(){br&&(clearInterval(br),br=null)}function _o(){if(Lt)return Lt;let e=Qm();return e&&(Lt=e),e}function Sr(e){Lt=e,xn=!0,tx(),nx()}function ko(){xn&&Lt&&(rs(Lt),xn=!1)}function Lo(){if(!os&&xn&&Lt){os=!0;try{rs(Lt),xn=!1}catch{}finally{os=!1}}}function jc(){Lt=null,xn=!1,os=!1}function $m(){jc(),zc(),Bc()}var ox=1;function ix(e){return Rn(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 Wm(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 Vm(){let e=new Date().toISOString();return{version:ox,sessionId:rx(),createdAt:e,lastActiveAt:e,stats:Cn()}}function Km(){ko()}function Xm(){Lo()}function Ym(e){if(e?.forceNew){let r=Vm();return Sr(r),ko(),r}let t=_o();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return Sr(r),ko(),r}let n=Vm();return Sr(n),ko(),n}function Zm(){return _o()?.sessionId??null}function dt(e){let t=_o();if(!t)return{success:!1,session:null};let n=ix(t.stats),r=Rn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Wm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:sx(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:ax(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Wm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Sr(o),{success:!0,session:o}}function qm(e=1){return dt({toolCalls:e})}function Jm(e=1){return dt({errors:e})}function is(e=1){return dt({rateLimits:e})}function ef(e,t=1){return dt({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 dt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function as(e,t=1){return dt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function cs(e=1){return dt({githubCacheHits:{hits:{},rateLimits:e}})}function tf(e,t=1){return dt({packageRegistryFailures:{[e]:t}})}function nf(){let e=_o();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Cn()};return Sr(t),{success:!0,session:t}}function rf(){return jc(),zc(),Bc(),Um()}function of(){$m()}import{z as Ce}from"zod";var sf=Ce.looseObject({$schema:Ce.string().optional(),version:Ce.number().int().optional(),github:Ce.record(Ce.string(),Ce.unknown()).optional(),local:Ce.record(Ce.string(),Ce.unknown()).optional(),tools:Ce.record(Ce.string(),Ce.unknown()).optional(),network:Ce.record(Ce.string(),Ce.unknown()).optional(),lsp:Ce.record(Ce.string(),Ce.unknown()).optional(),output:Ce.record(Ce.string(),Ce.unknown()).optional()});import{existsSync as cx,readdirSync as lx,lstatSync as ux}from"node:fs";import{join as px}from"node:path";function Io(e){if(!cx(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=lx(r)}catch{continue}for(let i of o){let s=px(r,i);try{let a=ux(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function dx(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}import{getConfigSync as Uf}from"@octocodeai/config";var Vn="18.2.0";import{maskSensitiveData as xw}from"@octocodeai/octocode-engine/mask";import{mkdirSync as Nf,readFileSync as pw,renameSync as Hf,rmSync as Gf,statSync as dw,writeFileSync as mw}from"node:fs";import{join as qc}from"node:path";import{isPersistentStorageEnabled as Bf}from"@octocodeai/config";import{existsSync as No,readFileSync as Tx,writeFileSync as Ex,mkdirSync as Ax,rmSync as Mo,readdirSync as Lx,statSync as _x}from"node:fs";import{join as wn}from"node:path";import{join as ls}from"node:path";import{createHash as af}from"node:crypto";function fx(e){return Oo(e)}function Oo(e){return ls(e,"tmp","clone")}function us(e){return ls(e,"tmp","tree")}function hx(e){return e?`__sp_${af("sha256").update(e).digest("hex").substring(0,6)}`:""}function gx(e){if(!/[\\/]/.test(e))return e;let t=af("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function Qc(e,t,n,r,o){let i=`${gx(r)}${hx(o)}`;return ls(Oo(e),t,n,i)}function vo(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new Error("Tree cache identity must be a 40-character commit SHA.");return ls(us(e),t,n,r.toLowerCase())}import{readFileSync as yx,readdirSync as bx,renameSync as Sx,rmSync as uf,statSync as pf,writeFileSync as Rx}from"node:fs";import{join as Rr}from"node:path";var Cx=900*1e3,cf=300*1e3,df=".octocode-lock.json";function xx(e){return typeof e=="object"&&e!==null}function lf(e){try{return bx(e)}catch{return[]}}function Uc(e,t=process.pid,n=Date.now()){try{Rx(Rr(e,df),JSON.stringify({pid:t,createdAt:n}),{encoding:"utf8",mode:384})}catch{}}function wx(e){try{let t=JSON.parse(yx(Rr(e,df),"utf8"));return!xx(t)||!Number.isInteger(t.pid)||t.pid<=0||typeof t.createdAt!="number"?null:{pid:t.pid,createdAt:t.createdAt}}catch{return null}}function Px(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function ps(e,t=Date.now()){let n,r=wx(e);if(r){if(n=r.createdAt,t-n<=cf||Px(r.pid))return!1}else{try{n=pf(e).mtimeMs}catch{return!1}if(t-n<=cf)return!1}let o=`${e}.stale-${process.pid}-${t}`;try{return Sx(e,o),uf(o,{recursive:!0,force:!0}),!0}catch{return!1}}function $c(e,t=Date.now()){let n=Rr(e,"tmp","clone-tmp"),r=0;for(let i of lf(n)){let s=Rr(n,i);try{let a=pf(s);if(t-a.mtimeMs<=Cx)continue;uf(s,{recursive:!0,force:!0}),r++}catch{}}let o=Rr(e,"tmp","clone-locks");for(let i of lf(o))ps(Rr(o,i),t)&&r++;return r}var kx=1440*60*1e3,Ix=2*1024*1024*1024,Ox=50,ff=".octocode-clone-meta.json";function vx(e){return typeof e=="object"&&e!==null}function Fx(e){if(!vx(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 Wc(e){let t=wn(e,ff);if(!No(t))return null;try{return Fx(JSON.parse(Tx(t,"utf-8")))}catch{return null}}function Cr(e,t){try{Ex(wn(e,ff),JSON.stringify(t,null,2),"utf-8")}catch{}}function hf(e){return Date.now()<new Date(e.expiresAt).getTime()}function xr(e){let t=Wc(e);return t?hf(t)?No(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Mx(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return kx}function Nx(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Ix}function Dx(){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 Ox}function wr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Mx()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function Pn(e){let t=wn(e,"..");try{No(t)||Ax(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 ds(e){try{No(e)&&Mo(e,{recursive:!0,force:!0})}catch{}}function Fo(e){try{return _x(e).isDirectory()}catch{return!1}}function Kn(e){try{return Lx(e)}catch{return[]}}function*gf(e){for(let t of Kn(e)){let n=wn(e,t);if(Fo(n))for(let r of Kn(n)){let o=wn(n,r);if(Fo(o))for(let i of Kn(o)){let s=wn(o,i);Fo(s)&&(yield s)}}}}function mf(e){for(let t of[...Kn(e)]){let n=wn(e,t);if(Fo(n)){for(let r of[...Kn(n)]){let o=wn(n,r);if(Fo(o)&&Kn(o).length===0)try{Mo(o,{recursive:!0,force:!0})}catch{}}if(Kn(n).length===0)try{Mo(n,{recursive:!0,force:!0})}catch{}}}}function Hx(e){let t=0;for(let n of gf(e))try{let r=Wc(n);(!r||!hf(r))&&(Mo(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Gx(e){let t=[];for(let n of gf(e)){let r=Wc(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??Io(n)})}return t}function Bx(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{Mo(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function yf(e){if(!No(e))return 0;let t=0;try{t+=Hx(e)}catch{return t}mf(e);let n=Bx(Gx(e),Nx(),Dx());return t+=n,n>0&&mf(e),t}function ms(e){return yf(Oo(e))}function Pr(e){return yf(us(e))}import zx from"crypto";var jx="v2",Qx=new Set([]);function Ux(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(Qx.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function xe(e,t,n){let r=Vc(Ux(t)),o=n?`${n}:${r}`:r,i=zx.createHash("sha256").update(o).digest("hex");return`${jx}-${e}:${i}`}function Vc(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=>Vc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Vc(i,t)}`}).join(",")}}`)}import $x from"node-cache";var Wx=300*1e3,je=new $x({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),me={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},bf={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},it=new Map;function Vx(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Kx(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Xn(e){let t=Vx(e);if(!(!t||!Kx(t)))try{as(t,1)}catch{}}function fs(){let e=Date.now();for(let[t,n]of it.entries())e-n.startedAt>Wx&&it.delete(t)}function hs(e){return bf[e]||bf.default}function Yn(e,t,n){try{return je.set(e,t,n),me.sets++,me.totalKeys=je.keys().length,!0}catch{try{let r=je.keys();for(let o of r)je.get(o);return je.set(e,t,n),me.sets++,me.totalKeys=je.keys().length,!0}catch{return!1}}}import{createHash as Xx}from"node:crypto";import{chmod as Sf,mkdir as Cf,readFile as xf,readdir as Yx,rename as Rf,rm as Zx,stat as Kc,writeFile as wf}from"node:fs/promises";import{join as Do}from"node:path";import{isPersistentStorageEnabled as qx}from"@octocodeai/config";var Pf=1,Tf=5*1024*1024,Jx=5e3,ew=256*1024*1024,tw=1440*60*1e3,nw=900*1e3,Ef=".last-gc",_e={hits:0,misses:0,sets:0,errors:0,evictions:0};function gs(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Xc(){if(!qx())return!1;let e=process.env.OCTOCODE_DISK_CACHE?.trim().toLowerCase();return!(e==="false"||e==="0")}function Yc(e=gn()){return Do(e,"tmp","response")}function rw(e){return(e.match(/^v\d+-([^:]+):/)?.[1]??"default").replace(/[^a-zA-Z0-9._-]/g,"_")}function Af(e,t=gn()){let n=Xx("sha256").update(e).digest("hex");return Do(Yc(t),rw(e),n.slice(0,2),`${n}.json`)}function Lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ow(e,t){let n;try{n=JSON.parse(e)}catch{return null}return!Lf(n)||n.version!==Pf||n.key!==t||typeof n.createdAt!="number"||typeof n.expiresAt!="number"||typeof n.staleUntil!="number"||!("value"in n)||n.etag!==void 0&&typeof n.etag!="string"?null:n}async function en(e){try{await Zx(e,{force:!0,recursive:!0})}catch{}}async function ys(e,t={}){if(!Xc())return;let n=Af(e);try{let r=await Kc(n);if(!r.isFile()||r.size>gs("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",Tf)){await en(n),_e.errors++;return}let o=ow(await xf(n,"utf8"),e);if(!o){await en(n),_e.errors++;return}let i=Date.now();if(i>=o.staleUntil){await en(n),_e.evictions++,_e.misses++;return}if(i>=o.expiresAt&&!t.allowStale){_e.misses++;return}return _e.hits++,{value:o.value,...o.etag?{etag:o.etag}:{},state:i<o.expiresAt?"fresh":"stale",expiresAt:o.expiresAt}}catch(r){r.code!=="ENOENT"&&_e.errors++,_e.misses++;return}}async function Ho(e,t,n,r={}){if(!Xc())return!1;let o=Date.now(),i=Math.max(1,n*1e3),s=Math.max(i,(r.staleTtlSeconds??n)*1e3),a={version:Pf,key:e,createdAt:o,expiresAt:o+i,staleUntil:o+s,value:t,...r.etag?{etag:r.etag}:{}},c;try{c=JSON.stringify(a)}catch{return _e.errors++,!1}if(c===void 0||Buffer.byteLength(c)>gs("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",Tf))return!1;let l=Af(e),u=Do(l,".."),p=`${l}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{await Cf(u,{recursive:!0,mode:448}),await Sf(u,448),await wf(p,c,{encoding:"utf8",mode:384}),await Sf(p,384);try{await Rf(p,l)}catch(d){let m=d.code;if(m!=="EEXIST"&&m!=="EPERM")throw d;await en(l),await Rf(p,l)}return _e.sets++,!0}catch{return _e.errors++,await en(p),!1}}async function iw(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=await Yx(r,{withFileTypes:!0})}catch{continue}for(let i of o){let s=Do(r,i.name);i.isDirectory()?n.push(s):i.isFile()&&i.name!==Ef&&t.push(s)}}return t}async function _f(e,t,n){if(!Xc())return 0;let r=Yc(e),o=Do(r,Ef);if(n)try{let p=await Kc(o);if(t-p.mtimeMs<tw)return 0}catch{}let i=0,s=await iw(r),a=gs("OCTOCODE_DISK_CACHE_MAX_ENTRIES",Jx),c=gs("OCTOCODE_DISK_CACHE_MAX_SIZE",ew),l=[],u=0;for(let p of s)try{let d=await Kc(p);if(p.includes(".tmp-")){t-d.mtimeMs>nw&&(await en(p),i++);continue}let m=await xf(p,"utf8"),f;try{f=JSON.parse(m)}catch{f=null}if(!Lf(f)||typeof f.staleUntil!="number"||t>=f.staleUntil){await en(p),i++;continue}l.push({path:p,size:d.size,modified:d.mtimeMs}),u+=d.size}catch{}for(l.sort((p,d)=>p.modified-d.modified);l.length>a||u>c;){let p=l.shift();if(!p)break;await en(p.path),u-=p.size,i++}try{await Cf(r,{recursive:!0,mode:448}),await wf(o,String(t),{encoding:"utf8",mode:384})}catch{_e.errors++}return _e.evictions+=i,i}function PM(e=gn(),t=Date.now()){return _f(e,t,!0)}function kf(e=gn(),t=Date.now()){return _f(e,t,!1)}async function TM(e=gn()){await en(Yc(e))}function If(){return{..._e}}function Of(){_e.hits=0,_e.misses=0,_e.sets=0,_e.errors=0,_e.evictions=0}import{AsyncLocalStorage as sw}from"node:async_hooks";var bs=new sw;async function vf(e){let t={hit:!1};return{value:await bs.run({root:t,depth:0,role:"response"},e),cacheHit:t.hit}}function Ss(e,t="response"){let n=bs.getStore();return n?bs.run({root:n.root,depth:n.depth+1,role:t},e):e()}function tn(){let e=bs.getStore();e&&e.depth<=1&&e.role==="response"&&(e.root.hit=!0)}function aw(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return hs(n?.[1]??"default")}async function De(e,t,n={}){return Ss(()=>cw(e,t,n),n.cacheRole)}async function cw(e,t,n){if(n.skipCache)return await t();if(!n.forceRefresh){try{let a=je.get(e);if(a!==void 0)return me.hits++,Xn(e),tn(),a}catch{}let s=await ys(e);if(s?.state==="fresh")return me.hits++,Xn(e),tn(),Yn(e,s.value,Math.max(1,(s.expiresAt-Date.now())/1e3)),s.value}fs();let r=it.get(e);if(r)return r.promise;let o=Symbol(e),i=(async()=>{try{let s=await t();if(n.forceRefresh||me.misses++,(n.shouldCache??(()=>!0))(s)){let c=aw(e,n.ttl);Yn(e,s,c),await Ho(e,s,c)}return s}finally{it.get(e)?.requestId===o&&it.delete(e)}})();return it.set(e,{promise:i,startedAt:Date.now(),requestId:o}),i}import lw from"node-cache";var Ff=86400;function Mf(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return hs(n?.[1]??"default")}var Tr=new lw({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function Rs(e,t,n={}){return Ss(()=>uw(e,t,n),n.cacheRole)}async function uw(e,t,n){if(n.skipCache)return(await t({})).value;let r;if(!n.forceRefresh){try{let a=je.get(e);if(a!==void 0)return me.hits++,Xn(e),tn(),a}catch{}if(r=await ys(e,{allowStale:!0}),r?.state==="fresh")return me.hits++,Xn(e),tn(),Yn(e,r.value,Math.max(1,(r.expiresAt-Date.now())/1e3)),r.etag&&Tr.set(e,{data:r.value,etag:r.etag}),r.value}fs();let o=it.get(e);if(o)return o.promise;let i=Symbol(e),s=(async()=>{try{let c=(n.forceRefresh?void 0:Tr.get(e))??(r?{data:r.value,etag:r.etag}:void 0),l=await t({ifNoneMatch:!n.forceRefresh&&c?.etag?c.etag:void 0});if(l.notModified&&c){me.hits++,Xn(e),tn();let p=Mf(e,n.ttl);return Yn(e,c.data,p),await Ho(e,c.data,p,{...c.etag?{etag:c.etag}:{},staleTtlSeconds:Ff}),c.data}if(n.forceRefresh||me.misses++,(n.shouldCache??(()=>!0))(l.value)){let p=Mf(e,n.ttl);Yn(e,l.value,p),Tr.set(e,{data:l.value,etag:l.etag}),await Ho(e,l.value,p,{...l.etag?{etag:l.etag}:{},staleTtlSeconds:Ff})}return l.value}finally{it.get(e)?.requestId===i&&it.delete(e)}})();return it.set(e,{promise:s,startedAt:Date.now(),requestId:i}),s}function zM(){je.flushAll(),Tr.flushAll(),it.clear(),me.hits=0,me.misses=0,me.sets=0,me.totalKeys=0,me.lastReset=new Date,Of()}function Tn(e){let t=je.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||je.del(r)>0&&n++}return n>0&&(me.totalKeys=je.keys().length),n}function jM(){return Tn("local-")}function QM(){return Tn("lsp-")}function UM(){let e=0;return e+=Tn("gh-api-"),e+=Tn("bb-api-"),e+=Tn("gh-repo-"),e+=Tn("bb-repo-"),e+=Tn("github-user"),e+=Tn("npm-search"),Tr.flushAll(),e}function $M(){let e=me.hits+me.misses,t=If();return{...me,hitRate:e>0?me.hits/e*100:0,cacheSize:je.keys().length,diskHits:t.hits,diskMisses:t.misses,diskSets:t.sets,diskErrors:t.errors,diskEvictions:t.evictions}}var Df=1440*60*1e3,fw=60*1e3,hw=900*1e3,gw=".last-cache-maintenance",yw=".cache-maintenance.lock",Er=null,xs=null,Cs=new Map;function zf(e){return qc(e,"tmp")}function jf(e){return qc(zf(e),gw)}function bw(e){try{let t=Number(pw(jf(e),"utf8"));return Number.isFinite(t)&&t>=0?t:null}catch{return null}}function Zc(e,t=Date.now()){let n=bw(e);return n===null?0:Math.min(Df,Math.max(0,n+Df-t))}function Sw(e,t){let n=zf(e),r=qc(n,yw);try{Nf(n,{recursive:!0,mode:448})}catch{return null}let o=()=>{try{return Nf(r,{mode:448}),!0}catch{return!1}};if(o())return r;try{if(t-dw(r).mtimeMs<=hw)return null;let i=`${r}.stale-${process.pid}-${t}`;Hf(r,i),Gf(i,{recursive:!0,force:!0})}catch{return null}return o()?r:null}function Rw(e,t){let n=jf(e),r=`${n}.tmp-${process.pid}-${t}`;mw(r,String(t),{encoding:"utf8",mode:384}),Hf(r,n)}async function Cw(e,t){if(Zc(e,t)>0)return!1;let n=Sw(e,t);if(!n)return!1;try{if(Zc(e,t)>0)return!1;try{return ms(e),Pr(e),$c(e,t),await kf(e,t),Rw(e,t),!0}catch{return!1}}finally{try{Gf(n,{recursive:!0,force:!0})}catch{}}}function Ar(e,t=Date.now()){if(!Bf())return Promise.resolve(!1);let n=Cs.get(e);if(n)return n;let r=Cw(e,t).finally(()=>{Cs.get(e)===r&&Cs.delete(e)});return Cs.set(e,r),r}function Qf(e){if(xs!==e)return;let t=Math.max(fw,Zc(e));Er=setTimeout(()=>{Er=null,Ar(e).finally(()=>{Qf(e)})},t),Er.unref()}function iN(e){Bf()&&xs===null&&(xs=e,Ar(e).finally(()=>{Qf(e)}))}function sN(){xs=null,Er&&clearTimeout(Er),Er=null}var En=null,Lr=null,Jc=Sn;function fN(e){e.resolveTokenFull&&(Jc=e.resolveTokenFull)}function hN(){Jc=Sn}var ww=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function el(){try{let e=await Jc({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:ww.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function $f(){if(En!==null)return;if(Lr!==null)return Lr;let e=(async()=>{let t=Uf(),n=await el();En={version:Vn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone&&t.storage.mode==="persistent",tokenSource:n.source},await Ar(At())})();Lr=e;try{await e}catch(t){throw Lr===e&&(En=null,Lr=null),t}}function gN(){En=null,Lr=null}function Go(){if(!En){let e=xw(Tc.NOT_INITIALIZED.message);throw new Error(e)}return En}async function tl(){return(await el()).token}function yN(){return Go().enableLocal}function Wf(){let e=Go();return e.enableLocal&&e.enableClone}async function bN(){return En!==null?En.tokenSource:(await el()).source}function nl(){return"github"}function rl(){let e=Uf().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}function An(e){(e.provider?dt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):is(1)).session&&e.provider==="github"&&cs(1)}function Vf(e){dt({packageRegistryFailures:{[e]:1}})}function qf(e){return Ew("sha256").update(e).digest("hex").substring(0,16)}async function ke(e){let t=e?.token??await tl(),n=t?qf(t):"anon",r=Go().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var Aw=Pw.plugin(Tw),Lw=300*1e3,ol=50,_w=60*1e3;function Jf(e){return Date.now()-e.createdAt>Lw}var jt=new Map,Ln=null;function eh(){for(let[e,t]of jt.entries())Jf(t)&&jt.delete(e);if(jt.size>ol){let e=jt.size-ol,t=0;for(let[n]of jt){if(t>=e)break;jt.delete(n),t++}}}function kw(){Ln||(Ln=setInterval(eh,_w),typeof Ln=="object"&&"unref"in Ln&&Ln.unref())}var Kf=3,Xf=60;function Yf(e,t,n){An({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var Iw=()=>({onRateLimit:(e,t,n,r)=>(Yf("primary",e,t),r<Kf&&e<Xf),onSecondaryRateLimit:(e,t,n,r)=>(Yf("secondary",e,t),r<Kf&&e<Xf)});function Ow(e){let t=Go(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Vn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:Iw(),log:r,...e&&{auth:e}};return new Aw(o)}async function $(e){kw();let t=e?.token??await tl(),n=t?qf(t):"ANONYMOUS",r=jt.get(n);if(r&&!Jf(r))return r.client;jt.size>=ol&&eh();let o=Ow(t??void 0);return jt.set(n,{client:o,createdAt:Date.now()}),o}var vw=200,Fw=300*1e3,Zn=new Map;async function Be(e,t,n){let o=`${await ke(n)}:${e}/${t}`,i=Zn.get(o);if(i&&i.expiresAt>Date.now())return i.branch;i&&Zn.delete(o);let s=await $(n);try{let{data:c}=await s.rest.repos.get({owner:e,repo:t}),l=c.default_branch;return Zf(o,l),l}catch{}let a=["main","master"];for(let c of a)try{return await s.rest.repos.getBranch({owner:e,repo:t,branch:c}),Zf(o,c),c}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Zf(e,t){if(Zn.size>=vw){let n=Zn.keys().next().value;n!==void 0&&Zn.delete(n)}Zn.set(e,{branch:t,expiresAt:Date.now()+Fw})}function _N(){jt.clear(),Zn.clear(),Ln&&(clearInterval(Ln),Ln=null)}import{ContentSanitizer as Jw}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as Mw}from"node:module";var Nw=Mw(import.meta.url),th="@octocodeai/octocode-engine",Dw=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??Nw(th),ws,Hw=Dw,il=class extends Error{constructor(n){super(`Failed to load native dependency ${th}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function te(){if(ws)return ws;try{return ws=Hw(),ws}catch(e){throw new il(e)}}var D={applyContentViewMinification(e,t){return te().applyContentViewMinification(e,t)},applyMinification(e,t){return te().applyMinification(e,t)},minifyContent(e,t){return te().minifyContent(e,t)},minifyContentSync(e,t){return te().minifyContentSync(e,t)},minifyContentResult(e,t){return te().minifyContentResult(e,t)},minifyMarkdownCore(e){return te().minifyMarkdownCore(e)},extractSignatures(e,t){return te().extractSignatures(e,t)},extractJsSymbols(e,t){return te().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return te().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return te().extractGraphFacts(e,t)},scanGraphFacts(e){return te().scanGraphFacts(e)},getSupportedJsTsExtensions(){return te().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return te().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return te().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return te().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return te().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return te().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return te().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return te().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return te().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return te().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return te().parseRipgrepJson(e,t)},searchRipgrep(e){return te().searchRipgrep(e)},queryFileSystem(e){return te().queryFileSystem(e)},extractMatchingLines(e,t,n){return te().extractMatchingLines(e,t,n)},filterPatch(e,t){return te().filterPatch(e,t)},computeLineDiff(e,t){return te().computeLineDiff(e,t)},charToByteOffset(e,t){return te().charToByteOffset(e,t)},byteToCharOffset(e,t){return te().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return te().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return te().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return te().SIGNATURES_ONLY_HINT}};import{RequestError as rh}from"octokit";var K={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},Ie={[K.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[K.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[K.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[K.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[K.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[K.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[K.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[K.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[K.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[K.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},nh={401:K.AUTH_REQUIRED,403:K.FORBIDDEN_PERMISSIONS,404:K.NOT_FOUND,422:K.INVALID_REQUEST,502:K.SERVER_UNAVAILABLE,503:K.SERVER_UNAVAILABLE,504:K.SERVER_UNAVAILABLE},sl={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},al={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ps={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var Gw=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function Qt(e){if(!(e instanceof rh)||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 Gw.some(o=>r.includes(o))})}function J(e){return e instanceof rh?Bw(e):e instanceof Error?Kw(e):{error:typeof e=="string"?e:Ie[K.UNKNOWN].message,type:"unknown"}}function Bw(e){let{status:t,message:n,response:r}=e;if(t===403)return jw(n,r);if(t===429)return zw(n,r);let o=nh[t];return o?Vw(o,t):_r(K.UNKNOWN,{error:n||Ie[K.UNKNOWN].message,status:t})}function cl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function zw(e,t){let n=t?.headers,r=cl(n,"retry-after"),o=cl(n,"x-ratelimit-reset"),i=cl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ps.RESET_BUFFER_SECONDS,0):void 0);return An({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),_r(K.RATE_LIMIT_PRIMARY,{error:e||Ie[K.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Ie[K.RATE_LIMIT_PRIMARY].suggestion})}function jw(e,t){let n=t?.headers;if(al.SECONDARY.test(e))return Qw(n);let r=n?.["x-ratelimit-remaining"],o=Ww(t);return r!==void 0&&String(r)==="0"||o?Uw(n):$w(n)}function Qw(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ps.SECONDARY_FALLBACK_SECONDS:t;return An({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),_r(K.RATE_LIMIT_SECONDARY,{error:Ie[K.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Ie[K.RATE_LIMIT_SECONDARY].suggestion})}function Uw(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)+Ps.RESET_BUFFER_SECONDS,0):void 0,i=r?Ie[K.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Ie[K.RATE_LIMIT_PRIMARY].messageWithoutTime;return An({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),_r(K.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Ie[K.RATE_LIMIT_PRIMARY].suggestion})}function $w(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Ie[K.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Xw(String(t),String(n))),_r(K.FORBIDDEN_PERMISSIONS,{error:Ie[K.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Ww(e){return e?.data?.errors?.some(n=>n.type===al.GRAPHQL_TYPE)??!1}function Vw(e,t){let n=Ie[e];return _r(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function Kw(e){return sl.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Ie[K.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Ie[K.NETWORK_CONNECTION_FAILED].suggestion}:sl.TIMEOUT.some(t=>e.message.includes(t))?{error:Ie[K.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Ie[K.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function _r(e,t){return{type:"http",...t}}function Xw(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?Ie[K.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Ie[K.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function oh(e){return`user:${e}`}var Yw=/[@/]/,Zw=/^[A-Za-z0-9_-]+$/;function ll(e){return e.startsWith('"')||Zw.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var nn=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(oh(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=Yw.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var qw=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ul=class extends nn{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(ll))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(qw):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}},pl=class extends nn{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(ll)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars");let n=t;return typeof n.size=="string"&&this.queryParts.push(`size:${n.size}`),typeof n.created=="string"&&this.queryParts.push(`created:${n.created}`),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`),typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function dl(e){return new ul().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ml(e){return new pl().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var fl=class extends nn{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function hl(e){return new fl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function gl(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var yl=class extends nn{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function bl(e){return new yl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Sl(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as qN,DISCOVERY_IGNORED_FILE_NAMES as JN,DISCOVERY_IGNORED_FOLDER_NAMES as eD,getDiscoveryExtension as ih,shouldIgnoreDiscoveryDir as Bo,shouldIgnoreDiscoveryFile as kr}from"@octocodeai/octocode-engine/security";var sh=Symbol.for("octocode.rawResponseChars");function B(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function ah(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function W(e,t){let n=typeof t=="number"?ah(t):B(t);if(n===void 0)return e;try{Object.defineProperty(e,sh,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ie(e){if(!(typeof e!="object"||e===null))return ah(e[sh])}function Ir(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function ch(e){let t=Ir(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function Or(e){let t=Ir(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function lh(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var uh=30;async function ph(e,t,n){let r=await ke(t),o=xe("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await De(o,async()=>await eP(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function eP(e,t){try{let n=await $(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(g=>g&&g.trim()).length===0)return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let r=dl(e);if(!r.trim())return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:uh,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 tP(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,p=Math.min(u,1e3),d=Math.ceil(p/o),m=Math.min(i,Math.max(1,d)),f=m<d,h=Math.min(p,d*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:m,totalPages:d,perPage:o,totalMatches:p,reportedTotalMatches:u,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:u>p,hasMore:f,...f?{nextPage:m+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Ir(a.headers),rawResponseChars:B(a.data)}}catch(n){if(Qt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:uh,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 J(n)}}async function tP(e,t){let n=nP(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(m=>!kr(m.path)),c=0,l=0,u=await Promise.allSettled(a.map(async m=>{s.add(m.path);let f=[],h=await Promise.allSettled((m.text_matches||[]).map(async C=>{let P=C.fragment,T=Jw.sanitizeContent(P||"",m.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${m.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${m.path}: ${k}`));try{let k=await D.minifyContent(P||"",m.path);P=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let E=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:P||"",positions:lh(C.fragment||"",E,P||"")}})),y=h.filter(C=>C.status==="fulfilled").map(C=>C.value),g=h.filter(C=>C.status==="rejected").length;g>0&&(l+=g);let S=m,R=Array.from(new Set(f));return{path:m.path,matches:y,url:m.html_url,repository:{nameWithOwner:m.repository.full_name,url:m.repository.url,pushedAt:m.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...R.length>0&&{minificationType:R.join(",")}}})),p=u.filter(m=>m.status==="fulfilled").map(m=>m.value);c=u.filter(m=>m.status==="rejected").length;let d={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let m=n.full_name.split("/");return m.length===2&&m[0]&&m[1]?{owner:m[0],repo:m[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(d.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&&(d.matchLocations=Array.from(r)),d.minified=!o,d.minificationFailed=o,i.length>0&&(d.minificationTypes=Array.from(new Set(i))),d}function nP(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{readdirSync as rP,statSync as dh}from"node:fs";import{join as oP}from"node:path";var zo=50,Ts=5*1024*1024,Rl=300*1024,mh=5,iP=1e4,fh=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"]),Cl={maxDirectoryFiles:zo,maxTotalSize:Ts,maxFileSize:Rl};function xl(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function hh(e){return Object.values(e).every(t=>t===0)}function wl(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 gh(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 aP(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var sP=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function aP(e,t){try{let o=new URL(e);if(!sP.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(),iP);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 yh(e,t){let n=[],r=0;function o(i){let s;try{s=rP(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=oP(i,a);try{let l=dh(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 bh(e){try{return dh(e).size}catch{return 0}}import{writeFileSync as uP,mkdirSync as Rh,existsSync as Pl,rmSync as pP}from"node:fs";import{join as Ch,dirname as dP,resolve as xh,sep as wh}from"node:path";var cP=60;async function Sh(e,t,n,r){let s=(await(await $(r)).rest.repos.getCommit({owner:e,repo:t,ref:n})).data.sha;if(typeof s!="string"||!/^[0-9a-f]{40}$/i.test(s))throw new Error(`GitHub returned an invalid commit SHA for ref "${n}".`);return s.toLowerCase()}async function lP(e,t,n,r){try{return{commitSha:await Sh(e,t,n,r),resolvedRef:n}}catch(o){if(!(n==="main"||n==="master"))throw o;let s=await Be(e,t,r);if(s===n)throw o;return{commitSha:await Sh(e,t,s,r),resolvedRef:s}}}async function Es(e,t,n,r,o=!1){let i=await ke(r),s=xe("gh-api-ref-resolution",{owner:e,repo:t,ref:n,auth:i});return De(s,()=>lP(e,t,n,r),{ttl:cP,forceRefresh:o,cacheRole:"helper"})}async function Tl(e,t,n,r,o,i=!1){let s=At(),{commitSha:a,resolvedRef:c}=await Es(e,t,r,o,i),l=vo(s,e,t,a),u=xh(Ch(l,n));if(!u.startsWith(l+wh)&&u!==l)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let p=xr(l);if(p.hit&&p.meta.commitSha===a&&!i&&Pl(u)){let w=yh(u,l),L=xl();return{localPath:u,repoRoot:l,files:w.files,fileCount:w.fileCount,totalSize:w.totalSize,complete:!0,verified:!1,commitSha:a,directoryEntryCount:w.fileCount,eligibleFileCount:w.fileCount,savedFileCount:w.fileCount,skipped:L,limits:Cl,warnings:wl(!0,!1),cached:!0,expiresAt:p.meta.expiresAt,owner:e,repo:t,branch:c,directoryPath:n}}let d=await $(o),{data:m}=await d.rest.repos.getContent({owner:e,repo:t,path:n,ref:a});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=m,h=xl(),y=[];for(let w of f){if(w.type!=="file"){h.nonFile+=1;continue}if(!w.download_url){h.missingDownloadUrl+=1;continue}if(w.size>Rl){h.oversized+=1;continue}let L=ih(w.name,{lowercase:!0,leadingDot:!0});if(fh.has(L)){h.binary+=1;continue}y.push(w)}h.fileLimit=Math.max(0,y.length-zo);let g=y.slice(0,zo),S=o?.token,R=await gh(g,mh,S);h.fetchFailed=g.length-R.length;let C=0,P=[];for(let w=0;w<R.length;w+=1){let{entry:L,content:O}=R[w];if(C+O.length>Ts){h.totalSizeLimit=R.length-w;break}C+=O.length,P.push({entry:L,content:O})}Pr(s),Pn(l),Pl(u)&&pP(u,{recursive:!0,force:!0}),Rh(u,{recursive:!0,mode:448});let T=[];for(let{entry:w,content:L}of P){let O=xh(Ch(l,w.path));if(!O.startsWith(l+wh)){h.pathTraversal+=1;continue}let v=dP(O);Pl(v)||Rh(v,{recursive:!0,mode:448}),uP(O,L,"utf-8"),T.push({path:w.path,size:L.length,type:"file"})}let E=wr(e,t,c,"treeFetch",void 0,void 0,a);Cr(l,E);let k=hh(h),x=k,b=h.nonFile>0;return{localPath:u,repoRoot:l,files:T,fileCount:T.length,totalSize:C,complete:k,verified:x,commitSha:a,...b?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:y.length,savedFileCount:T.length,skipped:h,limits:Cl,warnings:wl(k,x),cached:!1,expiresAt:E.expiresAt,owner:e,repo:t,branch:c,directoryPath:n}}import{writeFileSync as WP,mkdirSync as VP,existsSync as Fh}from"node:fs";import{join as KP,dirname as XP,resolve as YP,sep as ZP}from"node:path";import{RequestError as Kl}from"octokit";import{z as El}from"zod";var mt={GITHUB_SEARCH:"ghSearch",GITHUB_FETCH_CONTENT:"ghGetFileContent",GITHUB_SEARCH_HISTORY:"ghSearchHistory",GITHUB_GET_HISTORY_ITEM:"ghGetHistoryItem",PACKAGE_SEARCH:"npmSearch",GITHUB_CLONE_REPO:"ghCloneRepo",LOCAL_SEARCH:"localSearch",LOCAL_ANALYZE_GRAPH:"localAnalyzeGraph",LOCAL_FETCH_CONTENT:"localGetFileContent",LSP_GET_SEMANTIC_CONTENT:"lspGetSemantics"},As=El.object({goal:El.string().optional().describe("What this query should accomplish."),reasoning:El.string().optional().describe("Why this query advances the goal.")}),qn=Object.fromEntries(Object.entries(As.shape).map(([e,t])=>[e,t.description??""]));var mP={ghSearch:["Use only fields listed for the selected operation.","match: code=file|path; repositories=name|description|readme.","code cannot select branch; it searches GitHub's indexed default branch."],localSearch:["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."],localAnalyzeGraph:["dependencies | dependents -> requires file; depth applies.","path -> requires file + target.","deadCode/reachability use entrypoints and includeTests as roots."],localGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString."],lspGetSemantics:["workspaceSymbol needs symbolName and may use workspaceRoot.","documentSymbols/diagnostic need uri.","definition | references | hover | callers | callees | callHierarchy | implementation | typeDefinition | supertypes | subtypes -> requires uri + symbolName + lineHint."],ghGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString.",'type:"directory" materializes; extraction fields read files.'],npmSearch:["Set exactly one of packageName or keywords."]};function Ls(e){return[...mP[e]??[]]}var fP={ghSearch:[{name:"code",when:"Search code contents or file paths",requires:["operation"],excludes:["branch"],fields:["keywords","owner","repo","extension","filename","path","language","match","pageSize","page","concise"],example:{operation:"code",keywords:["toolSchemas"],owner:"bgauryy",repo:"octocode"}},{name:"repositories",when:"Discover repositories",requires:["operation"],fields:["keywords","topics","language","owner","stars","forks","goodFirstIssues","updated","created","size","match","sort","pageSize","page","archived","visibility","license","concise"],example:{operation:"repositories",keywords:["octocode"]}},{name:"tree",when:"Browse a known repository tree",requires:["operation","owner","repo"],fields:["owner","repo","branch","path","maxDepth","page","pageSize","include"],example:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}],localSearch:[{name:"text",when:"Search lexical text or regular expressions",requires:["operation","path","searchText"],example:{operation:"text",path:".",searchText:"toolSchemas"}},{name:"structural",when:"Match AST structure",requires:["operation","path","pattern"],example:{operation:"structural",path:".",pattern:"console.log($A)",langType:"typescript"}},{name:"files",when:"Discover paths by name or metadata",requires:["operation","path"],example:{operation:"files",path:".",names:["*.ts"]}},{name:"tree",when:"Browse a directory tree",requires:["operation","path"],example:{operation:"tree",path:".",maxDepth:5}}],localAnalyzeGraph:[{name:"dependencies",when:"Find files imported by a file",requires:["path","operation","file"],example:{path:".",operation:"dependencies",file:"src/index.ts"}},{name:"dependents",when:"Find files importing a file",requires:["path","operation","file"],example:{path:".",operation:"dependents",file:"src/index.ts"}},{name:"path",when:"Find a shortest dependency path",requires:["path","operation","file","target"],example:{path:".",operation:"path",file:"src/a.ts",target:"src/b.ts"}},{name:"cycles",when:"Find dependency cycles",requires:["path","operation"],example:{path:".",operation:"cycles"}},{name:"deadCode",when:"Find unreachable file candidates",requires:["path","operation"],example:{path:".",operation:"deadCode"}},{name:"reachability",when:"Find files unreachable from selected roots",requires:["path","operation","entrypoints"],example:{path:".",operation:"reachability",entrypoints:["src/index.ts"]}}],lspGetSemantics:[{name:"anchored",when:"Query a named symbol near a source line",requires:["uri","type","symbolName","lineHint"],example:{uri:"src/index.ts",type:"definition",symbolName:"main",lineHint:1}},{name:"document",when:"Query a whole document",requires:["uri","type"],example:{uri:"src/index.ts",type:"documentSymbols"}},{name:"workspace",when:"Search symbols across the workspace",requires:["workspaceRoot","type","symbolName"],example:{workspaceRoot:".",type:"workspaceSymbol",symbolName:"Schema"}}]};function Al(e){return fP[e]??[]}import{z as _s}from"zod";var vr=100,jo=1e3,Ph=1e8,Th=5e4,Ze=1e9,Ll=1e5,Qo=20,ks=100,Uo=1e4,Jn=50,_t=100,kt=30,_l=200,kl=100;var Il=1e5,Ol=500,Is=1e5,vl=1e3,Fl=20,Ml=100,Nl=20;function fe(e){return{...e,description:e.instructions}}function H(e,t){return _s.number().int().min(e).max(t)}var Ae=_s.array(_s.string()).optional();function Le(){return H(1,jo).default(1)}function Qe(){return H(1,jo).optional()}function Os(){return H(0,vr).optional()}function Fr(){return H(1,Ze).optional()}function qe(){return H(0,Ph).optional()}function yt(){return H(1,Th).optional()}var ee=As.shape,hP=new Set(Object.keys(ee)),gP={owner:"Repository owner (user or org).",repo:"Repository name, without the owner.",branch:"Branch, tag, or commit SHA; omit for the default branch.",path:"Target path. GitHub tools: repo-relative, exact case, no leading slash. Local tools: absolute path.",page:"Result page, 1-based. Advance only while pagination.hasMore.",itemsPerPage:"Items per result page.",limit:"Total result cap applied before pagination.",pageSize:"Results returned in one page.",contextLines:"Extra source lines around each match/anchor.",charLength:"Content-window length; continue with the returned offset when partial.",charOffset:"Content-window start; copy the returned offset. A partial window cannot prove absence."};function U(e,t,n=""){let r={};for(let o of Object.keys(t)){let i=t[o],s=n?`${n}.${o}`:o,c=n===""&&hP.has(o)?qn[s]:e[s]??(i.description?void 0:gP[o]);r[o]=c?i.describe(c):i}return _s.object(r).strict()}function vs(e,t){let n=e.fullContent===!0,r=e.matchString!==void 0,o=e.startLine!==void 0||e.endLine!==void 0;n&&r&&t.addIssue({code:"custom",message:"Choose fullContent or matchString.",path:["matchString"]}),n&&o&&t.addIssue({code:"custom",message:"Choose fullContent or startLine/endLine.",path:["startLine"]}),r&&o&&t.addIssue({code:"custom",message:"Choose matchString or startLine/endLine.",path:["startLine"]}),e.startLine===void 0!=(e.endLine===void 0)&&t.addIssue({code:"custom",message:"Set startLine and endLine together.",path:[e.startLine===void 0?"startLine":"endLine"]}),e.startLine!==void 0&&e.endLine!==void 0&&e.endLine<e.startLine&&t.addIssue({code:"custom",message:"Set endLine greater than or equal to startLine.",path:["endLine"]})}import{z as Fs}from"zod";import{z as _n}from"zod";var yP={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",path:"Repo path prefix, not a full file path.",match:'For ghSearch operation:"code": "file" returns snippets and character matchIndices; "path" returns paths only. Operation:"repositories" uses text-field names.',extension:'File extension filter, e.g. "ts" (no dot).',filename:"Exact filename filter.",language:'GitHub language filter, e.g. "typescript".',concise:'Flat "owner/repo:path" rows.',limit:"Results per page (paginate with page)."},kn=U(yP,{...ee,keywords:Ae,owner:_n.string().optional(),repo:_n.string().optional(),extension:_n.string().optional(),filename:_n.string().optional(),path:_n.string().optional(),language:_n.string().optional(),match:_n.enum(["file","path"]).default("file"),limit:H(1,_t).default(kt),page:Le(),concise:_n.boolean().optional()});import{z as Je}from"zod";var bP={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",topicsToSearch:"ANDed topic filters; metadata can be sparse.",match:'For ghSearch operation:"repositories": text fields to search are name, description, and readme; readme is broader and slower. Operation:"code" uses "file" or "path".',sort:"stars, forks, updated, help-wanted-issues, best-match.",language:'Primary language filter, e.g. "rust".',stars:'Star range: ">100", "10..50".',forks:'Fork range: ">50", "10..100".',goodFirstIssues:'Good-first-issue count range, e.g. ">5".',updated:'Last push date: ">2024-01-01" or "a..b".',created:'Creation date: ">2023-01-01" or "a..b".',size:'Repo size in KB: ">1000", "50..500".',license:'SPDX id, e.g. "mit".',archived:"true = archived only; default excludes archived.",visibility:'"public" or "private" (private needs token scope).',concise:'Flat "owner/repo" rows for triage.',limit:"Results per page (paginate with page)."},rn=U(bP,{...ee,keywords:Ae,topicsToSearch:Ae,language:Je.string().optional(),owner:Je.string().optional(),stars:Je.string().optional(),forks:Je.string().optional(),goodFirstIssues:Je.string().optional(),updated:Je.string().optional(),created:Je.string().optional(),size:Je.string().optional(),match:Je.array(Je.enum(["name","description","readme"])).optional(),sort:Je.enum(["stars","forks","help-wanted-issues","updated","best-match"]).default("best-match"),limit:H(1,_t).default(kt),page:Le(),archived:Je.boolean().optional(),visibility:Je.enum(["public","private"]).optional(),license:Je.string().optional(),concise:Je.boolean().optional()});import{z as Mr}from"zod";var SP={path:'Repo-relative directory; ""/"." for root.',branch:"Ref; fallback warning means default branch was used.",maxDepth:"Tree recursion depth.",page:"Advance only on hasMore.",include:"Optional sizes, languages, contributors, branches, or tags; each adds an API call."},er=U(SP,{...ee,owner:Mr.string(),repo:Mr.string(),branch:Mr.string().optional(),path:Mr.string().optional(),maxDepth:H(0,Nl).optional(),page:Le(),itemsPerPage:H(1,_l).default(kl),include:Mr.array(Mr.enum(["sizes","languages","contributors","branches","tags"])).optional()});var JD=fe({name:"ghSearch",type:"Github",shortDescription:"Search GitHub code or repositories, or browse a repository tree.",instructions:`Choose operation:"code" for code contents or file paths, "repositories" to discover repositories, or "tree" to browse a known repository.
10
+ `)}return null}async function Oc(e=bn){let t=await Sn({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function vc(e=bn,t=hr){let n=await Sn({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}async function Fc(e){let t=Bt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=Jt();return r.credentials[t]=n,_c(r),wo(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Un(e="github.com",t){let n=Bt(e);if(!t?.bypassCache){let i=lm(n);if(i!==void 0)return i}let o=Jt().credentials[n]||null;return um(n,o),o}function Ji(e="github.com"){let t=Bt(e);return Jt().credentials[t]||null}async function xm(e="github.com"){let t=Bt(e),n=!1,r=Jt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Sm():_c(r),n=!0),wo(t),{success:n,deletedFromFile:n}}async function wm(){let e=Jt();return Object.keys(e.credentials)}function Pm(){let e=Jt();return Object.keys(e.credentials)}async function Tm(e="github.com"){return await Un(e)!==null}function Em(e="github.com"){return Ji(e)!==null}async function es(e,t){let n=await Un(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Fc(n),!0):!1}function Am(){return qt}async function Lm(e="github.com"){let t=await Un(e);return!t||!t.token||Zt(t)?null:t.token.token}function _m(e="github.com"){let t=Ji(e);return!t||!t.token||Zt(t)?null:t.token.token}async function km(e,t){return kc({getCredentials:Un,updateToken:es},e,t)}async function Mc(e,t){return Rm({getCredentials:Un,updateToken:es},e,t)}Cm({getTokenWithRefresh:Mc});import yr from"node:os";import Im from"node:path";var Po=yr.platform()==="win32",Nc=yr.platform()==="darwin",Dc=yr.platform()==="linux",gr=yr.homedir();function Om(){return Po?process.env.APPDATA||Im.join(gr,"AppData","Roaming"):gr}function vm(){return Po?process.env.LOCALAPPDATA||Im.join(gr,"AppData","Local"):gr}function Fm(){return Nc?"macOS":Po?"Windows":Dc?"Linux":yr.platform()}function Mm(){return yr.arch()}import{randomUUID as rx}from"node:crypto";import{existsSync as Hc,readFileSync as Bm,writeFileSync as XC,unlinkSync as YC,renameSync as ZC}from"node:fs";import{isPersistentStorageEnabled as zm,isStatsEnabled as jm}from"@octocodeai/config";import{z as Y}from"zod";var $C=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),WC=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),ts=Y.record(Y.string(),Y.number()).default({}),VC=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:ts,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:ts}),ns=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:ts,charsSavedByTool:Y.record(Y.string(),$C).default({}),githubCacheHits:WC.default({hits:{},rateLimits:0}),packageRegistryFailures:ts,totalUsage:VC.optional()}),Nm=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:ns.optional()}),Dm=Y.object({version:Y.literal(1),stats:ns});function Hm(e){return Object.values(e).reduce((t,n)=>t+n,0)}function KC(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:Hm(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Hm(o),packageRegistryFailuresByRegistry:o}}function Rn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:KC(t)}}function Cn(){return Rn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var $n=ze.session,Wn=ze.stats;function Gm(e,t){let n=`${e}.tmp`;XC(n,JSON.stringify(t,null,2),{mode:384}),ZC(n,e)}function qC(e){let t=JSON.parse(e),n=Dm.safeParse(t);if(n.success)return Rn(n.data.stats);let r=ns.safeParse(t);return r.success?Rn(r.data):null}function JC(){if(!Hc(Wn))return Cn();try{let e=Bm(Wn,"utf8");return qC(e)??Cn()}catch{return Cn()}}function rs(e){if(!zm())return;yn(),jm()&&Gm(Wn,{version:e.version,stats:Rn(e.stats)});let{stats:t,...n}=e;Gm($n,n)}function Qm(){if(!zm()||!Hc($n))return null;try{let e=Bm($n,"utf8"),t=JSON.parse(e),n=Nm.safeParse(t);return n.success?{...n.data,stats:jm()?JC():Cn()}:null}catch{return null}}function Um(){let e=!1;for(let t of[$n,Wn])if(Hc(t))try{YC(t),e=!0}catch{return!1}return e}var ex=6e4,Lt=null,xn=!1,br=null,Gc=!1,To=null,Eo=null,Ao=null,os=!1;function tx(){Gc||(Gc=!0,To=()=>{Lo()},Eo=()=>{Lo()},Ao=()=>{Lo()},process.on("exit",To),process.on("SIGINT",Eo),process.on("SIGTERM",Ao))}function Bc(){To&&(process.removeListener("exit",To),To=null),Eo&&(process.removeListener("SIGINT",Eo),Eo=null),Ao&&(process.removeListener("SIGTERM",Ao),Ao=null),Gc=!1}function nx(){br||(br=setInterval(()=>{xn&&Lt&&(rs(Lt),xn=!1)},ex),br.unref())}function zc(){br&&(clearInterval(br),br=null)}function _o(){if(Lt)return Lt;let e=Qm();return e&&(Lt=e),e}function Sr(e){Lt=e,xn=!0,tx(),nx()}function ko(){xn&&Lt&&(rs(Lt),xn=!1)}function Lo(){if(!os&&xn&&Lt){os=!0;try{rs(Lt),xn=!1}catch{}finally{os=!1}}}function jc(){Lt=null,xn=!1,os=!1}function $m(){jc(),zc(),Bc()}var ox=1;function ix(e){return Rn(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 Wm(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 Vm(){let e=new Date().toISOString();return{version:ox,sessionId:rx(),createdAt:e,lastActiveAt:e,stats:Cn()}}function Km(){ko()}function Xm(){Lo()}function Ym(e){if(e?.forceNew){let r=Vm();return Sr(r),ko(),r}let t=_o();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return Sr(r),ko(),r}let n=Vm();return Sr(n),ko(),n}function Zm(){return _o()?.sessionId??null}function dt(e){let t=_o();if(!t)return{success:!1,session:null};let n=ix(t.stats),r=Rn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Wm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:sx(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:ax(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Wm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Sr(o),{success:!0,session:o}}function qm(e=1){return dt({toolCalls:e})}function Jm(e=1){return dt({errors:e})}function is(e=1){return dt({rateLimits:e})}function ef(e,t=1){return dt({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 dt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function as(e,t=1){return dt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function cs(e=1){return dt({githubCacheHits:{hits:{},rateLimits:e}})}function tf(e,t=1){return dt({packageRegistryFailures:{[e]:t}})}function nf(){let e=_o();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Cn()};return Sr(t),{success:!0,session:t}}function rf(){return jc(),zc(),Bc(),Um()}function of(){$m()}import{z as Ce}from"zod";var sf=Ce.looseObject({$schema:Ce.string().optional(),version:Ce.number().int().optional(),github:Ce.record(Ce.string(),Ce.unknown()).optional(),local:Ce.record(Ce.string(),Ce.unknown()).optional(),tools:Ce.record(Ce.string(),Ce.unknown()).optional(),network:Ce.record(Ce.string(),Ce.unknown()).optional(),lsp:Ce.record(Ce.string(),Ce.unknown()).optional(),output:Ce.record(Ce.string(),Ce.unknown()).optional()});import{existsSync as cx,readdirSync as lx,lstatSync as ux}from"node:fs";import{join as px}from"node:path";function Io(e){if(!cx(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=lx(r)}catch{continue}for(let i of o){let s=px(r,i);try{let a=ux(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function dx(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}import{getConfigSync as Uf}from"@octocodeai/config";var Vn="18.3.0";import{maskSensitiveData as xw}from"@octocodeai/octocode-engine/mask";import{mkdirSync as Nf,readFileSync as pw,renameSync as Hf,rmSync as Gf,statSync as dw,writeFileSync as mw}from"node:fs";import{join as qc}from"node:path";import{isPersistentStorageEnabled as Bf}from"@octocodeai/config";import{existsSync as No,readFileSync as Tx,writeFileSync as Ex,mkdirSync as Ax,rmSync as Mo,readdirSync as Lx,statSync as _x}from"node:fs";import{join as wn}from"node:path";import{join as ls}from"node:path";import{createHash as af}from"node:crypto";function fx(e){return Oo(e)}function Oo(e){return ls(e,"tmp","clone")}function us(e){return ls(e,"tmp","tree")}function hx(e){return e?`__sp_${af("sha256").update(e).digest("hex").substring(0,6)}`:""}function gx(e){if(!/[\\/]/.test(e))return e;let t=af("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function Qc(e,t,n,r,o){let i=`${gx(r)}${hx(o)}`;return ls(Oo(e),t,n,i)}function vo(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new Error("Tree cache identity must be a 40-character commit SHA.");return ls(us(e),t,n,r.toLowerCase())}import{readFileSync as yx,readdirSync as bx,renameSync as Sx,rmSync as uf,statSync as pf,writeFileSync as Rx}from"node:fs";import{join as Rr}from"node:path";var Cx=900*1e3,cf=300*1e3,df=".octocode-lock.json";function xx(e){return typeof e=="object"&&e!==null}function lf(e){try{return bx(e)}catch{return[]}}function Uc(e,t=process.pid,n=Date.now()){try{Rx(Rr(e,df),JSON.stringify({pid:t,createdAt:n}),{encoding:"utf8",mode:384})}catch{}}function wx(e){try{let t=JSON.parse(yx(Rr(e,df),"utf8"));return!xx(t)||!Number.isInteger(t.pid)||t.pid<=0||typeof t.createdAt!="number"?null:{pid:t.pid,createdAt:t.createdAt}}catch{return null}}function Px(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function ps(e,t=Date.now()){let n,r=wx(e);if(r){if(n=r.createdAt,t-n<=cf||Px(r.pid))return!1}else{try{n=pf(e).mtimeMs}catch{return!1}if(t-n<=cf)return!1}let o=`${e}.stale-${process.pid}-${t}`;try{return Sx(e,o),uf(o,{recursive:!0,force:!0}),!0}catch{return!1}}function $c(e,t=Date.now()){let n=Rr(e,"tmp","clone-tmp"),r=0;for(let i of lf(n)){let s=Rr(n,i);try{let a=pf(s);if(t-a.mtimeMs<=Cx)continue;uf(s,{recursive:!0,force:!0}),r++}catch{}}let o=Rr(e,"tmp","clone-locks");for(let i of lf(o))ps(Rr(o,i),t)&&r++;return r}var kx=1440*60*1e3,Ix=2*1024*1024*1024,Ox=50,ff=".octocode-clone-meta.json";function vx(e){return typeof e=="object"&&e!==null}function Fx(e){if(!vx(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 Wc(e){let t=wn(e,ff);if(!No(t))return null;try{return Fx(JSON.parse(Tx(t,"utf-8")))}catch{return null}}function Cr(e,t){try{Ex(wn(e,ff),JSON.stringify(t,null,2),"utf-8")}catch{}}function hf(e){return Date.now()<new Date(e.expiresAt).getTime()}function xr(e){let t=Wc(e);return t?hf(t)?No(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Mx(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return kx}function Nx(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Ix}function Dx(){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 Ox}function wr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Mx()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function Pn(e){let t=wn(e,"..");try{No(t)||Ax(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 ds(e){try{No(e)&&Mo(e,{recursive:!0,force:!0})}catch{}}function Fo(e){try{return _x(e).isDirectory()}catch{return!1}}function Kn(e){try{return Lx(e)}catch{return[]}}function*gf(e){for(let t of Kn(e)){let n=wn(e,t);if(Fo(n))for(let r of Kn(n)){let o=wn(n,r);if(Fo(o))for(let i of Kn(o)){let s=wn(o,i);Fo(s)&&(yield s)}}}}function mf(e){for(let t of[...Kn(e)]){let n=wn(e,t);if(Fo(n)){for(let r of[...Kn(n)]){let o=wn(n,r);if(Fo(o)&&Kn(o).length===0)try{Mo(o,{recursive:!0,force:!0})}catch{}}if(Kn(n).length===0)try{Mo(n,{recursive:!0,force:!0})}catch{}}}}function Hx(e){let t=0;for(let n of gf(e))try{let r=Wc(n);(!r||!hf(r))&&(Mo(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Gx(e){let t=[];for(let n of gf(e)){let r=Wc(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??Io(n)})}return t}function Bx(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{Mo(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function yf(e){if(!No(e))return 0;let t=0;try{t+=Hx(e)}catch{return t}mf(e);let n=Bx(Gx(e),Nx(),Dx());return t+=n,n>0&&mf(e),t}function ms(e){return yf(Oo(e))}function Pr(e){return yf(us(e))}import zx from"crypto";var jx="v2",Qx=new Set([]);function Ux(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(Qx.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function xe(e,t,n){let r=Vc(Ux(t)),o=n?`${n}:${r}`:r,i=zx.createHash("sha256").update(o).digest("hex");return`${jx}-${e}:${i}`}function Vc(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=>Vc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Vc(i,t)}`}).join(",")}}`)}import $x from"node-cache";var Wx=300*1e3,je=new $x({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),me={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},bf={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-issues":1800,"gh-api-history":1800,"gh-api-releases":3600,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},it=new Map;function Vx(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Kx(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Xn(e){let t=Vx(e);if(!(!t||!Kx(t)))try{as(t,1)}catch{}}function fs(){let e=Date.now();for(let[t,n]of it.entries())e-n.startedAt>Wx&&it.delete(t)}function hs(e){return bf[e]||bf.default}function Yn(e,t,n){try{return je.set(e,t,n),me.sets++,me.totalKeys=je.keys().length,!0}catch{try{let r=je.keys();for(let o of r)je.get(o);return je.set(e,t,n),me.sets++,me.totalKeys=je.keys().length,!0}catch{return!1}}}import{createHash as Xx}from"node:crypto";import{chmod as Sf,mkdir as Cf,readFile as xf,readdir as Yx,rename as Rf,rm as Zx,stat as Kc,writeFile as wf}from"node:fs/promises";import{join as Do}from"node:path";import{isPersistentStorageEnabled as qx}from"@octocodeai/config";var Pf=1,Tf=5*1024*1024,Jx=5e3,ew=256*1024*1024,tw=1440*60*1e3,nw=900*1e3,Ef=".last-gc",_e={hits:0,misses:0,sets:0,errors:0,evictions:0};function gs(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Xc(){if(!qx())return!1;let e=process.env.OCTOCODE_DISK_CACHE?.trim().toLowerCase();return!(e==="false"||e==="0")}function Yc(e=gn()){return Do(e,"tmp","response")}function rw(e){return(e.match(/^v\d+-([^:]+):/)?.[1]??"default").replace(/[^a-zA-Z0-9._-]/g,"_")}function Af(e,t=gn()){let n=Xx("sha256").update(e).digest("hex");return Do(Yc(t),rw(e),n.slice(0,2),`${n}.json`)}function Lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ow(e,t){let n;try{n=JSON.parse(e)}catch{return null}return!Lf(n)||n.version!==Pf||n.key!==t||typeof n.createdAt!="number"||typeof n.expiresAt!="number"||typeof n.staleUntil!="number"||!("value"in n)||n.etag!==void 0&&typeof n.etag!="string"?null:n}async function en(e){try{await Zx(e,{force:!0,recursive:!0})}catch{}}async function ys(e,t={}){if(!Xc())return;let n=Af(e);try{let r=await Kc(n);if(!r.isFile()||r.size>gs("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",Tf)){await en(n),_e.errors++;return}let o=ow(await xf(n,"utf8"),e);if(!o){await en(n),_e.errors++;return}let i=Date.now();if(i>=o.staleUntil){await en(n),_e.evictions++,_e.misses++;return}if(i>=o.expiresAt&&!t.allowStale){_e.misses++;return}return _e.hits++,{value:o.value,...o.etag?{etag:o.etag}:{},state:i<o.expiresAt?"fresh":"stale",expiresAt:o.expiresAt}}catch(r){r.code!=="ENOENT"&&_e.errors++,_e.misses++;return}}async function Ho(e,t,n,r={}){if(!Xc())return!1;let o=Date.now(),i=Math.max(1,n*1e3),s=Math.max(i,(r.staleTtlSeconds??n)*1e3),a={version:Pf,key:e,createdAt:o,expiresAt:o+i,staleUntil:o+s,value:t,...r.etag?{etag:r.etag}:{}},c;try{c=JSON.stringify(a)}catch{return _e.errors++,!1}if(c===void 0||Buffer.byteLength(c)>gs("OCTOCODE_DISK_CACHE_MAX_ENTRY_SIZE",Tf))return!1;let l=Af(e),u=Do(l,".."),p=`${l}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;try{await Cf(u,{recursive:!0,mode:448}),await Sf(u,448),await wf(p,c,{encoding:"utf8",mode:384}),await Sf(p,384);try{await Rf(p,l)}catch(d){let m=d.code;if(m!=="EEXIST"&&m!=="EPERM")throw d;await en(l),await Rf(p,l)}return _e.sets++,!0}catch{return _e.errors++,await en(p),!1}}async function iw(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=await Yx(r,{withFileTypes:!0})}catch{continue}for(let i of o){let s=Do(r,i.name);i.isDirectory()?n.push(s):i.isFile()&&i.name!==Ef&&t.push(s)}}return t}async function _f(e,t,n){if(!Xc())return 0;let r=Yc(e),o=Do(r,Ef);if(n)try{let p=await Kc(o);if(t-p.mtimeMs<tw)return 0}catch{}let i=0,s=await iw(r),a=gs("OCTOCODE_DISK_CACHE_MAX_ENTRIES",Jx),c=gs("OCTOCODE_DISK_CACHE_MAX_SIZE",ew),l=[],u=0;for(let p of s)try{let d=await Kc(p);if(p.includes(".tmp-")){t-d.mtimeMs>nw&&(await en(p),i++);continue}let m=await xf(p,"utf8"),f;try{f=JSON.parse(m)}catch{f=null}if(!Lf(f)||typeof f.staleUntil!="number"||t>=f.staleUntil){await en(p),i++;continue}l.push({path:p,size:d.size,modified:d.mtimeMs}),u+=d.size}catch{}for(l.sort((p,d)=>p.modified-d.modified);l.length>a||u>c;){let p=l.shift();if(!p)break;await en(p.path),u-=p.size,i++}try{await Cf(r,{recursive:!0,mode:448}),await wf(o,String(t),{encoding:"utf8",mode:384})}catch{_e.errors++}return _e.evictions+=i,i}function PM(e=gn(),t=Date.now()){return _f(e,t,!0)}function kf(e=gn(),t=Date.now()){return _f(e,t,!1)}async function TM(e=gn()){await en(Yc(e))}function If(){return{..._e}}function Of(){_e.hits=0,_e.misses=0,_e.sets=0,_e.errors=0,_e.evictions=0}import{AsyncLocalStorage as sw}from"node:async_hooks";var bs=new sw;async function vf(e){let t={hit:!1};return{value:await bs.run({root:t,depth:0,role:"response"},e),cacheHit:t.hit}}function Ss(e,t="response"){let n=bs.getStore();return n?bs.run({root:n.root,depth:n.depth+1,role:t},e):e()}function tn(){let e=bs.getStore();e&&e.depth<=1&&e.role==="response"&&(e.root.hit=!0)}function aw(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return hs(n?.[1]??"default")}async function De(e,t,n={}){return Ss(()=>cw(e,t,n),n.cacheRole)}async function cw(e,t,n){if(n.skipCache)return await t();if(!n.forceRefresh){try{let a=je.get(e);if(a!==void 0)return me.hits++,Xn(e),tn(),a}catch{}let s=await ys(e);if(s?.state==="fresh")return me.hits++,Xn(e),tn(),Yn(e,s.value,Math.max(1,(s.expiresAt-Date.now())/1e3)),s.value}fs();let r=it.get(e);if(r)return r.promise;let o=Symbol(e),i=(async()=>{try{let s=await t();if(n.forceRefresh||me.misses++,(n.shouldCache??(()=>!0))(s)){let c=aw(e,n.ttl);Yn(e,s,c),await Ho(e,s,c)}return s}finally{it.get(e)?.requestId===o&&it.delete(e)}})();return it.set(e,{promise:i,startedAt:Date.now(),requestId:o}),i}import lw from"node-cache";var Ff=86400;function Mf(e,t){if(t)return t;let n=e.match(/^v\d+-([^:]+):/);return hs(n?.[1]??"default")}var Tr=new lw({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function Rs(e,t,n={}){return Ss(()=>uw(e,t,n),n.cacheRole)}async function uw(e,t,n){if(n.skipCache)return(await t({})).value;let r;if(!n.forceRefresh){try{let a=je.get(e);if(a!==void 0)return me.hits++,Xn(e),tn(),a}catch{}if(r=await ys(e,{allowStale:!0}),r?.state==="fresh")return me.hits++,Xn(e),tn(),Yn(e,r.value,Math.max(1,(r.expiresAt-Date.now())/1e3)),r.etag&&Tr.set(e,{data:r.value,etag:r.etag}),r.value}fs();let o=it.get(e);if(o)return o.promise;let i=Symbol(e),s=(async()=>{try{let c=(n.forceRefresh?void 0:Tr.get(e))??(r?{data:r.value,etag:r.etag}:void 0),l=await t({ifNoneMatch:!n.forceRefresh&&c?.etag?c.etag:void 0});if(l.notModified&&c){me.hits++,Xn(e),tn();let p=Mf(e,n.ttl);return Yn(e,c.data,p),await Ho(e,c.data,p,{...c.etag?{etag:c.etag}:{},staleTtlSeconds:Ff}),c.data}if(n.forceRefresh||me.misses++,(n.shouldCache??(()=>!0))(l.value)){let p=Mf(e,n.ttl);Yn(e,l.value,p),Tr.set(e,{data:l.value,etag:l.etag}),await Ho(e,l.value,p,{...l.etag?{etag:l.etag}:{},staleTtlSeconds:Ff})}return l.value}finally{it.get(e)?.requestId===i&&it.delete(e)}})();return it.set(e,{promise:s,startedAt:Date.now(),requestId:i}),s}function zM(){je.flushAll(),Tr.flushAll(),it.clear(),me.hits=0,me.misses=0,me.sets=0,me.totalKeys=0,me.lastReset=new Date,Of()}function Tn(e){let t=je.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||je.del(r)>0&&n++}return n>0&&(me.totalKeys=je.keys().length),n}function jM(){return Tn("local-")}function QM(){return Tn("lsp-")}function UM(){let e=0;return e+=Tn("gh-api-"),e+=Tn("bb-api-"),e+=Tn("gh-repo-"),e+=Tn("bb-repo-"),e+=Tn("github-user"),e+=Tn("npm-search"),Tr.flushAll(),e}function $M(){let e=me.hits+me.misses,t=If();return{...me,hitRate:e>0?me.hits/e*100:0,cacheSize:je.keys().length,diskHits:t.hits,diskMisses:t.misses,diskSets:t.sets,diskErrors:t.errors,diskEvictions:t.evictions}}var Df=1440*60*1e3,fw=60*1e3,hw=900*1e3,gw=".last-cache-maintenance",yw=".cache-maintenance.lock",Er=null,xs=null,Cs=new Map;function zf(e){return qc(e,"tmp")}function jf(e){return qc(zf(e),gw)}function bw(e){try{let t=Number(pw(jf(e),"utf8"));return Number.isFinite(t)&&t>=0?t:null}catch{return null}}function Zc(e,t=Date.now()){let n=bw(e);return n===null?0:Math.min(Df,Math.max(0,n+Df-t))}function Sw(e,t){let n=zf(e),r=qc(n,yw);try{Nf(n,{recursive:!0,mode:448})}catch{return null}let o=()=>{try{return Nf(r,{mode:448}),!0}catch{return!1}};if(o())return r;try{if(t-dw(r).mtimeMs<=hw)return null;let i=`${r}.stale-${process.pid}-${t}`;Hf(r,i),Gf(i,{recursive:!0,force:!0})}catch{return null}return o()?r:null}function Rw(e,t){let n=jf(e),r=`${n}.tmp-${process.pid}-${t}`;mw(r,String(t),{encoding:"utf8",mode:384}),Hf(r,n)}async function Cw(e,t){if(Zc(e,t)>0)return!1;let n=Sw(e,t);if(!n)return!1;try{if(Zc(e,t)>0)return!1;try{return ms(e),Pr(e),$c(e,t),await kf(e,t),Rw(e,t),!0}catch{return!1}}finally{try{Gf(n,{recursive:!0,force:!0})}catch{}}}function Ar(e,t=Date.now()){if(!Bf())return Promise.resolve(!1);let n=Cs.get(e);if(n)return n;let r=Cw(e,t).finally(()=>{Cs.get(e)===r&&Cs.delete(e)});return Cs.set(e,r),r}function Qf(e){if(xs!==e)return;let t=Math.max(fw,Zc(e));Er=setTimeout(()=>{Er=null,Ar(e).finally(()=>{Qf(e)})},t),Er.unref()}function iN(e){Bf()&&xs===null&&(xs=e,Ar(e).finally(()=>{Qf(e)}))}function sN(){xs=null,Er&&clearTimeout(Er),Er=null}var En=null,Lr=null,Jc=Sn;function fN(e){e.resolveTokenFull&&(Jc=e.resolveTokenFull)}function hN(){Jc=Sn}var ww=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function el(){try{let e=await Jc({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:ww.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function $f(){if(En!==null)return;if(Lr!==null)return Lr;let e=(async()=>{let t=Uf(),n=await el();En={version:Vn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone&&t.storage.mode==="persistent",tokenSource:n.source},await Ar(At())})();Lr=e;try{await e}catch(t){throw Lr===e&&(En=null,Lr=null),t}}function gN(){En=null,Lr=null}function Go(){if(!En){let e=xw(Tc.NOT_INITIALIZED.message);throw new Error(e)}return En}async function tl(){return(await el()).token}function yN(){return Go().enableLocal}function Wf(){let e=Go();return e.enableLocal&&e.enableClone}async function bN(){return En!==null?En.tokenSource:(await el()).source}function nl(){return"github"}function rl(){let e=Uf().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}function An(e){(e.provider?dt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):is(1)).session&&e.provider==="github"&&cs(1)}function Vf(e){dt({packageRegistryFailures:{[e]:1}})}function qf(e){return Ew("sha256").update(e).digest("hex").substring(0,16)}async function ke(e){let t=e?.token??await tl(),n=t?qf(t):"anon",r=Go().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var Aw=Pw.plugin(Tw),Lw=300*1e3,ol=50,_w=60*1e3;function Jf(e){return Date.now()-e.createdAt>Lw}var jt=new Map,Ln=null;function eh(){for(let[e,t]of jt.entries())Jf(t)&&jt.delete(e);if(jt.size>ol){let e=jt.size-ol,t=0;for(let[n]of jt){if(t>=e)break;jt.delete(n),t++}}}function kw(){Ln||(Ln=setInterval(eh,_w),typeof Ln=="object"&&"unref"in Ln&&Ln.unref())}var Kf=3,Xf=60;function Yf(e,t,n){An({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var Iw=()=>({onRateLimit:(e,t,n,r)=>(Yf("primary",e,t),r<Kf&&e<Xf),onSecondaryRateLimit:(e,t,n,r)=>(Yf("secondary",e,t),r<Kf&&e<Xf)});function Ow(e){let t=Go(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Vn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:Iw(),log:r,...e&&{auth:e}};return new Aw(o)}async function $(e){kw();let t=e?.token??await tl(),n=t?qf(t):"ANONYMOUS",r=jt.get(n);if(r&&!Jf(r))return r.client;jt.size>=ol&&eh();let o=Ow(t??void 0);return jt.set(n,{client:o,createdAt:Date.now()}),o}var vw=200,Fw=300*1e3,Zn=new Map;async function Be(e,t,n){let o=`${await ke(n)}:${e}/${t}`,i=Zn.get(o);if(i&&i.expiresAt>Date.now())return i.branch;i&&Zn.delete(o);let s=await $(n);try{let{data:c}=await s.rest.repos.get({owner:e,repo:t}),l=c.default_branch;return Zf(o,l),l}catch{}let a=["main","master"];for(let c of a)try{return await s.rest.repos.getBranch({owner:e,repo:t,branch:c}),Zf(o,c),c}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Zf(e,t){if(Zn.size>=vw){let n=Zn.keys().next().value;n!==void 0&&Zn.delete(n)}Zn.set(e,{branch:t,expiresAt:Date.now()+Fw})}function _N(){jt.clear(),Zn.clear(),Ln&&(clearInterval(Ln),Ln=null)}import{ContentSanitizer as Jw}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as Mw}from"node:module";var Nw=Mw(import.meta.url),th="@octocodeai/octocode-engine",Dw=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??Nw(th),ws,Hw=Dw,il=class extends Error{constructor(n){super(`Failed to load native dependency ${th}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function te(){if(ws)return ws;try{return ws=Hw(),ws}catch(e){throw new il(e)}}var D={applyContentViewMinification(e,t){return te().applyContentViewMinification(e,t)},applyMinification(e,t){return te().applyMinification(e,t)},minifyContent(e,t){return te().minifyContent(e,t)},minifyContentSync(e,t){return te().minifyContentSync(e,t)},minifyContentResult(e,t){return te().minifyContentResult(e,t)},minifyMarkdownCore(e){return te().minifyMarkdownCore(e)},extractSignatures(e,t){return te().extractSignatures(e,t)},extractJsSymbols(e,t){return te().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return te().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return te().extractGraphFacts(e,t)},scanGraphFacts(e){return te().scanGraphFacts(e)},getSupportedJsTsExtensions(){return te().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return te().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return te().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return te().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return te().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return te().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return te().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return te().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return te().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return te().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return te().parseRipgrepJson(e,t)},searchRipgrep(e){return te().searchRipgrep(e)},queryFileSystem(e){return te().queryFileSystem(e)},extractMatchingLines(e,t,n){return te().extractMatchingLines(e,t,n)},filterPatch(e,t){return te().filterPatch(e,t)},computeLineDiff(e,t){return te().computeLineDiff(e,t)},charToByteOffset(e,t){return te().charToByteOffset(e,t)},byteToCharOffset(e,t){return te().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return te().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return te().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return te().SIGNATURES_ONLY_HINT}};import{RequestError as rh}from"octokit";var K={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},Ie={[K.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[K.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[K.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[K.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[K.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[K.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[K.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[K.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[K.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[K.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},nh={401:K.AUTH_REQUIRED,403:K.FORBIDDEN_PERMISSIONS,404:K.NOT_FOUND,422:K.INVALID_REQUEST,502:K.SERVER_UNAVAILABLE,503:K.SERVER_UNAVAILABLE,504:K.SERVER_UNAVAILABLE},sl={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},al={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ps={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var Gw=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function Qt(e){if(!(e instanceof rh)||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 Gw.some(o=>r.includes(o))})}function J(e){return e instanceof rh?Bw(e):e instanceof Error?Kw(e):{error:typeof e=="string"?e:Ie[K.UNKNOWN].message,type:"unknown"}}function Bw(e){let{status:t,message:n,response:r}=e;if(t===403)return jw(n,r);if(t===429)return zw(n,r);let o=nh[t];return o?Vw(o,t):_r(K.UNKNOWN,{error:n||Ie[K.UNKNOWN].message,status:t})}function cl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function zw(e,t){let n=t?.headers,r=cl(n,"retry-after"),o=cl(n,"x-ratelimit-reset"),i=cl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ps.RESET_BUFFER_SECONDS,0):void 0);return An({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),_r(K.RATE_LIMIT_PRIMARY,{error:e||Ie[K.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Ie[K.RATE_LIMIT_PRIMARY].suggestion})}function jw(e,t){let n=t?.headers;if(al.SECONDARY.test(e))return Qw(n);let r=n?.["x-ratelimit-remaining"],o=Ww(t);return r!==void 0&&String(r)==="0"||o?Uw(n):$w(n)}function Qw(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ps.SECONDARY_FALLBACK_SECONDS:t;return An({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),_r(K.RATE_LIMIT_SECONDARY,{error:Ie[K.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Ie[K.RATE_LIMIT_SECONDARY].suggestion})}function Uw(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)+Ps.RESET_BUFFER_SECONDS,0):void 0,i=r?Ie[K.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Ie[K.RATE_LIMIT_PRIMARY].messageWithoutTime;return An({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),_r(K.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Ie[K.RATE_LIMIT_PRIMARY].suggestion})}function $w(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Ie[K.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Xw(String(t),String(n))),_r(K.FORBIDDEN_PERMISSIONS,{error:Ie[K.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Ww(e){return e?.data?.errors?.some(n=>n.type===al.GRAPHQL_TYPE)??!1}function Vw(e,t){let n=Ie[e];return _r(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function Kw(e){return sl.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Ie[K.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Ie[K.NETWORK_CONNECTION_FAILED].suggestion}:sl.TIMEOUT.some(t=>e.message.includes(t))?{error:Ie[K.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Ie[K.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function _r(e,t){return{type:"http",...t}}function Xw(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?Ie[K.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Ie[K.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function oh(e){return`user:${e}`}var Yw=/[@/]/,Zw=/^[A-Za-z0-9_-]+$/;function ll(e){return e.startsWith('"')||Zw.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var nn=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(oh(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=Yw.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var qw=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ul=class extends nn{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(ll))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(qw):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}},pl=class extends nn{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(ll)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars");let n=t;return typeof n.size=="string"&&this.queryParts.push(`size:${n.size}`),typeof n.created=="string"&&this.queryParts.push(`created:${n.created}`),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`),typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function dl(e){return new ul().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ml(e){return new pl().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var fl=class extends nn{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function hl(e){return new fl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function gl(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var yl=class extends nn{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function bl(e){return new yl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Sl(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as qN,DISCOVERY_IGNORED_FILE_NAMES as JN,DISCOVERY_IGNORED_FOLDER_NAMES as eD,getDiscoveryExtension as ih,shouldIgnoreDiscoveryDir as Bo,shouldIgnoreDiscoveryFile as kr}from"@octocodeai/octocode-engine/security";var sh=Symbol.for("octocode.rawResponseChars");function B(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function ah(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function W(e,t){let n=typeof t=="number"?ah(t):B(t);if(n===void 0)return e;try{Object.defineProperty(e,sh,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ie(e){if(!(typeof e!="object"||e===null))return ah(e[sh])}function Ir(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}function ch(e){let t=Ir(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function Or(e){let t=Ir(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function lh(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var uh=30;async function ph(e,t,n){let r=await ke(t),o=xe("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await De(o,async()=>await eP(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function eP(e,t){try{let n=await $(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(g=>g&&g.trim()).length===0)return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let r=dl(e);if(!r.trim())return{error:Ke.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:uh,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 tP(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,p=Math.min(u,1e3),d=Math.ceil(p/o),m=Math.min(i,Math.max(1,d)),f=m<d,h=Math.min(p,d*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:m,totalPages:d,perPage:o,totalMatches:p,reportedTotalMatches:u,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:u>p,hasMore:f,...f?{nextPage:m+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Ir(a.headers),rawResponseChars:B(a.data)}}catch(n){if(Qt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:uh,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 J(n)}}async function tP(e,t){let n=nP(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(m=>!kr(m.path)),c=0,l=0,u=await Promise.allSettled(a.map(async m=>{s.add(m.path);let f=[],h=await Promise.allSettled((m.text_matches||[]).map(async C=>{let P=C.fragment,T=Jw.sanitizeContent(P||"",m.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${m.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${m.path}: ${k}`));try{let k=await D.minifyContent(P||"",m.path);P=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let E=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:P||"",positions:lh(C.fragment||"",E,P||"")}})),y=h.filter(C=>C.status==="fulfilled").map(C=>C.value),g=h.filter(C=>C.status==="rejected").length;g>0&&(l+=g);let S=m,R=Array.from(new Set(f));return{path:m.path,matches:y,url:m.html_url,repository:{nameWithOwner:m.repository.full_name,url:m.repository.url,pushedAt:m.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...R.length>0&&{minificationType:R.join(",")}}})),p=u.filter(m=>m.status==="fulfilled").map(m=>m.value);c=u.filter(m=>m.status==="rejected").length;let d={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let m=n.full_name.split("/");return m.length===2&&m[0]&&m[1]?{owner:m[0],repo:m[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(d.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&&(d.matchLocations=Array.from(r)),d.minified=!o,d.minificationFailed=o,i.length>0&&(d.minificationTypes=Array.from(new Set(i))),d}function nP(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{readdirSync as rP,statSync as dh}from"node:fs";import{join as oP}from"node:path";var zo=50,Ts=5*1024*1024,Rl=300*1024,mh=5,iP=1e4,fh=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"]),Cl={maxDirectoryFiles:zo,maxTotalSize:Ts,maxFileSize:Rl};function xl(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function hh(e){return Object.values(e).every(t=>t===0)}function wl(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 gh(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 aP(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var sP=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function aP(e,t){try{let o=new URL(e);if(!sP.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(),iP);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 yh(e,t){let n=[],r=0;function o(i){let s;try{s=rP(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=oP(i,a);try{let l=dh(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 bh(e){try{return dh(e).size}catch{return 0}}import{writeFileSync as uP,mkdirSync as Rh,existsSync as Pl,rmSync as pP}from"node:fs";import{join as Ch,dirname as dP,resolve as xh,sep as wh}from"node:path";var cP=60;async function Sh(e,t,n,r){let s=(await(await $(r)).rest.repos.getCommit({owner:e,repo:t,ref:n})).data.sha;if(typeof s!="string"||!/^[0-9a-f]{40}$/i.test(s))throw new Error(`GitHub returned an invalid commit SHA for ref "${n}".`);return s.toLowerCase()}async function lP(e,t,n,r){try{return{commitSha:await Sh(e,t,n,r),resolvedRef:n}}catch(o){if(!(n==="main"||n==="master"))throw o;let s=await Be(e,t,r);if(s===n)throw o;return{commitSha:await Sh(e,t,s,r),resolvedRef:s}}}async function Es(e,t,n,r,o=!1){let i=await ke(r),s=xe("gh-api-ref-resolution",{owner:e,repo:t,ref:n,auth:i});return De(s,()=>lP(e,t,n,r),{ttl:cP,forceRefresh:o,cacheRole:"helper"})}async function Tl(e,t,n,r,o,i=!1){let s=At(),{commitSha:a,resolvedRef:c}=await Es(e,t,r,o,i),l=vo(s,e,t,a),u=xh(Ch(l,n));if(!u.startsWith(l+wh)&&u!==l)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let p=xr(l);if(p.hit&&p.meta.commitSha===a&&!i&&Pl(u)){let w=yh(u,l),L=xl();return{localPath:u,repoRoot:l,files:w.files,fileCount:w.fileCount,totalSize:w.totalSize,complete:!0,verified:!1,commitSha:a,directoryEntryCount:w.fileCount,eligibleFileCount:w.fileCount,savedFileCount:w.fileCount,skipped:L,limits:Cl,warnings:wl(!0,!1),cached:!0,expiresAt:p.meta.expiresAt,owner:e,repo:t,branch:c,directoryPath:n}}let d=await $(o),{data:m}=await d.rest.repos.getContent({owner:e,repo:t,path:n,ref:a});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=m,h=xl(),y=[];for(let w of f){if(w.type!=="file"){h.nonFile+=1;continue}if(!w.download_url){h.missingDownloadUrl+=1;continue}if(w.size>Rl){h.oversized+=1;continue}let L=ih(w.name,{lowercase:!0,leadingDot:!0});if(fh.has(L)){h.binary+=1;continue}y.push(w)}h.fileLimit=Math.max(0,y.length-zo);let g=y.slice(0,zo),S=o?.token,R=await gh(g,mh,S);h.fetchFailed=g.length-R.length;let C=0,P=[];for(let w=0;w<R.length;w+=1){let{entry:L,content:O}=R[w];if(C+O.length>Ts){h.totalSizeLimit=R.length-w;break}C+=O.length,P.push({entry:L,content:O})}Pr(s),Pn(l),Pl(u)&&pP(u,{recursive:!0,force:!0}),Rh(u,{recursive:!0,mode:448});let T=[];for(let{entry:w,content:L}of P){let O=xh(Ch(l,w.path));if(!O.startsWith(l+wh)){h.pathTraversal+=1;continue}let v=dP(O);Pl(v)||Rh(v,{recursive:!0,mode:448}),uP(O,L,"utf-8"),T.push({path:w.path,size:L.length,type:"file"})}let E=wr(e,t,c,"treeFetch",void 0,void 0,a);Cr(l,E);let k=hh(h),x=k,b=h.nonFile>0;return{localPath:u,repoRoot:l,files:T,fileCount:T.length,totalSize:C,complete:k,verified:x,commitSha:a,...b?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:y.length,savedFileCount:T.length,skipped:h,limits:Cl,warnings:wl(k,x),cached:!1,expiresAt:E.expiresAt,owner:e,repo:t,branch:c,directoryPath:n}}import{writeFileSync as WP,mkdirSync as VP,existsSync as Fh}from"node:fs";import{join as KP,dirname as XP,resolve as YP,sep as ZP}from"node:path";import{RequestError as Kl}from"octokit";import{z as El}from"zod";var mt={GITHUB_SEARCH:"ghSearch",GITHUB_FETCH_CONTENT:"ghGetFileContent",GITHUB_SEARCH_HISTORY:"ghSearchHistory",GITHUB_GET_HISTORY_ITEM:"ghGetHistoryItem",PACKAGE_SEARCH:"npmSearch",GITHUB_CLONE_REPO:"ghCloneRepo",LOCAL_SEARCH:"localSearch",LOCAL_ANALYZE_GRAPH:"localAnalyzeGraph",LOCAL_FETCH_CONTENT:"localGetFileContent",LSP_GET_SEMANTIC_CONTENT:"lspGetSemantics"},As=El.object({goal:El.string().optional().describe("What this query should accomplish."),reasoning:El.string().optional().describe("Why this query advances the goal.")}),qn=Object.fromEntries(Object.entries(As.shape).map(([e,t])=>[e,t.description??""]));var mP={ghSearch:["Use only fields listed for the selected operation.","match: code=file|path; repositories=name|description|readme.","code cannot select branch; it searches GitHub's indexed default branch."],localSearch:["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."],localAnalyzeGraph:["dependencies | dependents -> requires file; depth applies.","path -> requires file + target.","deadCode/reachability use entrypoints and includeTests as roots."],localGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString."],lspGetSemantics:["workspaceSymbol needs symbolName and may use workspaceRoot.","documentSymbols/diagnostic need uri.","definition | references | hover | callers | callees | callHierarchy | implementation | typeDefinition | supertypes | subtypes -> requires uri + symbolName + lineHint."],ghGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString.",'type:"directory" materializes; extraction fields read files.'],npmSearch:["Set exactly one of packageName or keywords."]};function Ls(e){return[...mP[e]??[]]}var fP={ghSearch:[{name:"code",when:"Search code contents or file paths",requires:["operation"],excludes:["branch"],fields:["keywords","owner","repo","extension","filename","path","language","match","pageSize","page","concise"],example:{operation:"code",keywords:["toolSchemas"],owner:"bgauryy",repo:"octocode"}},{name:"repositories",when:"Discover repositories",requires:["operation"],fields:["keywords","topics","language","owner","stars","forks","goodFirstIssues","updated","created","size","match","sort","pageSize","page","archived","visibility","license","concise"],example:{operation:"repositories",keywords:["octocode"]}},{name:"tree",when:"Browse a known repository tree",requires:["operation","owner","repo"],fields:["owner","repo","branch","path","maxDepth","page","pageSize","include"],example:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}],localSearch:[{name:"text",when:"Search lexical text or regular expressions",requires:["operation","path","searchText"],example:{operation:"text",path:".",searchText:"toolSchemas"}},{name:"structural",when:"Match AST structure",requires:["operation","path","pattern"],example:{operation:"structural",path:".",pattern:"console.log($A)",langType:"typescript"}},{name:"files",when:"Discover paths by name or metadata",requires:["operation","path"],example:{operation:"files",path:".",names:["*.ts"]}},{name:"tree",when:"Browse a directory tree",requires:["operation","path"],example:{operation:"tree",path:".",maxDepth:5}}],localAnalyzeGraph:[{name:"dependencies",when:"Find files imported by a file",requires:["path","operation","file"],example:{path:".",operation:"dependencies",file:"src/index.ts"}},{name:"dependents",when:"Find files importing a file",requires:["path","operation","file"],example:{path:".",operation:"dependents",file:"src/index.ts"}},{name:"path",when:"Find a shortest dependency path",requires:["path","operation","file","target"],example:{path:".",operation:"path",file:"src/a.ts",target:"src/b.ts"}},{name:"cycles",when:"Find dependency cycles",requires:["path","operation"],example:{path:".",operation:"cycles"}},{name:"deadCode",when:"Find unreachable file candidates",requires:["path","operation"],example:{path:".",operation:"deadCode"}},{name:"reachability",when:"Find files unreachable from selected roots",requires:["path","operation","entrypoints"],example:{path:".",operation:"reachability",entrypoints:["src/index.ts"]}}],lspGetSemantics:[{name:"anchored",when:"Query a named symbol near a source line",requires:["uri","type","symbolName","lineHint"],example:{uri:"src/index.ts",type:"definition",symbolName:"main",lineHint:1}},{name:"document",when:"Query a whole document",requires:["uri","type"],example:{uri:"src/index.ts",type:"documentSymbols"}},{name:"workspace",when:"Search symbols across the workspace",requires:["workspaceRoot","type","symbolName"],example:{workspaceRoot:".",type:"workspaceSymbol",symbolName:"Schema"}}]};function Al(e){return fP[e]??[]}import{z as _s}from"zod";var vr=100,jo=1e3,Ph=1e8,Th=5e4,Ze=1e9,Ll=1e5,Qo=20,ks=100,Uo=1e4,Jn=50,_t=100,kt=30,_l=200,kl=100;var Il=1e5,Ol=500,Is=1e5,vl=1e3,Fl=20,Ml=100,Nl=20;function fe(e){return{...e,description:e.instructions}}function H(e,t){return _s.number().int().min(e).max(t)}var Ae=_s.array(_s.string()).optional();function Le(){return H(1,jo).default(1)}function Qe(){return H(1,jo).optional()}function Os(){return H(0,vr).optional()}function Fr(){return H(1,Ze).optional()}function qe(){return H(0,Ph).optional()}function yt(){return H(1,Th).optional()}var ee=As.shape,hP=new Set(Object.keys(ee)),gP={owner:"Repository owner (user or org).",repo:"Repository name, without the owner.",branch:"Branch, tag, or commit SHA; omit for the default branch.",path:"Target path. GitHub tools: repo-relative, exact case, no leading slash. Local tools: absolute path.",page:"Result page, 1-based. Advance only while pagination.hasMore.",itemsPerPage:"Items per result page.",limit:"Total result cap applied before pagination.",pageSize:"Results returned in one page.",contextLines:"Extra source lines around each match/anchor.",charLength:"Content-window length; continue with the returned offset when partial.",charOffset:"Content-window start; copy the returned offset. A partial window cannot prove absence."};function U(e,t,n=""){let r={};for(let o of Object.keys(t)){let i=t[o],s=n?`${n}.${o}`:o,c=n===""&&hP.has(o)?qn[s]:e[s]??(i.description?void 0:gP[o]);r[o]=c?i.describe(c):i}return _s.object(r).strict()}function vs(e,t){let n=e.fullContent===!0,r=e.matchString!==void 0,o=e.startLine!==void 0||e.endLine!==void 0;n&&r&&t.addIssue({code:"custom",message:"Choose fullContent or matchString.",path:["matchString"]}),n&&o&&t.addIssue({code:"custom",message:"Choose fullContent or startLine/endLine.",path:["startLine"]}),r&&o&&t.addIssue({code:"custom",message:"Choose matchString or startLine/endLine.",path:["startLine"]}),e.startLine===void 0!=(e.endLine===void 0)&&t.addIssue({code:"custom",message:"Set startLine and endLine together.",path:[e.startLine===void 0?"startLine":"endLine"]}),e.startLine!==void 0&&e.endLine!==void 0&&e.endLine<e.startLine&&t.addIssue({code:"custom",message:"Set endLine greater than or equal to startLine.",path:["endLine"]})}import{z as Fs}from"zod";import{z as _n}from"zod";var yP={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",path:"Repo path prefix, not a full file path.",match:'For ghSearch operation:"code": "file" returns snippets and character matchIndices; "path" returns paths only. Operation:"repositories" uses text-field names.',extension:'File extension filter, e.g. "ts" (no dot).',filename:"Exact filename filter.",language:'GitHub language filter, e.g. "typescript".',concise:'Flat "owner/repo:path" rows.',limit:"Results per page (paginate with page)."},kn=U(yP,{...ee,keywords:Ae,owner:_n.string().optional(),repo:_n.string().optional(),extension:_n.string().optional(),filename:_n.string().optional(),path:_n.string().optional(),language:_n.string().optional(),match:_n.enum(["file","path"]).default("file"),limit:H(1,_t).default(kt),page:Le(),concise:_n.boolean().optional()});import{z as Je}from"zod";var bP={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",topicsToSearch:"ANDed topic filters; metadata can be sparse.",match:'For ghSearch operation:"repositories": text fields to search are name, description, and readme; readme is broader and slower. Operation:"code" uses "file" or "path".',sort:"stars, forks, updated, help-wanted-issues, best-match.",language:'Primary language filter, e.g. "rust".',stars:'Star range: ">100", "10..50".',forks:'Fork range: ">50", "10..100".',goodFirstIssues:'Good-first-issue count range, e.g. ">5".',updated:'Last push date: ">2024-01-01" or "a..b".',created:'Creation date: ">2023-01-01" or "a..b".',size:'Repo size in KB: ">1000", "50..500".',license:'SPDX id, e.g. "mit".',archived:"true = archived only; default excludes archived.",visibility:'"public" or "private" (private needs token scope).',concise:'Flat "owner/repo" rows for triage.',limit:"Results per page (paginate with page)."},rn=U(bP,{...ee,keywords:Ae,topicsToSearch:Ae,language:Je.string().optional(),owner:Je.string().optional(),stars:Je.string().optional(),forks:Je.string().optional(),goodFirstIssues:Je.string().optional(),updated:Je.string().optional(),created:Je.string().optional(),size:Je.string().optional(),match:Je.array(Je.enum(["name","description","readme"])).optional(),sort:Je.enum(["stars","forks","help-wanted-issues","updated","best-match"]).default("best-match"),limit:H(1,_t).default(kt),page:Le(),archived:Je.boolean().optional(),visibility:Je.enum(["public","private"]).optional(),license:Je.string().optional(),concise:Je.boolean().optional()});import{z as Mr}from"zod";var SP={path:'Repo-relative directory; ""/"." for root.',branch:"Ref; fallback warning means default branch was used.",maxDepth:"Tree recursion depth.",page:"Advance only on hasMore.",include:"Optional sizes, languages, contributors, branches, or tags; each adds an API call."},er=U(SP,{...ee,owner:Mr.string(),repo:Mr.string(),branch:Mr.string().optional(),path:Mr.string().optional(),maxDepth:H(0,Nl).optional(),page:Le(),itemsPerPage:H(1,_l).default(kl),include:Mr.array(Mr.enum(["sizes","languages","contributors","branches","tags"])).optional()});var JD=fe({name:"ghSearch",type:"Github",shortDescription:"Search GitHub code or repositories, or browse a repository tree.",instructions:`Choose operation:"code" for code contents or file paths, "repositories" to discover repositories, or "tree" to browse a known repository.
11
11
  Each operation has a strict input branch; fields from other operations are rejected. Use ghGetFileContent only after a path is known. Empty GitHub search results do not prove absence.`,schema:{operation:'Required: "code", "repositories", or "tree".'}}),RP=kn.omit({limit:!0}).extend({match:kn.shape.match.describe('For operation:"code": "file" returns snippets; "path" returns paths only.'),pageSize:kn.shape.limit.describe("Results returned per page."),operation:Fs.literal("code").describe("Search code contents or file paths.")}).strict(),CP=rn.omit({topicsToSearch:!0,limit:!0}).extend({topics:rn.shape.topicsToSearch.describe("Repository topics; all must match."),pageSize:rn.shape.limit.describe("Results returned per page."),match:rn.shape.match.describe('For operation:"repositories": fields to search: name, description, or readme.'),operation:Fs.literal("repositories").describe("Discover repositories by keywords and repository filters.")}).strict(),xP=er.omit({itemsPerPage:!0}).extend({operation:Fs.literal("tree").describe("Browse the tree of a known repository."),pageSize:er.shape.itemsPerPage.describe("Tree entries returned per page.")}).strict(),Dl=Fs.discriminatedUnion("operation",[RP,CP,xP]);import{z as It}from"zod";var wP=fe({name:"ghGetFileContent",type:"Github",shortDescription:"Read a file or a specific region from a GitHub repository.",instructions:`Read a known GitHub path after search or structure discovery; a complete search snippet needs no reread. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
12
12
  Choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; continue with the returned charOffset. matchedLines are LSP anchors; match ranges and offsets are not. type:"directory" returns localPath when local access is enabled; otherwise use ghSearch operation:"tree".`,schema:{startLine:"Requires endLine; exclusive with fullContent/matchString.",endLine:"Requires startLine; must be >= startLine.",fullContent:"Whole small file; exclusive with range/match.",matchString:"Anchor returning padded matchRanges and exact matchedLines.",matchStringIsRegex:"Makes matchString a regex.",matchStringCaseSensitive:"Case-sensitive matchString.",type:'"file" reads; "directory" materializes localPath when clone/local access is enabled\u2014otherwise use ghSearch operation:"tree".',forceRefresh:"Bypass the 24h fetch cache and re-read from GitHub.",charOffset:"Copy pagination.nextCharOffset.",minify:'"symbols" outline, "standard" compact, "none" exact.'}}),Ms=U(wP.schema,{...ee,owner:It.string(),repo:It.string(),branch:It.string().optional(),path:It.string(),startLine:Fr(),endLine:Fr(),fullContent:It.boolean().optional(),matchString:It.string().optional(),matchStringIsRegex:It.boolean().optional(),matchStringCaseSensitive:It.boolean().optional(),forceRefresh:It.boolean().optional(),type:It.enum(["file","directory"]).default("file"),contextLines:H(0,vr).default(5),charOffset:qe(),charLength:yt(),minify:It.enum(["none","standard","symbols"]).default("standard")}).superRefine(vs);import{z as F}from"zod";var PP=fe({name:"githubHistory",type:"Github",shortDescription:"Search and read GitHub pull requests and commit history.",instructions:`Use for PR/commit archaeology \u2014 not current code (ghSearch operation:"code"/ghGetFileContent). type:"prs" lists/reads PRs; type:"commits" walks history.
13
13
  Param relations: list mode uses filters+sort/page; detail mode needs owner+repo+prNumber and content selectors. patches.mode:"selected" requires files or ranges. Body/patch/comment windows continue via returned charOffset/commentBodyOffset; file/comment/commit lists use their page fields. For code identity, clone and use local/LSP.`,schema:{type:'"prs" for pull requests; "commits" for commit history.',keywords:"PR search terms; ignored in commits mode.",match:'PR text fields searched by keywords; ghSearch operation:"code" instead uses match to select file content or paths.',prNumber:"Switches to PR detail mode; needs owner+repo.",issueNumber:"Switches to issue detail mode; needs owner+repo.",concise:"PR list triage; ignored with prNumber.",path:"Commit-mode file/dir prefix; trailing / scopes subtree.",includeDiff:"Commit-mode diffs; costly.",order:"asc+created helps archaeology.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',interactions:'Combined comment+reaction count range (">20").',project:'Project board: "owner/number".',"team-mentions":'Team mention: "org/team-slug".',filePage:"Changed-files page from contentPagination.",commentPage:"Comments page from contentPagination.",commitPage:"PR commits page from contentPagination.",reviewMode:'"full" fetches all PR detail surfaces.',content:"Detail selector for prNumber.","content.body":"Full PR description; windowed by charOffset.","content.changedFiles":"File list with status and +/- counts.","content.patches.mode":'"none", "selected" (cheapest; needs files or ranges), or "all".',"content.patches.ranges":"Line ranges for selected patch hunks.","content.comments.reviewInline":"Inline review comments; in_reply_to_id marks threads.","content.comments.includeBots":"Include bot/CI comments.","content.reviews":"Review verdicts per reviewer.","content.commits":"PR-bound commits selector.",matchString:"Substring filter for body/patch/comment windows.",charOffset:"Body/patch continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" compact patches; "none" exact diff; "symbols" not available.'}}),Nr=PP.schema,Ns=U(Nr,{...ee,type:F.enum(["prs","commits"]).default("prs"),since:F.string().optional(),until:F.string().optional(),path:F.string().optional(),branch:F.string().optional(),includeDiff:F.boolean().optional().default(!1),includeAssets:F.boolean().optional(),keywords:F.array(F.string()).optional(),prNumber:H(1,Ze).optional(),issueNumber:H(1,Ze).optional(),owner:F.string().optional(),repo:F.string().optional(),concise:F.boolean().optional(),state:F.enum(["open","closed","merged"]).optional(),assignee:F.string().optional(),author:F.string().optional(),committer:F.string().optional(),commenter:F.string().optional(),mentions:F.string().optional(),"review-requested":F.string().optional(),"reviewed-by":F.string().optional(),label:F.union([F.string(),F.array(F.string())]).optional(),checks:F.enum(["success","failure","pending"]).optional(),review:F.enum(["approved","changes_requested","required","none"]).optional(),head:F.string().optional(),base:F.string().optional(),created:F.string().optional(),updated:F.string().optional(),closed:F.string().optional(),"merged-at":F.string().optional(),comments:F.string().optional(),reactions:F.string().optional(),draft:F.boolean().optional(),match:F.array(F.enum(["title","body","comments"])).optional(),sort:F.enum(["created","updated","best-match","comments","reactions"]).optional(),order:F.enum(["asc","desc"]).optional(),limit:H(1,_t).default(kt),page:Le(),archived:F.boolean().optional(),filePage:Qe(),commentPage:Qe(),commitPage:Qe(),reviewMode:F.literal("full").optional(),content:U(Nr,{metadata:F.boolean().optional(),body:F.boolean().optional(),changedFiles:F.boolean().optional(),patches:U(Nr,{mode:F.enum(["none","selected","all"]).default("none"),files:Ae,ranges:F.array(U(Nr,{file:F.string(),additions:F.array(H(1,Ze)).optional(),deletions:F.array(H(1,Ze)).optional()},"content.patches.ranges")).optional()},"content.patches").optional(),comments:U(Nr,{discussion:F.boolean().optional(),reviewInline:F.boolean().optional(),includeBots:F.boolean().default(!1),file:F.string().optional()},"content.comments").optional(),reviews:F.boolean().optional(),commits:U(Nr,{list:F.boolean().optional(),includeFiles:F.boolean().optional()},"content.commits").optional()},"content").optional(),matchString:F.string().optional(),commentBodyOffset:qe(),charOffset:qe(),charLength:yt(),minify:F.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let n=e.content?.patches;if(!n)return;let r=(n.files?.length??0)>0,o=(n.ranges?.length??0)>0,i=r||o;n.mode==="selected"&&!i&&t.addIssue({code:"custom",message:'content.patches.mode="selected" requires non-empty files or ranges.',path:["content","patches","files"]}),n.mode!=="selected"&&i&&t.addIssue({code:"custom",message:'content.patches.files and content.patches.ranges require mode="selected".',path:["content","patches","mode"]})});import{z as Q}from"zod";var TP=fe({name:"ghSearchHistory",type:"Github",shortDescription:"Search GitHub pull requests, or read one PR's files, diffs, and reviews.",instructions:`Use for PR history, diffs, and review context; use code tools for current bytes, commits for history, and issues for issue threads. Conversation is context: prove landed behavior from selected patches or the merge SHA.
@@ -54,8 +54,8 @@ export declare const FindFilesQuerySchema: z.ZodObject<{
54
54
  basic: "basic";
55
55
  }>>;
56
56
  sortBy: z.ZodDefault<z.ZodEnum<{
57
- name: "name";
58
57
  path: "path";
58
+ name: "name";
59
59
  size: "size";
60
60
  modified: "modified";
61
61
  }>>;
@@ -220,8 +220,8 @@ export declare const LocalSearchQuerySchema: z.ZodUnion<readonly [z.ZodObject<{
220
220
  pathRegex: z.ZodOptional<z.ZodString>;
221
221
  limit: z.ZodOptional<z.ZodNumber>;
222
222
  sort: z.ZodDefault<z.ZodEnum<{
223
- name: "name";
224
223
  path: "path";
224
+ name: "name";
225
225
  size: "size";
226
226
  modified: "modified";
227
227
  }>>;
@@ -216,8 +216,8 @@ export declare const LocalSearchQuerySchema: z.ZodUnion<readonly [z.ZodObject<{
216
216
  pathRegex: z.ZodOptional<z.ZodString>;
217
217
  limit: z.ZodOptional<z.ZodNumber>;
218
218
  sort: z.ZodDefault<z.ZodEnum<{
219
- name: "name";
220
219
  path: "path";
220
+ name: "name";
221
221
  size: "size";
222
222
  modified: "modified";
223
223
  }>>;
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@octocodeai/octocode-tools-core",
3
3
  "description": "Core tool implementations for Octocode: GitHub, local filesystem, LSP, and package search tools.",
4
- "version": "18.2.0",
4
+ "version": "18.3.0",
5
5
  "author": "Guy Bary <bgauryy@octocodeai.com>",
6
6
  "bugs": "https://github.com/bgauryy/octocode/issues",
7
7
  "dependencies": {
8
8
  "@modelcontextprotocol/server": "^2.0.0",
9
- "@octocodeai/config": "18.0.1",
9
+ "@octocodeai/config": "18.3.0",
10
10
  "@octocodeai/octocode-core": "18.3.0",
11
- "@octocodeai/octocode-engine": "18.2.0",
11
+ "@octocodeai/octocode-engine": "18.3.0",
12
12
  "@octokit/oauth-methods": "^6.0.2",
13
13
  "@octokit/plugin-throttling": "^11.0.3",
14
14
  "@octokit/request": "^10.0.10",
@@ -20,12 +20,12 @@
20
20
  "@octokit/core": "^7.0.6",
21
21
  "@octokit/openapi-types": "^27.0.0",
22
22
  "@octokit/plugin-rest-endpoint-methods": "^17.0.0",
23
- "@types/node": "^25.9.3",
24
- "@vitest/coverage-v8": "^4.1.9",
23
+ "@types/node": "^26.2.0",
24
+ "@vitest/coverage-v8": "^4.1.11",
25
25
  "esbuild": "^0.28.1",
26
26
  "eslint": "^9.18.0",
27
27
  "typescript": "^5.9.3",
28
- "vitest": "^4.1.9"
28
+ "vitest": "^4.1.11"
29
29
  },
30
30
  "engines": {
31
31
  "node": ">=20.0.0"
@@ -92,8 +92,8 @@
92
92
  "directory": "packages/octocode-tools-core"
93
93
  },
94
94
  "scripts": {
95
- "build": "yarn readme:sync && yarn clean && node build.mjs && yarn build:types-deps && tsc --emitDeclarationOnly -p tsconfig.build.json",
96
- "build:dev": "yarn readme:sync && node build.mjs && yarn build:types-deps && tsc --emitDeclarationOnly -p tsconfig.build.json",
95
+ "build": "yarn readme:sync && yarn clean && node ../../scripts/esbuild-package.mjs && yarn build:types-deps && tsc --emitDeclarationOnly -p tsconfig.build.json",
96
+ "build:dev": "yarn readme:sync && node ../../scripts/esbuild-package.mjs && yarn build:types-deps && tsc --emitDeclarationOnly -p tsconfig.build.json",
97
97
  "build:types-deps": "yarn workspace @octocodeai/config build",
98
98
  "clean": "rm -rf dist/",
99
99
  "lint": "eslint src",