@octocodeai/octocode-tools-core 17.0.1 → 17.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/direct.js CHANGED
@@ -5,44 +5,44 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- var VE=Object.defineProperty;var f=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var KE=(e,t)=>{for(var n in t)VE(e,n,{get:t[n],enumerable:!0})};import{completeMetadata as YE}from"@octocodeai/octocode-core";function po(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var Y,Ie,rn,aH,mo=f(()=>{"use strict";Y=YE.toolNames,Ie=Y.LSP_GET_SEMANTIC_CONTENT,rn="oqlSearch";aH=new Set([Y.LOCAL_RIPGREP,Y.LOCAL_FETCH_CONTENT,Y.LOCAL_FIND_FILES,Y.LOCAL_VIEW_STRUCTURE,Ie])});function Qt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function El(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var Cf,kt=f(()=>{"use strict";mo();Cf=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});var ae=f(()=>{"use strict"});import{z as vs}from"zod";function B(e,t){return vs.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,vs.number().int().min(e).max(t))}function fe(e,t={}){let{maxQueries:n=5}=t;return vs.object({queries:vs.array(e).min(1).max(n).describe("Parallel queries."),...JE}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var Re,fr,hr,JE,Ze=f(()=>{"use strict";ae();Re=B(1,1e3).optional().default(1),fr=B(0,100).optional(),hr=B(1,1e9).optional(),JE={responseCharOffset:B(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:B(1,5e4).optional().describe("Full-response char window.")}});import{z as xf}from"zod";function ZE(e,t){return e?.description&&!t.description?t.describe(e.description):t}function wf(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=ZE(e.shape[r],o);return n}function ek(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Tf(e,t){if(!t?.length)return e;let n=new Set(t);return xf.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function he(e,t={},n={}){let r=Tf(e,n.omit),o=ek(r,wf(r,t));return n.strict?o.strict():o}function Se(e,t={},n={}){let r=Tf(e,n.omit),o=xf.object({...r.shape,...wf(r,t)});return n.strict?o.strict():o}var et=f(()=>{"use strict"});import{z}from"zod";function Ls(e,t,n="Continue to the next page of results."){return{tool:e,query:t,why:n,confidence:"exact"}}function _s(e,t,n,r){if(!n||!n.hasMore||n.nextCharOffset===void 0)return;let o=r?.includeCharLength!==!1;return{continueChars:{tool:e,query:{...t,charOffset:n.nextCharOffset,...o&&n.charLength!==void 0?{charLength:n.charLength}:{}}}}}var tt,As,Pe,on,gr,Be=f(()=>{"use strict";tt=z.object({currentPage:z.number(),totalPages:z.number(),hasMore:z.boolean(),nextPage:z.number().optional(),pageSize:z.number().optional(),totalItems:z.number().optional(),perPage:z.number().optional(),totalFound:z.number().optional(),returned:z.number().optional(),totalMatches:z.number().optional(),reportedTotalMatches:z.number().optional(),reachableTotalMatches:z.number().optional(),totalMatchesKind:z.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:z.boolean().optional(),totalResults:z.number().optional(),itemsPerPage:z.number().optional()}),As=z.object({charOffset:z.number(),charLength:z.number(),totalChars:z.number(),hasMore:z.boolean(),nextCharOffset:z.number().optional(),currentPage:z.number().optional(),totalPages:z.number().optional(),chunkMode:z.enum(["semantic","char-limit"]).optional()}),Pe=z.object({tool:z.string(),query:z.record(z.string(),z.unknown()),why:z.string().optional(),confidence:z.enum(["exact","heuristic"]).optional()}),on=tt.extend({filesPerPage:z.number().optional(),entriesPerPage:z.number().optional(),matchesPerPage:z.number().optional(),totalFiles:z.number().optional(),totalEntries:z.number().optional(),totalMatches:z.number().optional(),totalFilesFound:z.number().optional(),nextMatchPage:z.number().optional()});gr=z.object({level:z.enum(["info","warning","error"]),message:z.string(),field:z.string().optional(),code:z.string().optional()})});import{z as ge}from"zod";function nk(e){return ge.object({id:ge.string(),status:ge.enum(["empty","error"]).optional(),data:e,diagnostics:ge.array(gr).optional(),next:ge.record(ge.string(),Pe).optional()})}var tk,Ue,PH,sn,it=f(()=>{"use strict";Be();tk=ge.object({currentPage:ge.number(),totalPages:ge.number(),hasMore:ge.boolean(),charOffset:ge.number(),charLength:ge.number(),totalChars:ge.number(),nextCharOffset:ge.number().optional()}).optional(),Ue={base:ge.string().optional(),shared:ge.record(ge.string(),ge.union([ge.string(),ge.number(),ge.boolean()])).optional(),responsePagination:tk};PH=nk(ge.record(ge.string(),ge.unknown()).optional()),sn=Ue});import{CloneRepoQuerySchema as rk}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as ok}from"@octocodeai/octocode-core/schemas/outputs";var yr,fo,OH,Ef=f(()=>{"use strict";Ze();et();it();yr=he(rk),fo=fe(yr),OH=ok.extend(Ue)});import{z as O}from"zod";import{FileContentQuerySchema as kf}from"@octocodeai/octocode-core/schemas";var ik,sk,ak,ck,lk,Of,uk,Fn,go,NH,Ol=f(()=>{"use strict";ae();Ze();et();it();Be();ik=O.enum(["none","standard","symbols"]).optional().default("standard"),sk=O.union([As.extend({nextPage:O.number().optional()}),tt.extend({charOffset:O.number().optional(),charLength:O.number().optional(),totalChars:O.number().optional(),nextCharOffset:O.number().optional()})]),ak=O.object({continueChars:Pe.extend({tool:O.literal("ghGetFileContent")}).optional()}),ck=O.object({path:O.string(),content:O.string(),localPath:O.string().optional(),repoRoot:O.string().optional(),contentView:O.enum(["none","standard","symbols"]).optional(),totalLines:O.number().optional(),sourceChars:O.number().optional(),sourceBytes:O.number().optional(),resolvedBranch:O.string().optional(),modified:O.string().optional(),fileSize:O.number().optional(),pagination:sk.optional(),next:ak.optional(),isPartial:O.boolean().optional(),startLine:O.number().optional(),endLine:O.number().optional(),matchRanges:O.array(O.object({start:O.number(),end:O.number()})).optional(),lastModified:O.string().optional(),lastModifiedBy:O.string().optional(),warnings:O.array(O.string()).optional(),matchNotFound:O.boolean().optional(),searchedFor:O.string().optional(),cached:O.boolean().optional()}),lk=O.object({path:O.string(),localPath:O.string(),repoRoot:O.string().optional(),fileCount:O.number(),totalSize:O.number(),complete:O.boolean().optional(),directoryEntryCount:O.number().optional(),eligibleFileCount:O.number().optional(),savedFileCount:O.number().optional(),skipped:O.object({nonFile:O.number(),missingDownloadUrl:O.number(),oversized:O.number(),binary:O.number(),fileLimit:O.number(),fetchFailed:O.number(),totalSizeLimit:O.number(),pathTraversal:O.number()}).optional(),limits:O.object({maxDirectoryFiles:O.number(),maxTotalSize:O.number(),maxFileSize:O.number()}).optional(),warnings:O.array(O.string()).optional(),files:O.array(O.object({path:O.string(),size:O.number(),type:O.string()})).optional(),cached:O.boolean().optional(),resolvedBranch:O.string().optional()}),Of={startLine:hr,endLine:hr,contextLines:fr,charOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional(),minify:ik},uk=Se(kf,Of),Fn=he(kf,Of),go=fe(uk),NH=O.object({base:O.string().optional(),shared:O.record(O.string(),O.union([O.string(),O.number(),O.boolean()])).optional(),responsePagination:Ue.responsePagination,results:O.array(O.object({id:O.string(),data:O.object({owner:O.string(),repo:O.string(),files:O.array(ck).optional(),directories:O.array(lk).optional()}).optional()})),errors:O.array(O.object({id:O.string(),owner:O.string().optional(),repo:O.string().optional(),path:O.string().optional(),error:O.string()})).optional()})});import{z as Q}from"zod";import{GitHubCodeSearchQuerySchema as vf}from"@octocodeai/octocode-core/schemas";var Af,yo,bo,dk,qH,Lf=f(()=>{"use strict";ae();Ze();et();it();Be();Af={limit:B(1,100).optional(),page:Re.default(1),match:Q.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghHistoryResearch, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},yo=he(vf,Af),bo=fe(Se(vf,Af)),dk=tt.extend({totalMatchesKind:Q.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:Q.boolean().optional(),uniqueFileCount:Q.number().optional()}),qH=Q.object({base:Q.string().optional(),shared:Q.record(Q.string(),Q.union([Q.string(),Q.number(),Q.boolean()])).optional(),responsePagination:Ue.responsePagination,results:Q.array(Q.object({id:Q.string(),data:Q.object({files:Q.array(Q.union([Q.string(),Q.object({owner:Q.string(),repo:Q.string(),path:Q.string(),queryId:Q.string().optional(),matches:Q.array(Q.object({value:Q.string().optional(),pathOnly:Q.boolean().optional(),matchIndices:Q.array(Q.object({start:Q.number(),end:Q.number(),lineOffset:Q.number()})).optional(),url:Q.string().optional()}))})])),pagination:dk.optional()})})),emptyQueries:Q.array(Q.object({id:Q.string(),nonExistentScope:Q.literal(!0).optional(),incompleteResults:Q.literal(!0).optional()})).optional(),warnings:Q.array(Q.string()).optional(),diagnostics:Q.array(gr).optional(),next:Q.record(Q.string(),Pe).optional(),errors:Q.array(Q.object({id:Q.string(),error:Q.string()})).optional()})});import{z as $e}from"zod";import{GitHubPullRequestSearchQuerySchema as Ff}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as mk}from"@octocodeai/octocode-core/schemas/outputs";var If,fk,In,Ro,_f,nQ,vl=f(()=>{"use strict";ae();Ze();et();it();Be();If={type:$e.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),perPage:B(1,100).optional().default(30),prNumber:B(1,1e9).optional(),issueNumber:B(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:B(1,100).optional().default(30),match:$e.array($e.enum(["title","body","comments"])).optional().describe('Fields to match keywords against: "title", "body", "comments". Default searches all three. Use ["title"] for the most precise and fastest match. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)'),page:Re.default(1),filePage:Re.optional(),commentPage:Re.optional(),commitPage:Re.optional(),itemsPerPage:B(1,100).optional().default(20),charOffset:B(0,1e8).optional(),commentBodyOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional()},fk=Se(Ff,If),In=he(Ff,If),Ro=fe(fk),_f=$e.union([$e.string(),$e.object({}).passthrough()]),nQ=mk.extend({results:$e.array($e.object({id:$e.string().optional(),status:$e.string().optional(),data:$e.object({pull_requests:$e.array(_f).optional(),issues:$e.array(_f).optional(),next:$e.record($e.string(),Pe).optional()}).passthrough().optional()}).passthrough()).optional(),...Ue})});import{z as re}from"zod";import{GitHubReposSearchSingleQuerySchema as Mf}from"@octocodeai/octocode-core/schemas";var Df,So,Po,hk,gk,yk,dQ,Nf=f(()=>{"use strict";ae();Ze();et();it();Be();Df={limit:B(1,100).optional(),page:Re.default(1),match:re.array(re.enum(["name","description","readme"])).optional().describe("Which text fields to search: name, description, and/or readme. Defaults to name+description; add 'readme' for broader, slower full-text search. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)")},So=he(Mf,Df),Po=fe(Se(Mf,Df)),hk=re.object({owner:re.string(),repo:re.string(),stars:re.number().optional(),forks:re.number().optional(),openIssuesCount:re.number().optional(),language:re.string().optional(),license:re.string().optional(),description:re.string().optional(),homepage:re.string().optional(),pushedAt:re.string().optional(),createdAt:re.string().optional(),defaultBranch:re.string().optional(),topics:re.array(re.string()).optional(),visibility:re.string().optional(),url:re.string().optional(),updatedAt:re.string().optional()}),gk=tt.extend({totalMatchesKind:re.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:re.boolean().optional()}).optional(),yk=re.object({repositories:re.array(re.union([re.string(),hk])).optional(),pagination:gk}).passthrough(),dQ=re.object({results:re.array(re.object({id:re.string().optional(),status:re.string().optional(),data:yk.optional()}).passthrough()).optional()}).extend(Ue)});import{GitHubViewRepoStructureQuerySchema as Gf}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as Rk}from"@octocodeai/octocode-core/schemas/outputs";var Hf,xo,wo,SQ,Qf=f(()=>{"use strict";ae();ae();Ze();et();it();Hf={maxDepth:B(0,20).optional(),page:Re.default(1),itemsPerPage:B(1,200).optional()},xo=he(Gf,Hf),wo=fe(Se(Gf,Hf)),SQ=Rk.extend(Ue)});import{z as Z}from"zod";import{NpmPackageQuerySchema as jf}from"@octocodeai/octocode-core/schemas";var Bf,To,Eo,OQ,zf=f(()=>{"use strict";Ze();et();it();Be();Bf={page:Re,mode:Z.enum(["lean","full"]).optional(),keywords:Z.union([Z.string(),Z.array(Z.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},To=he(jf,Bf),Eo=fe(Se(jf,Bf,{strict:!0}),{maxQueries:5}),OQ=Z.object({results:Z.array(Z.looseObject({id:Z.string(),data:Z.looseObject({packages:Z.array(Z.object({name:Z.string(),version:Z.string().optional(),description:Z.string().optional(),license:Z.string().optional(),downloads:Z.number().optional(),repository:Z.string().optional(),repositoryDirectory:Z.string().optional(),repositoryId:Z.string().optional(),next:Z.record(Z.string(),Pe).optional(),warnings:Z.array(Z.string()).optional(),diagnostics:Z.array(gr).optional()}).passthrough()).optional(),repositories:Z.record(Z.string(),Z.object({repository:Z.string(),owner:Z.string(),repo:Z.string(),repositoryDirectory:Z.string().optional(),next:Z.record(Z.string(),Pe)}).passthrough()).optional(),pagination:tt.optional()}).optional(),status:Z.string().optional()})).optional()}).extend(Ue)});import{z as oe}from"zod";import{FetchContentQuerySchema as Uf}from"@octocodeai/octocode-core/schemas";var Sk,$f,Pk,Mn,ko,Ck,xk,NQ,Al=f(()=>{"use strict";ae();Ze();et();it();Be();Sk=oe.enum(["none","standard","symbols"]).optional().default("standard"),$f={startLine:hr,endLine:hr,contextLines:fr.default(5),charOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional(),minify:Sk},Pk=Se(Uf,$f),Mn=he(Uf,$f),ko=fe(Pk,{maxQueries:5}),Ck=oe.object({start:oe.number(),end:oe.number()}),xk=oe.object({path:oe.string().optional(),content:oe.string().optional(),contentView:oe.enum(["none","standard","symbols"]).optional(),totalLines:oe.number().optional(),sourceChars:oe.number().optional(),sourceBytes:oe.number().optional(),startLine:oe.number().optional(),endLine:oe.number().optional(),isPartial:oe.boolean().optional(),matchRanges:oe.array(Ck).optional(),pagination:oe.union([As.extend({nextBlockChar:oe.number().optional()}),tt]).optional(),next:oe.record(oe.string(),Pe).optional(),modified:oe.string().optional(),lastModified:oe.string().optional(),lastModifiedBy:oe.string().optional(),warnings:oe.array(oe.string()).optional(),matchNotFound:oe.boolean().optional(),searchedFor:oe.string().optional()}),NQ=oe.object({results:oe.array(oe.object({id:oe.string(),status:oe.enum(["empty","error"]).optional(),data:xk}))}).extend(sn)});import{z as ce}from"zod";import{FindFilesQuerySchema as wk}from"@octocodeai/octocode-core/schemas";function Tk(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 qf,Wf,Ek,Dn,Oo,kk,Ok,qQ,_l=f(()=>{"use strict";ae();Ze();et();it();Be();qf={maxDepth:B(0,100).optional(),minDepth:B(0,100).optional(),limit:B(1,1e4).optional(),page:Re.default(1),itemsPerPage:B(1,50).optional(),excludeDir:ce.array(ce.string()).optional().describe('Directory names to prune from the walk (e.g. ["node_modules","dist","coverage"]). NOTHING is excluded by default \u2014 results include build output and vendor dirs unless you pass this explicitly.')},Wf=ce.object(Object.fromEntries(Object.entries(wk.shape).filter(([e])=>e!=="regexType")));Ek=Se(Wf,qf),Dn=he(Wf,qf).superRefine(Tk),Oo=fe(Ek,{maxQueries:5}),kk=ce.object({name:ce.string().optional(),path:ce.string().optional(),type:ce.enum(["file","dir","directory","link","symlink"]).optional(),size:ce.union([ce.number(),ce.string()]).optional(),sizeFormatted:ce.string().optional(),modified:ce.string().optional(),accessed:ce.string().optional(),created:ce.string().optional(),permissions:ce.string().optional()}),Ok=ce.object({path:ce.string().optional(),files:ce.array(kk).optional(),summary:ce.string().optional(),pagination:on.optional(),next:ce.record(ce.string(),Pe).optional(),warnings:ce.array(ce.string()).optional()}),qQ=ce.object({results:ce.array(ce.object({id:ce.string(),status:ce.enum(["empty","error"]).optional(),data:Ok}))}).extend(sn)});import{z as F}from"zod";import{RipgrepQuerySchema as Vf}from"@octocodeai/octocode-core/schemas";var vk,Ak,Kf,Lk,_k,Fk,jt,vo,Ik,Mk,Dk,tj,Fs=f(()=>{"use strict";ae();Ze();et();it();Be();vk=["paginated","discovery","detailed","structural"],Ak=["semanticRanking"],Kf={mode:F.enum(vk).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghHistoryResearch\'s `patches.mode` \u2014 different concepts sharing this name.)'),keywords:F.string().optional().describe("The search pattern (text or regex). Set fixedString:true for a literal match, or perlRegex:true for advanced regex features (lookaheads, backreferences). (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)"),filesOnly:F.boolean().optional().describe("Returns matching file paths without line content. Mutually exclusive with filesWithoutMatch. (Unlike localViewStructure's `filesOnly`, which filters a directory listing to file entries only \u2014 a different concept sharing this name.)"),pattern:F.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:F.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:fr,matchContentLength:B(1,1e5).optional().default(500),maxMatchesPerFile:B(1,1e5).optional(),maxFiles:B(1,1e5).optional(),matchPage:Re.optional(),itemsPerPage:B(1,1e3).optional(),page:Re.default(1),unique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},Lk={...Kf,semanticRanking:F.never().optional()},_k=Se(Vf,Lk),Fk=he(Vf,Kf,{strict:!0,omit:Ak}),jt=Fk.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),vo=fe(_k,{maxQueries:5}),Ik=F.object({line:F.number(),endLine:F.number().optional(),value:F.string().optional(),column:F.number().optional(),endColumn:F.number().optional(),count:F.number().optional(),kind:F.string().optional(),scoreHint:F.number().optional(),metavars:F.record(F.string(),F.array(F.string())).optional(),metavarRanges:F.record(F.string(),F.array(F.object({text:F.string(),line:F.number(),column:F.number(),endLine:F.number(),endColumn:F.number()}))).optional()}),Mk=F.object({path:F.string(),matches:F.array(Ik).optional(),totalOccurrences:F.number().optional(),totalMatchedLines:F.number().optional(),totalMatchRows:F.number().optional(),returnedMatchRows:F.number().optional(),ranking:F.object({score:F.number(),profile:F.string().optional(),pathRole:F.string().optional(),reasons:F.array(F.string()).optional()}).optional(),matchPagination:on.optional(),pagination:on.optional(),next:F.record(F.string(),Pe).optional()}),Dk=F.object({files:F.array(Mk).optional(),summary:F.string().optional(),searchEngine:F.string().optional(),stats:F.object({totalOccurrences:F.number().optional(),matchedLines:F.number().optional(),filesMatched:F.number().optional(),filesSearched:F.number().optional(),bytesSearched:F.number().optional(),searchTime:F.string().optional()}).passthrough().optional(),pagination:on.optional(),next:F.record(F.string(),Pe).optional(),warnings:F.array(F.string()).optional()}),tj=F.object({results:F.array(F.object({id:F.string(),status:F.enum(["empty","error"]).optional(),data:Dk}))}).extend(sn)});import{z as ee}from"zod";import{ViewStructureQuerySchema as Yf}from"@octocodeai/octocode-core/schemas";var Xf,Nk,Nn,Ao,Gk,Hk,uj,Il=f(()=>{"use strict";ae();Ze();et();it();Be();Xf={maxDepth:B(0,20).optional(),limit:B(1,1e4).optional(),page:Re.default(1),itemsPerPage:B(1,50).optional(),filesOnly:ee.boolean().optional().describe("Returns files only. Mutually exclusive with directoriesOnly. (Unlike localSearchCode's `filesOnly`, which filters search results to matching file paths \u2014 a different concept sharing this name.)")},Nk=Se(Yf,Xf),Nn=he(Yf,Xf),Ao=fe(Nk,{maxQueries:5}),Gk=ee.object({name:ee.string().optional(),type:ee.enum(["file","dir","directory","link","symlink"]),path:ee.string().optional(),depth:ee.number().optional(),size:ee.union([ee.number(),ee.string()]).optional(),sizeBytes:ee.number().optional(),modified:ee.string().optional(),permissions:ee.string().optional()}),Hk=ee.object({path:ee.string().optional(),entries:ee.array(Gk).optional(),files:ee.array(ee.string()).optional(),folders:ee.array(ee.string()).optional(),links:ee.array(ee.string()).optional(),summary:ee.union([ee.string(),ee.record(ee.string(),ee.unknown())]).optional(),pagination:on.optional(),next:ee.record(ee.string(),Pe).optional(),warnings:ee.array(ee.string()).optional()}),uj=ee.object({results:ee.array(ee.object({id:ee.string(),status:ee.enum(["empty","error"]).optional(),data:Hk}))}).extend(sn)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as eh}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as Qk}from"@octocodeai/octocode-core/schemas/outputs";var jk,Bk,zk,th,Uk,Lo,_o,Jf,$k,qk,Is,Ms,Wk,Vk,nh,br,Kk,Yk,Xk,rh,Jk,Zk,eO,tO,nO,rO,oO,Zf,Sj,oh=f(()=>{"use strict";ae();Ze();et();kt();Be();jk=B(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),Bk=B(0,1e5).optional(),zk=["structured","compact"],th={type:R.enum(Cf).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:R.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:jk.optional(),orderHint:Bk,depth:B(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:Re,itemsPerPage:B(1,100).optional(),contextLines:B(0,100).optional(),format:R.enum(zk).optional().default("structured")},Uk=Se(eh,th),Lo=he(eh,th),_o=fe(Uk,{maxQueries:5}),Jf=R.object({line:R.number(),character:R.number()}),$k=R.object({start:Jf,end:Jf}),qk=R.object({startLine:R.number(),endLine:R.number()}),Is=R.object({uri:R.string(),content:R.string().optional(),displayRange:qk.optional(),isDefinition:R.boolean().optional()}),Ms=R.string(),Wk=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),Vk=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),nh=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),br=R.object({category:nh,reason:R.string()}),Kk=tt,Yk=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),Xk=R.string(),rh=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),Jk=R.string(),Zk=R.object({direction:R.enum(["incoming","outgoing"]),item:rh,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),eO=R.string(),tO=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),nO=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),rO=R.string(),oO=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Is,Ms]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Is,Ms]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Is,Ms]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Is,Ms])).optional(),byFile:R.array(R.union([nO,rO])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:br.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([rh,Jk]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([Zk,eO])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:tO,empty:br.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:$k.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([Yk,Xk])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:br.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:br.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:br.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:br.optional()}),R.object({kind:R.literal("empty"),category:nh,reason:R.string()})]),Zf=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:Wk.optional(),lsp:Vk.optional(),payload:oO,pagination:Kk.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional(),next:R.record(R.string(),Pe).optional(),hints:R.array(R.string()).optional()}),Sj=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:Zf}),R.object({id:R.string().min(1),status:R.literal("error"),data:Qk}),R.object({id:R.string().min(1),data:Zf})]))})});var ln,Fo,Ml,Dl,ih=f(()=>{"use strict";ln=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","diff","research","graph","materialize"],Fo=["fixes","dataflow"],Ml=["packages","repositories"],Dl={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});function Nl(e){return Array.isArray(e.queries)}function Gl(e){return Array.isArray(e.queries)}function Hl(e){return Array.isArray(e.children)}var sh=f(()=>{"use strict"});var un=f(()=>{"use strict";ih();sh()});import{z as U}from"zod";var ah,ch,iO,sO,Gn,Ql,aO,cO,dn,lh=f(()=>{"use strict";ah=U.enum(["smart","sensitive","insensitive"]),ch=U.string().max(1e4),iO=U.strictObject({id:U.string().optional(),kind:U.literal("text"),value:ch,case:ah.optional(),wholeWord:U.boolean().optional()}),sO=U.strictObject({id:U.string().optional(),kind:U.literal("regex"),value:ch,dialect:U.enum(["rust","pcre2","provider"]).optional(),case:ah.optional(),wholeWord:U.boolean().optional(),multiline:U.boolean().optional(),dotAll:U.boolean().optional()}),Gn=U.lazy(()=>U.strictObject({pattern:U.string().optional(),kind:U.string().optional(),inside:Gn.optional(),has:Gn.optional(),not:Gn.optional(),all:U.array(Gn).optional(),any:U.array(Gn).optional(),stopBy:U.literal("end").optional()})),Ql=U.union([Gn,U.string().min(1)]),aO=U.strictObject({id:U.string().optional(),kind:U.literal("structural"),lang:U.string().min(1),pattern:U.string().optional(),rule:Ql.optional()}),cO=U.strictObject({id:U.string().optional(),kind:U.literal("field"),field:U.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:U.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:U.unknown().optional()}),dn=U.lazy(()=>U.discriminatedUnion("kind",[U.strictObject({kind:U.literal("all"),id:U.string().optional(),of:U.array(dn).min(1)}),U.strictObject({kind:U.literal("any"),id:U.string().optional(),of:U.array(dn).min(1)}),U.strictObject({kind:U.literal("not"),id:U.string().optional(),predicate:dn}),iO,sO,aO,cO]))});import{z as P}from"zod";var Bl,jl,lO,uh,dh,ph,mh,Ds,uO,_j,fh,hh,gh,yh,Io,bh,Rh,Hn,Rr=f(()=>{"use strict";un();lh();Bl=P.lazy(()=>P.union([P.strictObject({kind:P.literal("local"),path:P.string().min(1)}),P.strictObject({kind:P.literal("github"),repo:P.string().min(1).optional(),owner:P.string().min(1).optional(),ref:P.string().min(1).optional()}),P.strictObject({kind:P.literal("materialized"),localPath:P.string().min(1),source:Bl.optional()}),P.strictObject({kind:P.literal("npm")})])),jl=P.union([P.string(),P.array(P.string()).max(100)]),lO=P.strictObject({path:jl.optional(),language:jl.optional(),include:P.array(P.string()).max(100).optional(),exclude:P.array(P.string()).max(100).optional(),excludeDir:P.array(P.string()).max(100).optional(),hidden:P.boolean().optional(),noIgnore:P.boolean().optional(),minDepth:P.number().int().min(0).max(64).optional(),maxDepth:P.number().int().min(0).max(64).optional()}).optional(),uh=P.strictObject({mode:P.enum(["never","auto","required"]),strategy:P.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:P.boolean().optional(),forceRefresh:P.boolean().optional()}),dh=P.strictObject({content:P.strictObject({range:P.strictObject({startLine:P.number().int().min(1).optional(),endLine:P.number().int().min(1).optional(),contextLines:P.number().int().min(0).max(100).optional()}).optional(),match:P.strictObject({text:P.string(),regex:P.boolean().optional(),caseSensitive:P.boolean().optional()}).optional(),contentView:P.enum(["none","standard","symbols","exact","compact"]).transform(e=>e==="exact"?"none":e==="compact"?"standard":e).optional(),charOffset:P.number().int().min(0).max(1e8).optional(),charLength:P.number().int().min(1).max(5e4).optional(),fullContent:P.boolean().optional()}).optional(),tree:P.strictObject({maxDepth:P.number().int().min(0).max(64).optional(),pattern:P.string().optional(),includeSizes:P.boolean().optional(),extensions:P.array(P.string()).optional(),filesOnly:P.boolean().optional(),directoriesOnly:P.boolean().optional(),sortBy:P.enum(["name","size","time","extension"]).optional(),reverse:P.boolean().optional()}).optional()}),ph=P.strictObject({search:P.strictObject({countLinesPerFile:P.boolean().optional(),countMatchesPerFile:P.boolean().optional(),onlyMatching:P.boolean().optional(),unique:P.boolean().optional(),countUnique:P.boolean().optional(),contextLines:P.number().int().min(0).max(100).optional(),invertMatch:P.boolean().optional(),matchWindow:P.number().int().min(0).optional(),matchContentLength:P.number().int().min(1).optional(),maxMatchesPerFile:P.number().int().min(1).optional(),matchPage:P.number().int().min(1).optional(),sort:P.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:P.boolean().optional(),rankingProfile:P.string().optional(),debugRanking:P.boolean().optional()}).optional(),budget:P.strictObject({maxFiles:P.number().int().min(1).optional(),maxCandidates:P.number().int().min(1).optional(),maxBytes:P.number().int().min(1).optional(),maxMaterializedBytes:P.number().int().min(1).optional(),maxPlanNodes:P.number().int().min(1).optional(),maxBooleanExpansion:P.number().int().min(1).optional(),timeoutMs:P.number().int().min(1).optional()}).optional()}),mh=P.enum(["discovery","paginated","detailed"]),Ds=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),target:P.enum(ln),from:Bl.optional(),scope:lO,where:dn.optional(),materialize:uh.optional(),fetch:dh.optional(),select:P.array(P.string()).optional(),view:mh.optional(),controls:ph.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional()}),uO=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),queries:P.array(Ds).min(1).max(5),combine:P.enum(["independent","merge"]).optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),explain:P.boolean().optional()}),_j=P.union([Ds,uO]),fh=[...ln,...Fo],hh={schema:P.literal("oql").optional(),id:P.string().optional(),mainResearchGoal:P.string().optional(),researchGoal:P.string().optional(),reasoning:P.string().optional()},gh={...hh,target:P.enum(fh).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Bl.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:dn.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:P.union([uh,P.enum(["never","auto","required"])]).optional(),fetch:dh.optional(),select:P.array(P.string()).optional(),view:mh.optional(),controls:ph.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional(),repo:P.string().optional(),owner:P.string().optional(),ref:P.string().optional(),path:jl.optional(),text:P.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:P.string().optional(),pattern:P.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:Ql.optional(),lang:P.string().optional(),and:P.array(P.unknown()).optional(),or:P.array(P.unknown()).optional(),xor:P.array(P.unknown()).optional(),noneOf:P.array(P.unknown()).optional(),oneOf:P.array(P.unknown()).optional(),invert:P.unknown().optional(),filesOnly:P.boolean().optional(),filesWithoutMatch:P.boolean().optional(),verbose:P.boolean().optional()},yh={...gh,target:P.enum(fh).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},Io=P.object(yh).catchall(P.unknown()),bh=P.object(gh).catchall(P.unknown()),Rh=P.object({...hh,queries:P.array(P.unknown()).min(1)}).catchall(P.unknown()),Hn=P.object({...yh,queries:P.array(P.unknown()).min(1).max(5).optional(),combine:P.enum(["independent","merge"]).optional()}).catchall(P.unknown())});var zl=f(()=>{"use strict";Ef();Ol();Lf();vl();Nf();Qf();zf();Al();_l();Fs();Il();oh();Rr()});import{z as Sh}from"zod";function pn(e){return xh.find(t=>t.name===e)}function Sr(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===Y.PACKAGE_SEARCH?"Package":"Other"}function mO(e){return[...e].sort((t,n)=>{let r=Ul.indexOf(Sr(t)),o=Ul.indexOf(Sr(n));if(r!==o)return r-o;let i=Ph.get(t)??Number.MAX_SAFE_INTEGER,s=Ph.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function fO(e){let t=pn(e);if(!t)return"{}";try{return JSON.stringify(Sh.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Sh.toJSONSchema(t.schema,{io:"input"}),null,2)}}function hO(e){return JSON.stringify(e??{},null,2)}function gO(e){let t=Sr(e),n=[...pO];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function yO(){return Ch.map(e=>({...e}))}function bO(){return JSON.stringify(Object.fromEntries(Ch.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function RO(e,t){return t?.tools?.[e]?.description??e}var Ul,Ph,st,dO,Mo,pO,Ch,xh,Do=f(()=>{"use strict";mo();kt();zl();Ul=["GitHub","Local Code","Package","Other"],Ph=new Map([Y.GITHUB_SEARCH_CODE,Y.GITHUB_SEARCH_REPOSITORIES,Y.GITHUB_SEARCH_PULL_REQUESTS,Y.GITHUB_FETCH_CONTENT,Y.GITHUB_VIEW_REPO_STRUCTURE,Y.GITHUB_CLONE_REPO,Y.LOCAL_RIPGREP,Y.LOCAL_FIND_FILES,Y.LOCAL_FETCH_CONTENT,Y.LOCAL_VIEW_STRUCTURE,Ie,Y.PACKAGE_SEARCH,...po()?[rn]:[]].map((e,t)=>[e,t])),st=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},dO=["id","mainResearchGoal","researchGoal","reasoning"],Mo=new Set([...dO]),pO=["id","researchGoal","reasoning"],Ch=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],xh=[{name:Y.GITHUB_SEARCH_CODE,schema:yo,inputSchema:bo},{name:Y.GITHUB_FETCH_CONTENT,schema:Fn,inputSchema:go},{name:Y.GITHUB_VIEW_REPO_STRUCTURE,schema:xo,inputSchema:wo},{name:Y.GITHUB_SEARCH_REPOSITORIES,schema:So,inputSchema:Po},{name:Y.GITHUB_SEARCH_PULL_REQUESTS,schema:In,inputSchema:Ro},{name:Y.PACKAGE_SEARCH,schema:To,inputSchema:Eo},{name:Y.GITHUB_CLONE_REPO,schema:yr,inputSchema:fo},{name:Y.LOCAL_RIPGREP,schema:jt,inputSchema:vo},{name:Y.LOCAL_VIEW_STRUCTURE,schema:Nn,inputSchema:Ao},{name:Y.LOCAL_FIND_FILES,schema:Dn,inputSchema:Oo},{name:Y.LOCAL_FETCH_CONTENT,schema:Mn,inputSchema:ko},{name:Ie,schema:Lo,inputSchema:_o},...po()?[{name:rn,schema:Io,inputSchema:Hn}]:[]]});import{z as SO}from"zod";function No(e){let t=pn(e);if(!t)return[];let n=SO.toJSONSchema(t.schema,{io:"input"});if(!Pr(n))return[];let r=Bt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Mo.has(i)&&!Wl(r[i])):[]);return ql(r,o)}function PO(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 $l(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Pr(e.items)?e.items:void 0;return`array<${n?$l(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Pr).map($l).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 ql(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Mo.has(o))continue;let s=Pr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:$l(s),constraints:PO(s),description:typeof s.description=="string"?s.description:void 0}),Bt(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!Wl(s.properties?.[u]):!1):[]);r.push(...ql(s.properties,l,a))}let c=s.type==="array"&&Pr(s.items)?s.items:void 0;if(c&&Bt(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!Wl(c.properties?.[u]):!1):[]);r.push(...ql(c.properties,l,a))}}return r}function Th(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[wh(e,n)]}return wh(e,t)}function wh(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 Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pr(e){return Bt(e)}function Wl(e){return Pr(e)&&"default"in e}var Ns=f(()=>{"use strict";Do()});function Eh(e){return e===rn?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===Y.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"2024-01-01T00:00:00Z",perPage:5}},{label:"releases + latest",query:{type:"releases",owner:"microsoft",repo:"TypeScript",perPage:5}},{label:"issues search",query:{type:"issues",owner:"microsoft",repo:"TypeScript",keywordsToSearch:["crash"],state:"open",concise:!0,limit:5}},{label:"issue detail",query:{type:"issues",owner:"bgauryy",repo:"octocode",issueNumber:443,content:{body:!0,comments:{discussion:!0}}}}]:e===Y.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===Y.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===Y.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===Y.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===Y.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",keywords:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===Y.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===Y.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===Y.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,filesOnly:!0,itemsPerPage:100}}]:e===Ie?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}var kh=f(()=>{"use strict";mo()});function Oh(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function CO(e){let t=Eh(e);if(t.length>0)return t.map(r=>({...r,command:Oh(e,r.query)}));let n=wO(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:Oh(e,n)}]}function xO(e){return CO(e)[0]?.query??{}}function wO(e){if(!pn(e))return{};let t=No(e),n=t.filter(i=>!i.name.includes(".")),r=TO(n),o={};for(let i of r)o[i.name]=Th(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Ie&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function TO(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&&EO(i)).sort(kO),o=Math.max(vh,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=>!Ah.has(i.name)).filter(i=>i.type!=="boolean").slice(0,vh)}function EO(e){return Ah.has(e.name)||e.type==="boolean"?!1:OO(e)?Vl.has(e.name):!0}function kO(e,t){let n=Vl.get(e.name)??Number.MAX_SAFE_INTEGER,r=Vl.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function OO(e){return e.constraints?.includes("default ")===!0}var vh,Vl,Ah,Lh=f(()=>{"use strict";kt();Do();kh();Ns();vh=4,Vl=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]]),Ah=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});function vO(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new st("Tool input must be valid JSON.")}return _h(e,r,n)}function _h(e,t,n={}){let r=LO(e,t,n),o=pn(e);if(!o)throw new st(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new st("Tool input does not match the expected schema.",AO(i.error));return i.data}function AO(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function LO(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(Bt(t)&&Array.isArray(t.queries))r=t.queries;else if(Bt(t))r=[t];else throw new st('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new st("At least one query is required.");let o=Bt(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>_O(e,a,GO(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function _O(e,t,n,r){let o={...n},i=Sr(e),s=r.sourceLabel??"direct tool execution",a=FO(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function FO(e,t){return`Execute ${e} via ${t}`}function IO(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 MO(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=IO(n,c);if(c.includes(n)||n.includes(c)){l<o&&(r=a,o=l);continue}if(n.length<3)continue;let u=Math.max(2,Math.floor(a.length/3));l<=u&&l<s&&(i=a,s=l)}return r??i}function NO(e,t){let n=DO[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n))o in t&&!(i in t)&&(r??={...t},r[i]=r[o],delete r[o]);return r??t}function GO(e,t,n,r={}){if(!Bt(t))throw new st("Tool input must be a JSON object or an array of objects.");let o=NO(e,t),i=new Set([...No(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Mo]),s={},a=[];for(let[c,l]of Object.entries(o)){if(i.has(c)){s[c]=l;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(l=>{let u=MO(l,i);return u?`'${l}' \u2192 did you mean '${u}'?`:""}).filter(Boolean);throw new st(`Unknown field(s): ${a.join(", ")}`,[...c,`Remove unknown field(s) from query ${n+1}: ${a.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return s}var DO,Fh=f(()=>{"use strict";Do();Ns();DO={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"keywords"}}});var Kl=f(()=>{"use strict";Do();Ns();Lh();Fh()});function mn(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function Cr(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 Gs(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Hs=f(()=>{"use strict"});function QO(e){let t=mn(e),n=Go.get(t);return!n||Date.now()-n.cachedAt>=HO?!1:n.credentials?!Cr(n.credentials):!0}function Yl(e){e?Go.delete(mn(e)):Go.clear()}function Ih(e){let t=mn(e);if(QO(t))return Go.get(t).credentials}function Mh(e,t){let n=mn(e);Go.set(n,{credentials:t,cachedAt:Date.now()})}var Go,HO,Dh=f(()=>{"use strict";Hs();Go=new Map,HO=300*1e3});import{existsSync as jO,mkdirSync as BO}from"node:fs";import{join as St}from"node:path";import{getOctocodeHome as zO}from"@octocodeai/config";function $O(){return zO(process.env)}function xr(){return nt}function Nh(){jO(zt.home)||BO(zt.home,{recursive:!0,mode:UO})}var UO,nt,zt,Qs=f(()=>{"use strict";UO=448;nt=$O(),zt={home:nt,config:St(nt,".octocoderc"),credentials:St(nt,"credentials.json"),key:St(nt,".key"),session:St(nt,"session.json"),stats:St(nt,"stats.json"),tmp:St(nt,"tmp"),clone:St(nt,"tmp","clone"),tree:St(nt,"tmp","tree"),repos:St(nt,"tmp","clone"),cliConfig:St(nt,"config.json"),lspConfig:St(nt,"lsp-servers.json")}});import{z as Me}from"zod";var qO,WO,Gh,Hh=f(()=>{"use strict";qO=Me.object({token:Me.string(),tokenType:Me.literal("oauth"),scopes:Me.array(Me.string()).optional(),refreshToken:Me.string().optional(),expiresAt:Me.string().optional(),refreshTokenExpiresAt:Me.string().optional()}),WO=Me.object({hostname:Me.string(),username:Me.string(),token:qO,gitProtocol:Me.enum(["ssh","https"]),createdAt:Me.string(),updatedAt:Me.string()}),Gh=Me.object({version:Me.number(),credentials:Me.record(Me.string(),WO)})});import{existsSync as Qh,readFileSync as jh,writeFileSync as Bh,unlinkSync as kB,statSync as VO,chmodSync as KO}from"node:fs";import{createCipheriv as YO,createDecipheriv as XO,randomBytes as zh}from"node:crypto";function jn(){Nh()}function qh(){if(jn(),Qh(Qn))return VO(Qn).mode&511&63&&KO(Qn,384),Buffer.from(jh(Qn,"utf8"),"hex");let e=zh(32);return Bh(Qn,e.toString("hex"),{mode:384}),e}function Xl(e){let t=qh(),n=zh(JO),r=YO($h,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 Jl(e){let t=qh(),[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=XO($h,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function js(){if(jn(),!Qh(Ho))return{version:1,credentials:{}};try{let e=jh(Ho,"utf8"),t=Jl(e),n=JSON.parse(t),r=Gh.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Wh(e){jn();let t=Xl(JSON.stringify(e,null,2));Bh(Ho,t,{mode:384})}var Uh,Ho,Qn,$h,JO,Vh=f(()=>{"use strict";Qs();Hh();Uh=zt.home,Ho=zt.credentials,Qn=zt.key,$h="aes-256-gcm",JO=16});var Qo,wr,Zl=f(()=>{"use strict";Qo="178c6fc778ccc68e1d6a",wr="github.com"});import{refreshToken as ZO}from"@octokit/oauth-methods";import{request as ev}from"@octokit/request";function tv(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 nv(e){return e==="github.com"||e===wr?"https://api.github.com":`https://${e}/api/v3`}async function Kh(e,t=wr,n=Qo){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(Gs(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await ZO({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:ev.defaults({baseUrl:nv(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?tv(o.message):"Token refresh failed"}}}async function Yh(e,t=wr,n=Qo){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!Cr(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Kh(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var Xh=f(()=>{"use strict";Hs();Zl()});import{execFile as rv}from"child_process";function eu(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=ov.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;rv("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var ov,tu=f(()=>{"use strict";ov=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});import{resolveEnvToken as iv}from"@octocodeai/config";function Jh(e){nu=e}function sv(){if(!nu)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return nu}async function Bs(e){let t=e?.hostname??wr,n=e?.clientId??Qo,r=e?.getGhCliToken??eu,o=iv();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await sv().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)}
9
- `)}return null}var nu,Zh=f(()=>{"use strict";tu();Zl();nu=null});async function eg(e){let t=mn(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=js();return r.credentials[t]=n,Wh(r),Yl(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function ru(e="github.com",t){let n=mn(e);if(!t?.bypassCache){let i=Ih(n);if(i!==void 0)return i}let o=js().credentials[n]||null;return Mh(n,o),o}async function tg(e,t){let n=await ru(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await eg(n),!0):!1}async function ng(e,t){return Yh({getCredentials:ru,updateToken:tg},e,t)}var ou=f(()=>{"use strict";Dh();Vh();Xh();Zh();Hs();Jh({getTokenWithRefresh:ng})});var rg=f(()=>{"use strict";ou();tu()});import zs from"node:os";import fz from"node:path";var uv,dv,pv,mv,og=f(()=>{"use strict";uv=zs.platform()==="win32",dv=zs.platform()==="darwin",pv=zs.platform()==="linux",mv=zs.homedir()});var ig=f(()=>{"use strict";og()});import{z as X}from"zod";var fv,hv,Us,gv,$s,sg,ag,cg=f(()=>{"use strict";fv=X.object({rawChars:X.number(),responseChars:X.number(),savedChars:X.number(),calls:X.number()}),hv=X.object({hits:X.record(X.string(),X.number()).default({}),rateLimits:X.number().default(0)}),Us=X.record(X.string(),X.number()).default({}),gv=X.object({toolCalls:X.number(),errors:X.number(),rateLimits:X.number(),rateLimitsByProvider:Us,rawChars:X.number(),responseChars:X.number(),savedChars:X.number(),charSavingsCalls:X.number(),githubCacheHits:X.number(),githubCacheRateLimits:X.number(),packageRegistryFailures:X.number().default(0),packageRegistryFailuresByRegistry:Us}),$s=X.object({toolCalls:X.number(),errors:X.number(),rateLimits:X.number(),rateLimitsByProvider:Us,charsSavedByTool:X.record(X.string(),fv).default({}),githubCacheHits:hv.default({hits:{},rateLimits:0}),packageRegistryFailures:Us,totalUsage:gv.optional()}),sg=X.object({version:X.literal(1),sessionId:X.string(),createdAt:X.string(),lastActiveAt:X.string(),stats:$s.optional()}),ag=X.object({version:X.literal(1),stats:$s})});function lg(e){return Object.values(e).reduce((t,n)=>t+n,0)}function yv(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:lg(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:lg(o),packageRegistryFailuresByRegistry:o}}function fn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:yv(t)}}function Tr(){return fn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var iu=f(()=>{"use strict"});import{existsSync as dg,readFileSync as pg,writeFileSync as bv,unlinkSync as Ez,renameSync as Rv}from"node:fs";import{isStatsEnabled as mg}from"@octocodeai/config";function ug(e,t){let n=`${e}.tmp`;bv(n,JSON.stringify(t,null,2),{mode:384}),Rv(n,e)}function Sv(e){let t=JSON.parse(e),n=ag.safeParse(t);if(n.success)return fn(n.data.stats);let r=$s.safeParse(t);return r.success?fn(r.data):null}function Pv(){if(!dg(Bo))return Tr();try{let e=pg(Bo,"utf8");return Sv(e)??Tr()}catch{return Tr()}}function su(e){jn(),mg()&&ug(Bo,{version:e.version,stats:fn(e.stats)});let{stats:t,...n}=e;ug(jo,n)}function fg(){if(!dg(jo))return null;try{let e=pg(jo,"utf8"),t=JSON.parse(e),n=sg.safeParse(t);return n.success?{...n.data,stats:mg()?Pv():Tr()}:null}catch{return null}}var jo,Bo,qs=f(()=>{"use strict";ou();Qs();cg();iu();jo=zt.session,Bo=zt.stats});function xv(){hg||(hg=!0,gg=()=>{Ws()},yg=()=>{Ws()},bg=()=>{Ws()},process.on("exit",gg),process.on("SIGINT",yg),process.on("SIGTERM",bg))}function wv(){au||(au=setInterval(()=>{zo&&hn&&(su(hn),zo=!1)},Cv),au.unref())}function Rg(){if(hn)return hn;let e=fg();return e&&(hn=e),e}function Sg(e){hn=e,zo=!0,xv(),wv()}function Ws(){if(!cu&&zo&&hn){cu=!0;try{su(hn),zo=!1}catch{}finally{cu=!1}}}var Cv,hn,zo,au,hg,gg,yg,bg,cu,Pg=f(()=>{"use strict";qs();Cv=6e4,hn=null,zo=!1,au=null,hg=!1,gg=null,yg=null,bg=null,cu=!1});import{randomUUID as Bz}from"node:crypto";function Tv(e){return fn(e)}function Ev(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 Cg(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 kv(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 gn(e){let t=Rg();if(!t)return{success:!1,session:null};let n=Tv(t.stats),r=fn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Cg(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Ev(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:kv(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Cg(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Sg(o),{success:!0,session:o}}function lu(e=1){return gn({rateLimits:e})}function uu(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return gn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function du(e,t=1){return gn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function pu(e=1){return gn({githubCacheHits:{hits:{},rateLimits:e}})}var Uo=f(()=>{"use strict";qs();iu();Pg();qs()});var xg=f(()=>{"use strict";Uo();Uo();Uo();Uo()});import{z as Ce}from"zod";var Ov,wg=f(()=>{"use strict";Ov=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{setRuntimeSurface as yU,invalidateConfigCache as bU}from"@octocodeai/config";var Tg=f(()=>{"use strict";wg()});import{existsSync as vv,readdirSync as Av,lstatSync as Lv}from"node:fs";import{join as _v}from"node:path";function Vs(e){if(!vv(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Av(r)}catch{continue}for(let i of o){let s=_v(r,i);try{let a=Lv(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var Eg=f(()=>{"use strict"});var Ot=f(()=>{"use strict";rg();ig();xg();Tg();Qs();Eg()});var Bn,Ks=f(()=>{Bn="17.0.1"});var mu,$o,qo,Iv,yn,bn,qe,Mv,Wo,Dv,AU,at=f(()=>{"use strict";mu={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},$o={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"}},qo={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})`}},Iv={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"}},yn={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}`}},bn={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"}},qe={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}`}},Mv={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}`}},Wo={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Dv={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}`}},AU={...mu,...$o,...qo,...Iv,...yn,...bn,...qe,...Mv,...Wo,...Dv}});import{getConfigSync as kg,invalidateConfigCache as IU}from"@octocodeai/config";import{maskSensitiveData as Nv}from"@octocodeai/octocode-engine/mask";async function Og(){try{let e=await Gv({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:Hv.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function vg(){if(Ko!==null)return;if(Vo!==null)return Vo;let e=(async()=>{let t=kg(),n=await Og();Ko={version:Bn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Vo=e;try{await e}catch(t){throw Vo===e&&(Ko=null,Vo=null),t}}function fu(){if(!Ko){let e=Nv(mu.NOT_INITIALIZED.message);throw new Error(e)}return Ko}async function hu(){return(await Og()).token}function gu(){return"github"}function yu(){let e=kg().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var Ko,Vo,Gv,Hv,Yo=f(()=>{"use strict";Ot();Ks();at();Ko=null,Vo=null,Gv=Bs,Hv=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});import{createRequire as Qv}from"node:module";function se(){if(Ys)return Ys;try{return Ys=Bv(),Ys}catch(e){throw new bu(e)}}var jv,Ag,Ys,Bv,bu,D,Ee=f(()=>{"use strict";jv=Qv(import.meta.url),Ag="@octocodeai/octocode-engine",Bv=()=>jv(Ag),bu=class extends Error{constructor(n){super(`Failed to load native dependency ${Ag}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return se().applyContentViewMinification(e,t)},applyMinification(e,t){return se().applyMinification(e,t)},minifyContent(e,t){return se().minifyContent(e,t)},minifyContentSync(e,t){return se().minifyContentSync(e,t)},minifyContentResult(e,t){return se().minifyContentResult(e,t)},minifyMarkdownCore(e){return se().minifyMarkdownCore(e)},extractSignatures(e,t){return se().extractSignatures(e,t)},extractJsSymbols(e,t){return se().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return se().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return se().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return se().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return se().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return se().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return se().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return se().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return se().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return se().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return se().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return se().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return se().parseRipgrepJson(e,t)},searchRipgrep(e){return se().searchRipgrep(e)},queryFileSystem(e){return se().queryFileSystem(e)},extractMatchingLines(e,t,n){return se().extractMatchingLines(e,t,n)},filterPatch(e,t){return se().filterPatch(e,t)},computeLineDiff(e,t){return se().computeLineDiff(e,t)},charToByteOffset(e,t){return se().charToByteOffset(e,t)},byteToCharOffset(e,t){return se().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return se().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return se().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return se().SIGNATURES_ONLY_HINT}}});function Rn(e){(e.provider?gn({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):lu(1)).session&&e.provider==="github"&&pu(1)}function Lg(e){gn({packageRegistryFailures:{[e]:1}})}var Xs=f(()=>{"use strict";Ot()});import{Octokit as zv}from"octokit";import{throttling as Uv}from"@octokit/plugin-throttling";import{createHash as $v}from"crypto";function Dg(e){return $v("sha256").update(e).digest("hex").substring(0,16)}async function He(e){let t=e?.token??await hu(),n=t?Dg(t):"anon",r=fu().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}function Ng(e){return Date.now()-e.createdAt>Wv}function Gg(){for(let[e,t]of Ut.entries())Ng(t)&&Ut.delete(e);if(Ut.size>Ru){let e=Ut.size-Ru,t=0;for(let[n]of Ut){if(t>=e)break;Ut.delete(n),t++}}}function Kv(){Xo||(Xo=setInterval(Gg,Vv),typeof Xo=="object"&&"unref"in Xo&&Xo.unref())}function Ig(e,t,n){Rn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function Xv(e){let t=fu(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Bn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:Yv(),log:r,...e&&{auth:e}};return new qv(o)}async function ie(e){Kv();let t=e?.token??await hu(),n=t?Dg(t):"ANONYMOUS",r=Ut.get(n);if(r&&!Ng(r))return r.client;Ut.size>=Ru&&Gg();let o=Xv(t??void 0);return Ut.set(n,{client:o,createdAt:Date.now()}),o}async function We(e,t,n){let r=`${e}/${t}`,o=Jo.get(r);if(o)return o;let i=await ie(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Mg(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),Mg(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Mg(e,t){if(Jo.size>=Jv){let n=Jo.keys().next().value;n!==void 0&&Jo.delete(n)}Jo.set(e,t)}var qv,Wv,Ru,Vv,Ut,Xo,_g,Fg,Yv,Jv,Jo,Ae=f(()=>{"use strict";Yo();Yo();Ks();Xs();qv=zv.plugin(Uv),Wv=300*1e3,Ru=50,Vv=60*1e3;Ut=new Map,Xo=null;_g=3,Fg=60;Yv=()=>({onRateLimit:(e,t,n,r)=>(Ig("primary",e,t),r<_g&&e<Fg),onSecondaryRateLimit:(e,t,n,r)=>(Ig("secondary",e,t),r<_g&&e<Fg)});Jv=200,Jo=new Map});var V,Le,Hg,Su,Pu,Js,Qg=f(()=>{"use strict";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"},Le={[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."}},Hg={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},Su={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},Pu={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Js={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as jg}from"octokit";function vt(e){if(!(e instanceof jg)||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 Zv.some(o=>r.includes(o))})}function ne(e){return e instanceof jg?eA(e):e instanceof Error?cA(e):{error:typeof e=="string"?e:Le[V.UNKNOWN].message,type:"unknown"}}function eA(e){let{status:t,message:n,response:r}=e;if(t===403)return nA(n,r);if(t===429)return tA(n,r);let o=Hg[t];return o?aA(o,t):Er(V.UNKNOWN,{error:n||Le[V.UNKNOWN].message,status:t})}function Cu(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function tA(e,t){let n=t?.headers,r=Cu(n,"retry-after"),o=Cu(n,"x-ratelimit-reset"),i=Cu(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Js.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||Le[V.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Le[V.RATE_LIMIT_PRIMARY].suggestion})}function nA(e,t){let n=t?.headers;if(Pu.SECONDARY.test(e))return rA(n);let r=n?.["x-ratelimit-remaining"],o=sA(t);return r!==void 0&&String(r)==="0"||o?oA(n):iA(n)}function rA(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Js.SECONDARY_FALLBACK_SECONDS:t;return Rn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Er(V.RATE_LIMIT_SECONDARY,{error:Le[V.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Le[V.RATE_LIMIT_SECONDARY].suggestion})}function oA(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)+Js.RESET_BUFFER_SECONDS,0):void 0,i=r?Le[V.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Le[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:Le[V.RATE_LIMIT_PRIMARY].suggestion})}function iA(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Le[V.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=lA(String(t),String(n))),Er(V.FORBIDDEN_PERMISSIONS,{error:Le[V.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function sA(e){return e?.data?.errors?.some(n=>n.type===Pu.GRAPHQL_TYPE)??!1}function aA(e,t){let n=Le[e];return Er(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function cA(e){return Su.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Le[V.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Le[V.NETWORK_CONNECTION_FAILED].suggestion}:Su.TIMEOUT.some(t=>e.message.includes(t))?{error:Le[V.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Le[V.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Er(e,t){return{type:"http",...t}}function lA(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?Le[V.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Le[V.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var Zv,rt=f(()=>{"use strict";Qg();Xs();Zv=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function Bg(e){return`user:${e}`}function xu(e){return e.startsWith('"')||dA.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var uA,dA,$t,Zo=f(()=>{"use strict";uA=/[@/]/,dA=/^[A-Za-z0-9_-]+$/;$t=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(Bg(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=uA.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}}});function Eu(e){return new wu().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ku(e){return new Tu().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var pA,wu,Tu,zg=f(()=>{"use strict";Zo();pA=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,wu=class extends $t{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(xu))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(pA):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}},Tu=class extends $t{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(xu)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}}});function vu(e){return new Ou().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Au(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Ou,Ug=f(()=>{"use strict";Zo();Ou=class extends $t{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});function _u(e){return new Lu().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Fu(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Lu,$g=f(()=>{"use strict";Zo();Lu=class extends $t{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}}});var kr=f(()=>{"use strict";Zo();zg();Ug();$g()});import mA from"crypto";function gA(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(hA.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function ke(e,t,n){let r=Iu(gA(t)),o=n?`${n}:${r}`:r,i=mA.createHash("sha256").update(o).digest("hex");return`${fA}-${e}:${i}`}function Iu(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=>Iu(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Iu(i,t)}`}).join(",")}}`)}var fA,hA,qg=f(()=>{"use strict";fA="v2",hA=new Set([])});import yA from"node-cache";function RA(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function SA(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function ei(e){let t=RA(e);if(!(!t||!SA(t)))try{du(t,1)}catch{}}function Zs(){let e=Date.now();for(let[t,n]of Ct.entries())e-n.startedAt>bA&&Ct.delete(t)}function ti(e){return Wg[e]||Wg.default}function ni(e,t,n){try{return Pt.set(e,t,n),ct.sets++,ct.totalKeys=Pt.keys().length,!0}catch{try{let r=Pt.keys();for(let o of r)Pt.get(o);return Pt.set(e,t,n),ct.sets++,ct.totalKeys=Pt.keys().length,!0}catch{return!1}}}var bA,Pt,ct,Wg,Ct,ea=f(()=>{"use strict";Ot();bA=300*1e3,Pt=new yA({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ct={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Wg={"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});async function Qe(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Pt.get(e);if(i!==void 0)return ct.hits++,ei(e),i}catch{}Zs();let r=Ct.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ct.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=ti(l)}ni(e,i,a)}return i}finally{Ct.delete(e)}})();return Ct.set(e,{promise:o,startedAt:Date.now()}),o}var Vg=f(()=>{"use strict";ea()});import PA from"node-cache";async function ta(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Pt.get(e);if(i!==void 0)return ct.hits++,ei(e),i}catch{}Zs();let r=Ct.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:Mu.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ct.hits++,ei(e);let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=ti(u)}return ni(e,i.data,c),i.data}if(n.forceRefresh||ct.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=ti(u)}ni(e,s.value,c),Mu.set(e,{data:s.value,etag:s.etag})}return s.value}finally{Ct.delete(e)}})();return Ct.set(e,{promise:o,startedAt:Date.now()}),o}var Mu,Du=f(()=>{"use strict";ea();Mu=new PA({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1})});var Kg=f(()=>{"use strict";ea();Du()});var lt=f(()=>{"use strict";qg();Vg();Du();Kg()});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as I$,DISCOVERY_IGNORED_FILE_NAMES as M$,DISCOVERY_IGNORED_FOLDER_NAMES as D$,getDiscoveryExtension as Yg,shouldIgnoreDiscoveryDir as ri,shouldIgnoreDiscoveryFile as Or}from"@octocodeai/octocode-engine/security";var oi=f(()=>{"use strict"});function j(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Jg(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function W(e,t){let n=typeof t=="number"?Jg(t):j(t);if(n===void 0)return e;try{Object.defineProperty(e,Xg,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function le(e){if(!(typeof e!="object"||e===null))return Jg(e[Xg])}var Xg,ue=f(()=>{"use strict";Xg=Symbol.for("octocode.rawResponseChars")});function ii(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 vr(e){let t=ii(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}var Ar=f(()=>{"use strict"});import{ContentSanitizer as CA}from"@octocodeai/octocode-engine/contentSanitizer";async function ey(e,t,n){let r=await He(t),o=ke("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 Qe(o,async()=>await xA(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function xA(e,t){try{let n=await ie(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(b=>b&&b.trim()).length===0)return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let r=Eu(e);if(!r.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Zg,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 wA(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),h=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:h,...h?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:ii(a.headers),rawResponseChars:j(a.data)}}catch(n){if(vt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Zg,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 ne(n)}}async function wA(e,t){let n=TA(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!Or(p.path)),c=0,l=0,u=await Promise.allSettled(a.map(async p=>{s.add(p.path);let h=[],g=await Promise.allSettled((p.text_matches||[]).map(async k=>{let E=k.fragment,_=CA.sanitizeContent(E||"",p.path);E=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(w=>r.add(`${p.path}: ${w}`));try{let w=await D.minifyContent(E||"",p.path);E=w.content,w.failed?o=!0:w.type!=="failed"&&(h.push(w.type),i.push(w.type))}catch{o=!0}return{context:E||"",positions:k.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),y=g.filter(k=>k.status==="fulfilled").map(k=>k.value),b=g.filter(k=>k.status==="rejected").length;b>0&&(l+=b);let S=p,x=Array.from(new Set(h));return{path:p.path,matches:y,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...x.length>0&&{minificationType:x.join(",")}}})),d=u.filter(p=>p.status==="fulfilled").map(p=>p.value);c=u.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function TA(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 Zg,ty=f(()=>{"use strict";Ee();Ae();rt();kr();lt();oi();at();ue();Ar();ae();Zg=30});function ry(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 oy(e,t,n){let r=await He(t),o=e,i=ke("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await Qe(i,async()=>await kA(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function EA(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){if(p?.status!==404)return ne(p);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return ne(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),y=g[0]||"",b=g[1]||"";return{owner:y,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...ry(p)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:m,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:j(i)}}async function kA(e,t){try{let n=await ie(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await EA({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=ku(e);if(!i.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||ny,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let k=S.full_name.split("/"),E=k[0]||"",_=k[1]||"";return{owner:E,repo:_,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...ry(S)}}),m=u.data.total_count,p=Math.min(m,1e3),h=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,h)),y=g<h,b=Math.min(p,h*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:h,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:y,...y?{nextPage:g+1}:{}}},status:200,headers:ii(u.headers),rawResponseChars:j(u.data)}}catch(n){if(vt(n)){let r=Math.min(e.limit||ny,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 ne(n)}}var ny,iy=f(()=>{"use strict";Ae();rt();kr();lt();at();ue();Ar();ae();ny=30});function At(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var Lr=f(()=>{"use strict"});function _e(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 OA(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 qt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:OA(e)}}function na(e){return vA(e)?qt({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 vA(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||AA(n)}function AA(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var Lt=f(()=>{"use strict"});function si(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}var Nu=f(()=>{"use strict"});function LA(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,...si(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function _A(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,...si(e.pagination)},nonExistentScope:e.nonExistentScope}}async function sy(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await ey(s,t);return At(a)?qt(a):a.data?{data:LA(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function ay(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await oy(n,t);return"error"in r?na(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:_A(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??j(r.data)}}var cy=f(()=>{"use strict";ty();iy();Lr();ue();Lt();Lt();Nu()});import{completeMetadata as Gu}from"@octocodeai/octocode-core";var v,ly=f(()=>{"use strict";v=new Proxy({},{get(e,t){return Gu.toolNames[t]},ownKeys(){return Object.keys(Gu.toolNames)},getOwnPropertyDescriptor(e,t){let n=Gu.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as Hu}from"@octocodeai/octocode-core";function ra(e=Hu){if(Qu&&e===Hu)return Qu;let t=e,n=t.tools?.localFindFiles;n?.description&&uy.test(n.description)&&(t={...t,tools:{...t.tools,localFindFiles:{...n,description:n.description.replace(uy,IA)}}});let r=t.tools?.ghHistoryResearch;return r?.description&&dy.test(r.description)&&(t={...t,tools:{...t.tools,ghHistoryResearch:{...r,description:r.description.replace(dy,MA)}}}),e===Hu&&(Qu=t),t}var uy,IA,dy,MA,Qu,ju=f(()=>{"use strict";uy=/Default excludeDir skips common generated\/vendor dirs; pass \[\] to search all\./,IA='Nothing is excluded by default \u2014 pass excludeDir (e.g. ["node_modules","dist","coverage"]) to prune build/vendor dirs.',dy=/type:"prs" searches PRs; add prNumber to read selected content\. type:"commits" reads owner\/repo\/path history\./,MA='type:"prs" searches PRs; add prNumber to read selected content. type:"commits" reads owner/repo/path history. type:"issues" searches or reads GitHub issues; add issueNumber to read a specific issue (body + comments). type:"releases" lists repo releases.',Qu=null});var Bu,py=f(()=>{"use strict";ju();Bu=new Proxy({},{get(e,t){return ra().tools[t]?.description??""}})});import{completeMetadata as DA}from"@octocodeai/octocode-core";function zu(e){return Object.prototype.hasOwnProperty.call(DA.tools,e)}var my=f(()=>{"use strict"});import{completeMetadata as NA}from"@octocodeai/octocode-core";function Uu(){return NA.baseSchema}var GA,fy=f(()=>{"use strict";GA=new Proxy({},{get(e,t){return Uu()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Uu())]))},getOwnPropertyDescriptor(e,t){let n=Uu();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var pe=f(()=>{"use strict";ly();py();my();fy()});function $u(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function qu(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(p=>p.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>l.push(p.path)),l.length===0&&d.length>=3&&c.filter(h=>{let g=h.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(h=>l.push(h.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var hy=f(()=>{"use strict"});import{RequestError as Wu}from"octokit";async function HA(e,t,n,r,o,i,s,a){let c=await We(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=ne(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await qu(e,r,o,i,s||c);return m.length>0&&(u.hints=[...u.hints||[],...$u(i,m)]),{...u,...d&&{scopesSuggestion:d}}}async function QA(e,t,n,r,o,i){let s=ne(t),a=await qu(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...$u(o,a)]),s}async function gy(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:yn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:yn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:yn.DECODE_FAILED.message,type:"unknown",status:422}}}async function yy(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"?gy(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return ne(i)}}async function jA(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 We(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(m=>m.name===a&&m.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await yy(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return ne(s)}}async function ai(e,t,n={}){try{let r=await ie(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(p){if(p instanceof Wu&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof Wu&&p.status===404)if(a){let h=await HA(r,p,c,o,i,s,a,t);if("result"in h)l=h.result,u=h.actualBranch;else return h}else return await QA(r,p,o,i,s,a);else{if(p instanceof Wu&&p.status===413)return await jA(r,o,i,s,a||u,t);throw p}}let d=l.data,m=vr(l.headers);if(Array.isArray(d))return{error:yn.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",h=d.size??0,g;if(p.length>0)g=await gy(p,s);else if(h>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await yy(r,o,i,d.sha,s);else return{error:yn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!u&&!a)try{u=await We(o,i,t)}catch{}return{data:{rawContent:g.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:j(d),...m?{etag:m}:{}}}return{error:yn.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return ne(r)}}var by=f(()=>{"use strict";Ae();rt();pe();at();ue();Ar();hy()});var Vu=f(()=>{"use strict";by()});function ci(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function _t(e){return ci(e).length}var _r=f(()=>{"use strict"});function oa(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(`
10
- `),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 Ku=f(()=>{"use strict";Ee()});function zA(e){return BA.test(e.split(/[?#]/,1)[0]??e)}function Ry(e,t){return zA(t)?$A(UA(e)):null}function ia(e,t){let n=Ry(e,t);if(n===null||n.length===0)return null;let r=[];return Py(n,r),r.join(`
11
- `)}function Sy(e,t){let n=Ry(e,t);return n===null?null:n.map(Cy)}function UA(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 $A(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 Py(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}`),Py(n.children,t)}}function Cy(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(Cy)}}var BA,sa=f(()=>{"use strict";BA=/\.(?:md|markdown|mdx)$/i});import{getConfigSync as qA,DEFAULT_OUTPUT_CONFIG as WA}from"@octocodeai/config";function zn(){try{return qA().output.pagination.defaultCharLength}catch{return WA.pagination.defaultCharLength}}var aa=f(()=>{"use strict"});function Yu(e,t){return D.byteToCharOffset(e,t)}function xy(e,t){return D.charToByteOffset(e,t)}function wy(e){return D.charToByteOffset(e,e.length)}function Xu(e,t,n,r){return D.sliceContent(e,t,n,r)}var Ty=f(()=>{"use strict";Ee()});function ca(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=wy(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,m,p,h,g;if(o==="bytes"){let y=Math.min(t,s),b=Math.min(y+n,s);d=Yu(e,y),m=Yu(e,b),m<i&&xy(e,m)<b&&(m+=1);let S=Xu(e,d,m-d);c=S.text,d=S.charOffset,m=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,p=u<s;let x=r.actualOffset??y;h=Math.floor(x/a)+1,g=Math.max(h,Math.ceil(s/a))}else{let y=Xu(e,t,n);c=y.text,d=y.charOffset,m=y.charOffset+y.charLength,l=y.byteOffset,u=y.byteOffset+y.byteLength,p=m<i;let b=r.actualOffset??d;h=Math.floor(b/a)+1,g=Math.max(h,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:p?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:h,totalPages:g}}function Ju(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 Zu=f(()=>{"use strict";Ty()});function YA(e){return e&&e.trim().length>0?e:KA}async function Ey(e,t){return(await D.getSemanticBoundaryOffsets(e,YA(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function XA(e,t){let n=e.indexOf(`
8
+ var YE=Object.defineProperty;var f=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var XE=(e,t)=>{for(var n in t)YE(e,n,{get:t[n],enumerable:!0})};import{completeMetadata as JE}from"@octocodeai/octocode-core";function mo(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var Y,Ie,rn,cH,fo=f(()=>{"use strict";Y=JE.toolNames,Ie=Y.LSP_GET_SEMANTIC_CONTENT,rn="oqlSearch";cH=new Set([Y.LOCAL_RIPGREP,Y.LOCAL_FETCH_CONTENT,Y.LOCAL_FIND_FILES,Y.LOCAL_VIEW_STRUCTURE,Ie])});function Qt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function El(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var Cf,kt=f(()=>{"use strict";fo();Cf=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});var ae=f(()=>{"use strict"});import{z as As}from"zod";function B(e,t){return As.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,As.number().int().min(e).max(t))}function fe(e,t={}){let{maxQueries:n=5}=t;return As.object({queries:As.array(e).min(1).max(n).describe("Parallel queries."),...ek}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var Re,fr,hr,ek,Ze=f(()=>{"use strict";ae();Re=B(1,1e3).optional().default(1),fr=B(0,100).optional(),hr=B(1,1e9).optional(),ek={responseCharOffset:B(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:B(1,5e4).optional().describe("Full-response char window.")}});import{z as xf}from"zod";function tk(e,t){return e?.description&&!t.description?t.describe(e.description):t}function wf(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=tk(e.shape[r],o);return n}function nk(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Tf(e,t){if(!t?.length)return e;let n=new Set(t);return xf.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function he(e,t={},n={}){let r=Tf(e,n.omit),o=nk(r,wf(r,t));return n.strict?o.strict():o}function Se(e,t={},n={}){let r=Tf(e,n.omit),o=xf.object({...r.shape,...wf(r,t)});return n.strict?o.strict():o}var et=f(()=>{"use strict"});import{z}from"zod";function Ls(e,t,n="Continue to the next page of results."){return{tool:e,query:t,why:n,confidence:"exact"}}function _s(e,t,n,r){if(!n||!n.hasMore||n.nextCharOffset===void 0)return;let o=r?.includeCharLength!==!1;return{continueChars:{tool:e,query:{...t,charOffset:n.nextCharOffset,...o&&n.charLength!==void 0?{charLength:n.charLength}:{}}}}}var tt,gr,Pe,on,yr,Be=f(()=>{"use strict";tt=z.object({currentPage:z.number(),totalPages:z.number(),hasMore:z.boolean(),nextPage:z.number().optional(),pageSize:z.number().optional(),totalItems:z.number().optional(),perPage:z.number().optional(),totalFound:z.number().optional(),returned:z.number().optional(),totalMatches:z.number().optional(),reportedTotalMatches:z.number().optional(),reachableTotalMatches:z.number().optional(),totalMatchesKind:z.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:z.boolean().optional(),totalResults:z.number().optional(),itemsPerPage:z.number().optional()}),gr=z.object({charOffset:z.number(),charLength:z.number(),totalChars:z.number(),hasMore:z.boolean(),nextCharOffset:z.number().optional(),currentPage:z.number().optional(),totalPages:z.number().optional(),chunkMode:z.enum(["semantic","char-limit"]).optional()}),Pe=z.object({tool:z.string(),query:z.record(z.string(),z.unknown()),why:z.string().optional(),confidence:z.enum(["exact","heuristic"]).optional()}),on=tt.extend({filesPerPage:z.number().optional(),entriesPerPage:z.number().optional(),matchesPerPage:z.number().optional(),totalFiles:z.number().optional(),totalEntries:z.number().optional(),totalMatches:z.number().optional(),totalFilesFound:z.number().optional(),nextMatchPage:z.number().optional()});yr=z.object({level:z.enum(["info","warning","error"]),message:z.string(),field:z.string().optional(),code:z.string().optional()})});import{z as ge}from"zod";function ok(e){return ge.object({id:ge.string(),status:ge.enum(["empty","error"]).optional(),data:e,diagnostics:ge.array(yr).optional(),next:ge.record(ge.string(),Pe).optional()})}var rk,Ue,CH,sn,it=f(()=>{"use strict";Be();rk=ge.object({currentPage:ge.number(),totalPages:ge.number(),hasMore:ge.boolean(),charOffset:ge.number(),charLength:ge.number(),totalChars:ge.number(),nextCharOffset:ge.number().optional()}).optional(),Ue={base:ge.string().optional(),shared:ge.record(ge.string(),ge.union([ge.string(),ge.number(),ge.boolean()])).optional(),responsePagination:rk};CH=ok(ge.record(ge.string(),ge.unknown()).optional()),sn=Ue});import{CloneRepoQuerySchema as ik}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as sk}from"@octocodeai/octocode-core/schemas/outputs";var br,ho,vH,Ef=f(()=>{"use strict";Ze();et();it();br=he(ik),ho=fe(br),vH=sk.extend(Ue)});import{z as O}from"zod";import{FileContentQuerySchema as kf}from"@octocodeai/octocode-core/schemas";var ak,ck,lk,uk,dk,Of,pk,Fn,yo,GH,Ol=f(()=>{"use strict";ae();Ze();et();it();Be();ak=O.enum(["none","standard","symbols"]).optional().default("standard"),ck=O.union([gr.extend({nextPage:O.number().optional()}),tt.extend({charOffset:O.number().optional(),charLength:O.number().optional(),totalChars:O.number().optional(),nextCharOffset:O.number().optional()})]),lk=O.record(O.string(),Pe),uk=O.object({path:O.string(),content:O.string(),localPath:O.string().optional(),repoRoot:O.string().optional(),contentView:O.enum(["none","standard","symbols"]).optional(),totalLines:O.number().optional(),sourceChars:O.number().optional(),sourceBytes:O.number().optional(),resolvedBranch:O.string().optional(),modified:O.string().optional(),fileSize:O.number().optional(),pagination:ck.optional(),next:lk.optional(),isPartial:O.boolean().optional(),startLine:O.number().optional(),endLine:O.number().optional(),matchRanges:O.array(O.object({start:O.number(),end:O.number()})).optional(),lastModified:O.string().optional(),lastModifiedBy:O.string().optional(),warnings:O.array(O.string()).optional(),matchNotFound:O.boolean().optional(),searchedFor:O.string().optional(),cached:O.boolean().optional()}),dk=O.object({path:O.string(),localPath:O.string(),repoRoot:O.string().optional(),fileCount:O.number(),totalSize:O.number(),complete:O.boolean().optional(),directoryEntryCount:O.number().optional(),eligibleFileCount:O.number().optional(),savedFileCount:O.number().optional(),skipped:O.object({nonFile:O.number(),missingDownloadUrl:O.number(),oversized:O.number(),binary:O.number(),fileLimit:O.number(),fetchFailed:O.number(),totalSizeLimit:O.number(),pathTraversal:O.number()}).optional(),limits:O.object({maxDirectoryFiles:O.number(),maxTotalSize:O.number(),maxFileSize:O.number()}).optional(),warnings:O.array(O.string()).optional(),files:O.array(O.object({path:O.string(),size:O.number(),type:O.string()})).optional(),cached:O.boolean().optional(),resolvedBranch:O.string().optional()}),Of={startLine:hr,endLine:hr,contextLines:fr,charOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional(),minify:ak},pk=Se(kf,Of),Fn=he(kf,Of),yo=fe(pk),GH=O.object({base:O.string().optional(),shared:O.record(O.string(),O.union([O.string(),O.number(),O.boolean()])).optional(),responsePagination:Ue.responsePagination,results:O.array(O.object({id:O.string(),data:O.object({owner:O.string(),repo:O.string(),files:O.array(uk).optional(),directories:O.array(dk).optional()}).optional()})),errors:O.array(O.object({id:O.string(),owner:O.string().optional(),repo:O.string().optional(),path:O.string().optional(),error:O.string()})).optional()})});import{z as Q}from"zod";import{GitHubCodeSearchQuerySchema as vf}from"@octocodeai/octocode-core/schemas";var Af,bo,Ro,mk,WH,Lf=f(()=>{"use strict";ae();Ze();et();it();Be();Af={limit:B(1,100).optional(),page:Re.default(1),match:Q.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghHistoryResearch, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},bo=he(vf,Af),Ro=fe(Se(vf,Af)),mk=tt.extend({totalMatchesKind:Q.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:Q.boolean().optional(),uniqueFileCount:Q.number().optional()}),WH=Q.object({base:Q.string().optional(),shared:Q.record(Q.string(),Q.union([Q.string(),Q.number(),Q.boolean()])).optional(),responsePagination:Ue.responsePagination,results:Q.array(Q.object({id:Q.string(),data:Q.object({files:Q.array(Q.union([Q.string(),Q.object({owner:Q.string(),repo:Q.string(),path:Q.string(),queryId:Q.string().optional(),matches:Q.array(Q.object({value:Q.string().optional(),pathOnly:Q.boolean().optional(),matchIndices:Q.array(Q.object({start:Q.number(),end:Q.number(),lineOffset:Q.number()})).optional(),url:Q.string().optional()}))})])),pagination:mk.optional()})})),emptyQueries:Q.array(Q.object({id:Q.string(),nonExistentScope:Q.literal(!0).optional(),incompleteResults:Q.literal(!0).optional()})).optional(),warnings:Q.array(Q.string()).optional(),diagnostics:Q.array(yr).optional(),next:Q.record(Q.string(),Pe).optional(),errors:Q.array(Q.object({id:Q.string(),error:Q.string()})).optional()})});import{z as $e}from"zod";import{GitHubPullRequestSearchQuerySchema as Ff}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as hk}from"@octocodeai/octocode-core/schemas/outputs";var If,gk,In,So,_f,rQ,vl=f(()=>{"use strict";ae();Ze();et();it();Be();If={type:$e.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),perPage:B(1,100).optional().default(30),prNumber:B(1,1e9).optional(),issueNumber:B(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:B(1,100).optional().default(30),match:$e.array($e.enum(["title","body","comments"])).optional().describe('Fields to match keywords against: "title", "body", "comments". Default searches all three. Use ["title"] for the most precise and fastest match. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)'),page:Re.default(1),filePage:Re.optional(),commentPage:Re.optional(),commitPage:Re.optional(),itemsPerPage:B(1,100).optional().default(20),charOffset:B(0,1e8).optional(),commentBodyOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional()},gk=Se(Ff,If),In=he(Ff,If),So=fe(gk),_f=$e.union([$e.string(),$e.object({}).passthrough()]),rQ=hk.extend({results:$e.array($e.object({id:$e.string().optional(),status:$e.string().optional(),data:$e.object({pull_requests:$e.array(_f).optional(),issues:$e.array(_f).optional(),next:$e.record($e.string(),Pe).optional()}).passthrough().optional()}).passthrough()).optional(),...Ue})});import{z as re}from"zod";import{GitHubReposSearchSingleQuerySchema as Mf}from"@octocodeai/octocode-core/schemas";var Df,Po,Co,yk,bk,Rk,pQ,Nf=f(()=>{"use strict";ae();Ze();et();it();Be();Df={limit:B(1,100).optional(),page:Re.default(1),match:re.array(re.enum(["name","description","readme"])).optional().describe("Which text fields to search: name, description, and/or readme. Defaults to name+description; add 'readme' for broader, slower full-text search. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)")},Po=he(Mf,Df),Co=fe(Se(Mf,Df)),yk=re.object({owner:re.string(),repo:re.string(),stars:re.number().optional(),forks:re.number().optional(),openIssuesCount:re.number().optional(),language:re.string().optional(),license:re.string().optional(),description:re.string().optional(),homepage:re.string().optional(),pushedAt:re.string().optional(),createdAt:re.string().optional(),defaultBranch:re.string().optional(),topics:re.array(re.string()).optional(),visibility:re.string().optional(),url:re.string().optional(),updatedAt:re.string().optional()}),bk=tt.extend({totalMatchesKind:re.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:re.boolean().optional()}).optional(),Rk=re.object({repositories:re.array(re.union([re.string(),yk])).optional(),pagination:bk}).passthrough(),pQ=re.object({results:re.array(re.object({id:re.string().optional(),status:re.string().optional(),data:Rk.optional()}).passthrough()).optional()}).extend(Ue)});import{GitHubViewRepoStructureQuerySchema as Gf}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as Pk}from"@octocodeai/octocode-core/schemas/outputs";var Hf,wo,To,PQ,Qf=f(()=>{"use strict";ae();ae();Ze();et();it();Hf={maxDepth:B(0,20).optional(),page:Re.default(1),itemsPerPage:B(1,200).optional()},wo=he(Gf,Hf),To=fe(Se(Gf,Hf)),PQ=Pk.extend(Ue)});import{z as Z}from"zod";import{NpmPackageQuerySchema as jf}from"@octocodeai/octocode-core/schemas";var Bf,Eo,ko,vQ,zf=f(()=>{"use strict";Ze();et();it();Be();Bf={page:Re,mode:Z.enum(["lean","full"]).optional(),keywords:Z.union([Z.string(),Z.array(Z.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},Eo=he(jf,Bf),ko=fe(Se(jf,Bf,{strict:!0}),{maxQueries:5}),vQ=Z.object({results:Z.array(Z.looseObject({id:Z.string(),data:Z.looseObject({packages:Z.array(Z.object({name:Z.string(),version:Z.string().optional(),description:Z.string().optional(),license:Z.string().optional(),downloads:Z.number().optional(),repository:Z.string().optional(),repositoryDirectory:Z.string().optional(),repositoryId:Z.string().optional(),next:Z.record(Z.string(),Pe).optional(),warnings:Z.array(Z.string()).optional(),diagnostics:Z.array(yr).optional()}).passthrough()).optional(),repositories:Z.record(Z.string(),Z.object({repository:Z.string(),owner:Z.string(),repo:Z.string(),repositoryDirectory:Z.string().optional(),next:Z.record(Z.string(),Pe)}).passthrough()).optional(),pagination:tt.optional()}).optional(),status:Z.string().optional()})).optional()}).extend(Ue)});import{z as oe}from"zod";import{FetchContentQuerySchema as Uf}from"@octocodeai/octocode-core/schemas";var Ck,$f,xk,Mn,Oo,wk,Tk,GQ,Al=f(()=>{"use strict";ae();Ze();et();it();Be();Ck=oe.enum(["none","standard","symbols"]).optional().default("standard"),$f={startLine:hr,endLine:hr,contextLines:fr.default(5),charOffset:B(0,1e8).optional(),charLength:B(1,5e4).optional(),minify:Ck},xk=Se(Uf,$f),Mn=he(Uf,$f),Oo=fe(xk,{maxQueries:5}),wk=oe.object({start:oe.number(),end:oe.number()}),Tk=oe.object({path:oe.string().optional(),content:oe.string().optional(),contentView:oe.enum(["none","standard","symbols"]).optional(),totalLines:oe.number().optional(),sourceChars:oe.number().optional(),sourceBytes:oe.number().optional(),startLine:oe.number().optional(),endLine:oe.number().optional(),isPartial:oe.boolean().optional(),matchRanges:oe.array(wk).optional(),pagination:oe.union([gr.extend({nextBlockChar:oe.number().optional()}),tt]).optional(),next:oe.record(oe.string(),Pe).optional(),modified:oe.string().optional(),lastModified:oe.string().optional(),lastModifiedBy:oe.string().optional(),warnings:oe.array(oe.string()).optional(),matchNotFound:oe.boolean().optional(),searchedFor:oe.string().optional()}),GQ=oe.object({results:oe.array(oe.object({id:oe.string(),status:oe.enum(["empty","error"]).optional(),data:Tk}))}).extend(sn)});import{z as ce}from"zod";import{FindFilesQuerySchema as Ek}from"@octocodeai/octocode-core/schemas";function kk(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 qf,Wf,Ok,Dn,vo,vk,Ak,WQ,_l=f(()=>{"use strict";ae();Ze();et();it();Be();qf={maxDepth:B(0,100).optional(),minDepth:B(0,100).optional(),limit:B(1,1e4).optional(),page:Re.default(1),itemsPerPage:B(1,50).optional(),excludeDir:ce.array(ce.string()).optional().describe('Directory names to prune from the walk (e.g. ["node_modules","dist","coverage"]). NOTHING is excluded by default \u2014 results include build output and vendor dirs unless you pass this explicitly.')},Wf=ce.object(Object.fromEntries(Object.entries(Ek.shape).filter(([e])=>e!=="regexType")));Ok=Se(Wf,qf),Dn=he(Wf,qf).superRefine(kk),vo=fe(Ok,{maxQueries:5}),vk=ce.object({name:ce.string().optional(),path:ce.string().optional(),type:ce.enum(["file","dir","directory","link","symlink"]).optional(),size:ce.union([ce.number(),ce.string()]).optional(),sizeFormatted:ce.string().optional(),modified:ce.string().optional(),accessed:ce.string().optional(),created:ce.string().optional(),permissions:ce.string().optional()}),Ak=ce.object({path:ce.string().optional(),files:ce.array(vk).optional(),summary:ce.string().optional(),pagination:on.optional(),next:ce.record(ce.string(),Pe).optional(),warnings:ce.array(ce.string()).optional()}),WQ=ce.object({results:ce.array(ce.object({id:ce.string(),status:ce.enum(["empty","error"]).optional(),data:Ak}))}).extend(sn)});import{z as F}from"zod";import{RipgrepQuerySchema as Vf}from"@octocodeai/octocode-core/schemas";var Lk,_k,Kf,Fk,Ik,Mk,jt,Ao,Dk,Nk,Gk,nj,Fs=f(()=>{"use strict";ae();Ze();et();it();Be();Lk=["paginated","discovery","detailed","structural"],_k=["semanticRanking"],Kf={mode:F.enum(Lk).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghHistoryResearch\'s `patches.mode` \u2014 different concepts sharing this name.)'),keywords:F.string().optional().describe("The search pattern (text or regex). Set fixedString:true for a literal match, or perlRegex:true for advanced regex features (lookaheads, backreferences). (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)"),filesOnly:F.boolean().optional().describe("Returns matching file paths without line content. Mutually exclusive with filesWithoutMatch. (Unlike localViewStructure's `filesOnly`, which filters a directory listing to file entries only \u2014 a different concept sharing this name.)"),pattern:F.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:F.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:fr,matchContentLength:B(1,1e5).optional().default(500),maxMatchesPerFile:B(1,1e5).optional(),maxFiles:B(1,1e5).optional(),matchPage:Re.optional(),itemsPerPage:B(1,1e3).optional(),page:Re.default(1),unique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:F.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},Fk={...Kf,semanticRanking:F.never().optional()},Ik=Se(Vf,Fk),Mk=he(Vf,Kf,{strict:!0,omit:_k}),jt=Mk.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),Ao=fe(Ik,{maxQueries:5}),Dk=F.object({line:F.number(),endLine:F.number().optional(),value:F.string().optional(),column:F.number().optional(),endColumn:F.number().optional(),count:F.number().optional(),kind:F.string().optional(),scoreHint:F.number().optional(),metavars:F.record(F.string(),F.array(F.string())).optional(),metavarRanges:F.record(F.string(),F.array(F.object({text:F.string(),line:F.number(),column:F.number(),endLine:F.number(),endColumn:F.number()}))).optional()}),Nk=F.object({path:F.string(),matches:F.array(Dk).optional(),totalOccurrences:F.number().optional(),totalMatchedLines:F.number().optional(),totalMatchRows:F.number().optional(),returnedMatchRows:F.number().optional(),ranking:F.object({score:F.number(),profile:F.string().optional(),pathRole:F.string().optional(),reasons:F.array(F.string()).optional()}).optional(),matchPagination:on.optional(),pagination:on.optional(),next:F.record(F.string(),Pe).optional()}),Gk=F.object({files:F.array(Nk).optional(),summary:F.string().optional(),searchEngine:F.string().optional(),stats:F.object({totalOccurrences:F.number().optional(),matchedLines:F.number().optional(),filesMatched:F.number().optional(),filesSearched:F.number().optional(),bytesSearched:F.number().optional(),searchTime:F.string().optional()}).passthrough().optional(),pagination:on.optional(),next:F.record(F.string(),Pe).optional(),warnings:F.array(F.string()).optional()}),nj=F.object({results:F.array(F.object({id:F.string(),status:F.enum(["empty","error"]).optional(),data:Gk}))}).extend(sn)});import{z as ee}from"zod";import{ViewStructureQuerySchema as Yf}from"@octocodeai/octocode-core/schemas";var Xf,Hk,Nn,Lo,Qk,jk,dj,Il=f(()=>{"use strict";ae();Ze();et();it();Be();Xf={maxDepth:B(0,20).optional(),limit:B(1,1e4).optional(),page:Re.default(1),itemsPerPage:B(1,50).optional(),filesOnly:ee.boolean().optional().describe("Returns files only. Mutually exclusive with directoriesOnly. (Unlike localSearchCode's `filesOnly`, which filters search results to matching file paths \u2014 a different concept sharing this name.)")},Hk=Se(Yf,Xf),Nn=he(Yf,Xf),Lo=fe(Hk,{maxQueries:5}),Qk=ee.object({name:ee.string().optional(),type:ee.enum(["file","dir","directory","link","symlink"]),path:ee.string().optional(),depth:ee.number().optional(),size:ee.union([ee.number(),ee.string()]).optional(),sizeBytes:ee.number().optional(),modified:ee.string().optional(),permissions:ee.string().optional()}),jk=ee.object({path:ee.string().optional(),entries:ee.array(Qk).optional(),files:ee.array(ee.string()).optional(),folders:ee.array(ee.string()).optional(),links:ee.array(ee.string()).optional(),summary:ee.union([ee.string(),ee.record(ee.string(),ee.unknown())]).optional(),pagination:on.optional(),next:ee.record(ee.string(),Pe).optional(),warnings:ee.array(ee.string()).optional()}),dj=ee.object({results:ee.array(ee.object({id:ee.string(),status:ee.enum(["empty","error"]).optional(),data:jk}))}).extend(sn)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as eh}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as Bk}from"@octocodeai/octocode-core/schemas/outputs";var zk,Uk,$k,th,qk,_o,Fo,Jf,Wk,Vk,Is,Ms,Kk,Yk,nh,Rr,Xk,Jk,Zk,rh,eO,tO,nO,rO,oO,iO,sO,Zf,Pj,oh=f(()=>{"use strict";ae();Ze();et();kt();Be();zk=B(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),Uk=B(0,1e5).optional(),$k=["structured","compact"],th={type:R.enum(Cf).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:R.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:zk.optional(),orderHint:Uk,depth:B(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:Re,itemsPerPage:B(1,100).optional(),contextLines:B(0,100).optional(),format:R.enum($k).optional().default("structured")},qk=Se(eh,th),_o=he(eh,th),Fo=fe(qk,{maxQueries:5}),Jf=R.object({line:R.number(),character:R.number()}),Wk=R.object({start:Jf,end:Jf}),Vk=R.object({startLine:R.number(),endLine:R.number()}),Is=R.object({uri:R.string(),content:R.string().optional(),displayRange:Vk.optional(),isDefinition:R.boolean().optional()}),Ms=R.string(),Kk=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),Yk=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),nh=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Rr=R.object({category:nh,reason:R.string()}),Xk=tt,Jk=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),Zk=R.string(),rh=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),eO=R.string(),tO=R.object({direction:R.enum(["incoming","outgoing"]),item:rh,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),nO=R.string(),rO=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),oO=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),iO=R.string(),sO=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Is,Ms]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Is,Ms]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Is,Ms]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Is,Ms])).optional(),byFile:R.array(R.union([oO,iO])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:Rr.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([rh,eO]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([tO,nO])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:rO,empty:Rr.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:Wk.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([Jk,Zk])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:Rr.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:Rr.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:Rr.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:Rr.optional()}),R.object({kind:R.literal("empty"),category:nh,reason:R.string()})]),Zf=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:Kk.optional(),lsp:Yk.optional(),payload:sO,pagination:Xk.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional(),next:R.record(R.string(),Pe).optional(),hints:R.array(R.string()).optional()}),Pj=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),responsePagination:gr.optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:Zf}),R.object({id:R.string().min(1),status:R.literal("error"),data:Bk}),R.object({id:R.string().min(1),data:Zf})]))})});var ln,Io,Ml,Dl,ih=f(()=>{"use strict";ln=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","diff","research","graph","materialize"],Io=["fixes","dataflow"],Ml=["packages","repositories"],Dl={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});function Nl(e){return Array.isArray(e.queries)}function Gl(e){return Array.isArray(e.queries)}function Hl(e){return Array.isArray(e.children)}var sh=f(()=>{"use strict"});var un=f(()=>{"use strict";ih();sh()});import{z as U}from"zod";var ah,ch,aO,cO,Gn,Ql,lO,uO,dn,lh=f(()=>{"use strict";ah=U.enum(["smart","sensitive","insensitive"]),ch=U.string().max(1e4),aO=U.strictObject({id:U.string().optional(),kind:U.literal("text"),value:ch,case:ah.optional(),wholeWord:U.boolean().optional()}),cO=U.strictObject({id:U.string().optional(),kind:U.literal("regex"),value:ch,dialect:U.enum(["rust","pcre2","provider"]).optional(),case:ah.optional(),wholeWord:U.boolean().optional(),multiline:U.boolean().optional(),dotAll:U.boolean().optional()}),Gn=U.lazy(()=>U.strictObject({pattern:U.string().optional(),kind:U.string().optional(),inside:Gn.optional(),has:Gn.optional(),not:Gn.optional(),all:U.array(Gn).optional(),any:U.array(Gn).optional(),stopBy:U.literal("end").optional()})),Ql=U.union([Gn,U.string().min(1)]),lO=U.strictObject({id:U.string().optional(),kind:U.literal("structural"),lang:U.string().min(1),pattern:U.string().optional(),rule:Ql.optional()}),uO=U.strictObject({id:U.string().optional(),kind:U.literal("field"),field:U.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:U.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:U.unknown().optional()}),dn=U.lazy(()=>U.discriminatedUnion("kind",[U.strictObject({kind:U.literal("all"),id:U.string().optional(),of:U.array(dn).min(1)}),U.strictObject({kind:U.literal("any"),id:U.string().optional(),of:U.array(dn).min(1)}),U.strictObject({kind:U.literal("not"),id:U.string().optional(),predicate:dn}),aO,cO,lO,uO]))});import{z as P}from"zod";var Bl,jl,dO,uh,dh,ph,mh,Ds,pO,Fj,fh,hh,gh,yh,Mo,bh,Rh,Hn,Sr=f(()=>{"use strict";un();lh();Bl=P.lazy(()=>P.union([P.strictObject({kind:P.literal("local"),path:P.string().min(1)}),P.strictObject({kind:P.literal("github"),repo:P.string().min(1).optional(),owner:P.string().min(1).optional(),ref:P.string().min(1).optional()}),P.strictObject({kind:P.literal("materialized"),localPath:P.string().min(1),source:Bl.optional()}),P.strictObject({kind:P.literal("npm")})])),jl=P.union([P.string(),P.array(P.string()).max(100)]),dO=P.strictObject({path:jl.optional(),language:jl.optional(),include:P.array(P.string()).max(100).optional(),exclude:P.array(P.string()).max(100).optional(),excludeDir:P.array(P.string()).max(100).optional(),hidden:P.boolean().optional(),noIgnore:P.boolean().optional(),minDepth:P.number().int().min(0).max(64).optional(),maxDepth:P.number().int().min(0).max(64).optional()}).optional(),uh=P.strictObject({mode:P.enum(["never","auto","required"]),strategy:P.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:P.boolean().optional(),forceRefresh:P.boolean().optional()}),dh=P.strictObject({content:P.strictObject({range:P.strictObject({startLine:P.number().int().min(1).optional(),endLine:P.number().int().min(1).optional(),contextLines:P.number().int().min(0).max(100).optional()}).optional(),match:P.strictObject({text:P.string(),regex:P.boolean().optional(),caseSensitive:P.boolean().optional()}).optional(),contentView:P.enum(["none","standard","symbols","exact","compact"]).transform(e=>e==="exact"?"none":e==="compact"?"standard":e).optional(),charOffset:P.number().int().min(0).max(1e8).optional(),charLength:P.number().int().min(1).max(5e4).optional(),fullContent:P.boolean().optional()}).optional(),tree:P.strictObject({maxDepth:P.number().int().min(0).max(64).optional(),pattern:P.string().optional(),includeSizes:P.boolean().optional(),extensions:P.array(P.string()).optional(),filesOnly:P.boolean().optional(),directoriesOnly:P.boolean().optional(),sortBy:P.enum(["name","size","time","extension"]).optional(),reverse:P.boolean().optional()}).optional()}),ph=P.strictObject({search:P.strictObject({countLinesPerFile:P.boolean().optional(),countMatchesPerFile:P.boolean().optional(),onlyMatching:P.boolean().optional(),unique:P.boolean().optional(),countUnique:P.boolean().optional(),contextLines:P.number().int().min(0).max(100).optional(),invertMatch:P.boolean().optional(),matchWindow:P.number().int().min(0).optional(),matchContentLength:P.number().int().min(1).optional(),maxMatchesPerFile:P.number().int().min(1).optional(),matchPage:P.number().int().min(1).optional(),sort:P.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:P.boolean().optional(),rankingProfile:P.string().optional(),debugRanking:P.boolean().optional()}).optional(),budget:P.strictObject({maxFiles:P.number().int().min(1).optional(),maxCandidates:P.number().int().min(1).optional(),maxBytes:P.number().int().min(1).optional(),maxMaterializedBytes:P.number().int().min(1).optional(),maxPlanNodes:P.number().int().min(1).optional(),maxBooleanExpansion:P.number().int().min(1).optional(),timeoutMs:P.number().int().min(1).optional()}).optional()}),mh=P.enum(["discovery","paginated","detailed"]),Ds=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),target:P.enum(ln),from:Bl.optional(),scope:dO,where:dn.optional(),materialize:uh.optional(),fetch:dh.optional(),select:P.array(P.string()).optional(),view:mh.optional(),controls:ph.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional()}),pO=P.strictObject({schema:P.literal("oql"),id:P.string().optional(),queries:P.array(Ds).min(1).max(5),combine:P.enum(["independent","merge"]).optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),explain:P.boolean().optional()}),Fj=P.union([Ds,pO]),fh=[...ln,...Io],hh={schema:P.literal("oql").optional(),id:P.string().optional(),mainResearchGoal:P.string().optional(),researchGoal:P.string().optional(),reasoning:P.string().optional()},gh={...hh,target:P.enum(fh).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Bl.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:dn.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:P.union([uh,P.enum(["never","auto","required"])]).optional(),fetch:dh.optional(),select:P.array(P.string()).optional(),view:mh.optional(),controls:ph.optional(),limit:P.number().int().min(1).optional(),page:P.number().int().min(1).optional(),itemsPerPage:P.number().int().min(1).optional(),params:P.record(P.string(),P.unknown()).optional(),explain:P.boolean().optional(),repo:P.string().optional(),owner:P.string().optional(),ref:P.string().optional(),path:jl.optional(),text:P.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:P.string().optional(),pattern:P.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:Ql.optional(),lang:P.string().optional(),and:P.array(P.unknown()).optional(),or:P.array(P.unknown()).optional(),xor:P.array(P.unknown()).optional(),noneOf:P.array(P.unknown()).optional(),oneOf:P.array(P.unknown()).optional(),invert:P.unknown().optional(),filesOnly:P.boolean().optional(),filesWithoutMatch:P.boolean().optional(),verbose:P.boolean().optional()},yh={...gh,target:P.enum(fh).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},Mo=P.object(yh).catchall(P.unknown()),bh=P.object(gh).catchall(P.unknown()),Rh=P.object({...hh,queries:P.array(P.unknown()).min(1)}).catchall(P.unknown()),Hn=P.object({...yh,queries:P.array(P.unknown()).min(1).max(5).optional(),combine:P.enum(["independent","merge"]).optional()}).catchall(P.unknown())});var zl=f(()=>{"use strict";Ef();Ol();Lf();vl();Nf();Qf();zf();Al();_l();Fs();Il();oh();Sr()});import{z as Sh}from"zod";function pn(e){return xh.find(t=>t.name===e)}function Pr(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===Y.PACKAGE_SEARCH?"Package":"Other"}function hO(e){return[...e].sort((t,n)=>{let r=Ul.indexOf(Pr(t)),o=Ul.indexOf(Pr(n));if(r!==o)return r-o;let i=Ph.get(t)??Number.MAX_SAFE_INTEGER,s=Ph.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function gO(e){let t=pn(e);if(!t)return"{}";try{return JSON.stringify(Sh.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Sh.toJSONSchema(t.schema,{io:"input"}),null,2)}}function yO(e){return JSON.stringify(e??{},null,2)}function bO(e){let t=Pr(e),n=[...fO];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function RO(){return Ch.map(e=>({...e}))}function SO(){return JSON.stringify(Object.fromEntries(Ch.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function PO(e,t){return t?.tools?.[e]?.description??e}var Ul,Ph,st,mO,Do,fO,Ch,xh,No=f(()=>{"use strict";fo();kt();zl();Ul=["GitHub","Local Code","Package","Other"],Ph=new Map([Y.GITHUB_SEARCH_CODE,Y.GITHUB_SEARCH_REPOSITORIES,Y.GITHUB_SEARCH_PULL_REQUESTS,Y.GITHUB_FETCH_CONTENT,Y.GITHUB_VIEW_REPO_STRUCTURE,Y.GITHUB_CLONE_REPO,Y.LOCAL_RIPGREP,Y.LOCAL_FIND_FILES,Y.LOCAL_FETCH_CONTENT,Y.LOCAL_VIEW_STRUCTURE,Ie,Y.PACKAGE_SEARCH,...mo()?[rn]:[]].map((e,t)=>[e,t])),st=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},mO=["id","mainResearchGoal","researchGoal","reasoning"],Do=new Set([...mO]),fO=["id","researchGoal","reasoning"],Ch=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],xh=[{name:Y.GITHUB_SEARCH_CODE,schema:bo,inputSchema:Ro},{name:Y.GITHUB_FETCH_CONTENT,schema:Fn,inputSchema:yo},{name:Y.GITHUB_VIEW_REPO_STRUCTURE,schema:wo,inputSchema:To},{name:Y.GITHUB_SEARCH_REPOSITORIES,schema:Po,inputSchema:Co},{name:Y.GITHUB_SEARCH_PULL_REQUESTS,schema:In,inputSchema:So},{name:Y.PACKAGE_SEARCH,schema:Eo,inputSchema:ko},{name:Y.GITHUB_CLONE_REPO,schema:br,inputSchema:ho},{name:Y.LOCAL_RIPGREP,schema:jt,inputSchema:Ao},{name:Y.LOCAL_VIEW_STRUCTURE,schema:Nn,inputSchema:Lo},{name:Y.LOCAL_FIND_FILES,schema:Dn,inputSchema:vo},{name:Y.LOCAL_FETCH_CONTENT,schema:Mn,inputSchema:Oo},{name:Ie,schema:_o,inputSchema:Fo},...mo()?[{name:rn,schema:Mo,inputSchema:Hn}]:[]]});import{z as CO}from"zod";function Go(e){let t=pn(e);if(!t)return[];let n=CO.toJSONSchema(t.schema,{io:"input"});if(!Cr(n))return[];let r=Bt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Do.has(i)&&!Wl(r[i])):[]);return ql(r,o)}function xO(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 $l(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Cr(e.items)?e.items:void 0;return`array<${n?$l(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Cr).map($l).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 ql(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Do.has(o))continue;let s=Cr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:$l(s),constraints:xO(s),description:typeof s.description=="string"?s.description:void 0}),Bt(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!Wl(s.properties?.[u]):!1):[]);r.push(...ql(s.properties,l,a))}let c=s.type==="array"&&Cr(s.items)?s.items:void 0;if(c&&Bt(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!Wl(c.properties?.[u]):!1):[]);r.push(...ql(c.properties,l,a))}}return r}function Th(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[wh(e,n)]}return wh(e,t)}function wh(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 Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cr(e){return Bt(e)}function Wl(e){return Cr(e)&&"default"in e}var Ns=f(()=>{"use strict";No()});function Eh(e){return e===rn?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===Y.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"2024-01-01T00:00:00Z",perPage:5}},{label:"releases + latest",query:{type:"releases",owner:"microsoft",repo:"TypeScript",perPage:5}},{label:"issues search",query:{type:"issues",owner:"microsoft",repo:"TypeScript",keywordsToSearch:["crash"],state:"open",concise:!0,limit:5}},{label:"issue detail",query:{type:"issues",owner:"bgauryy",repo:"octocode",issueNumber:443,content:{body:!0,comments:{discussion:!0}}}}]:e===Y.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===Y.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===Y.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===Y.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===Y.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",keywords:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===Y.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===Y.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===Y.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,filesOnly:!0,itemsPerPage:100}}]:e===Ie?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}var kh=f(()=>{"use strict";fo()});function Oh(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function wO(e){let t=Eh(e);if(t.length>0)return t.map(r=>({...r,command:Oh(e,r.query)}));let n=EO(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:Oh(e,n)}]}function TO(e){return wO(e)[0]?.query??{}}function EO(e){if(!pn(e))return{};let t=Go(e),n=t.filter(i=>!i.name.includes(".")),r=kO(n),o={};for(let i of r)o[i.name]=Th(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Ie&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function kO(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&&OO(i)).sort(vO),o=Math.max(vh,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=>!Ah.has(i.name)).filter(i=>i.type!=="boolean").slice(0,vh)}function OO(e){return Ah.has(e.name)||e.type==="boolean"?!1:AO(e)?Vl.has(e.name):!0}function vO(e,t){let n=Vl.get(e.name)??Number.MAX_SAFE_INTEGER,r=Vl.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function AO(e){return e.constraints?.includes("default ")===!0}var vh,Vl,Ah,Lh=f(()=>{"use strict";kt();No();kh();Ns();vh=4,Vl=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]]),Ah=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});function LO(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new st("Tool input must be valid JSON.")}return _h(e,r,n)}function _h(e,t,n={}){let r=FO(e,t,n),o=pn(e);if(!o)throw new st(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new st("Tool input does not match the expected schema.",_O(i.error));return i.data}function _O(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function FO(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(Bt(t)&&Array.isArray(t.queries))r=t.queries;else if(Bt(t))r=[t];else throw new st('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new st("At least one query is required.");let o=Bt(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>IO(e,a,QO(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function IO(e,t,n,r){let o={...n},i=Pr(e),s=r.sourceLabel??"direct tool execution",a=MO(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function MO(e,t){return`Execute ${e} via ${t}`}function DO(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 NO(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=DO(n,c);if(c.includes(n)||n.includes(c)){l<o&&(r=a,o=l);continue}if(n.length<3)continue;let u=Math.max(2,Math.floor(a.length/3));l<=u&&l<s&&(i=a,s=l)}return r??i}function HO(e,t){let n=GO[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n))o in t&&!(i in t)&&(r??={...t},r[i]=r[o],delete r[o]);return r??t}function QO(e,t,n,r={}){if(!Bt(t))throw new st("Tool input must be a JSON object or an array of objects.");let o=HO(e,t),i=new Set([...Go(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Do]),s={},a=[];for(let[c,l]of Object.entries(o)){if(i.has(c)){s[c]=l;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(l=>{let u=NO(l,i);return u?`'${l}' \u2192 did you mean '${u}'?`:""}).filter(Boolean);throw new st(`Unknown field(s): ${a.join(", ")}`,[...c,`Remove unknown field(s) from query ${n+1}: ${a.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return s}var GO,Fh=f(()=>{"use strict";No();Ns();GO={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"keywords"}}});var Kl=f(()=>{"use strict";No();Ns();Lh();Fh()});function mn(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function xr(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 Gs(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Hs=f(()=>{"use strict"});function BO(e){let t=mn(e),n=Ho.get(t);return!n||Date.now()-n.cachedAt>=jO?!1:n.credentials?!xr(n.credentials):!0}function Yl(e){e?Ho.delete(mn(e)):Ho.clear()}function Ih(e){let t=mn(e);if(BO(t))return Ho.get(t).credentials}function Mh(e,t){let n=mn(e);Ho.set(n,{credentials:t,cachedAt:Date.now()})}var Ho,jO,Dh=f(()=>{"use strict";Hs();Ho=new Map,jO=300*1e3});import{existsSync as zO,mkdirSync as UO}from"node:fs";import{join as St}from"node:path";import{getOctocodeHome as $O}from"@octocodeai/config";function WO(){return $O(process.env)}function wr(){return nt}function Nh(){zO(zt.home)||UO(zt.home,{recursive:!0,mode:qO})}var qO,nt,zt,Qs=f(()=>{"use strict";qO=448;nt=WO(),zt={home:nt,config:St(nt,".octocoderc"),credentials:St(nt,"credentials.json"),key:St(nt,".key"),session:St(nt,"session.json"),stats:St(nt,"stats.json"),tmp:St(nt,"tmp"),clone:St(nt,"tmp","clone"),tree:St(nt,"tmp","tree"),repos:St(nt,"tmp","clone"),cliConfig:St(nt,"config.json"),lspConfig:St(nt,"lsp-servers.json")}});import{z as Me}from"zod";var VO,KO,Gh,Hh=f(()=>{"use strict";VO=Me.object({token:Me.string(),tokenType:Me.literal("oauth"),scopes:Me.array(Me.string()).optional(),refreshToken:Me.string().optional(),expiresAt:Me.string().optional(),refreshTokenExpiresAt:Me.string().optional()}),KO=Me.object({hostname:Me.string(),username:Me.string(),token:VO,gitProtocol:Me.enum(["ssh","https"]),createdAt:Me.string(),updatedAt:Me.string()}),Gh=Me.object({version:Me.number(),credentials:Me.record(Me.string(),KO)})});import{existsSync as Qh,readFileSync as jh,writeFileSync as Bh,unlinkSync as OB,statSync as YO,chmodSync as XO}from"node:fs";import{createCipheriv as JO,createDecipheriv as ZO,randomBytes as zh}from"node:crypto";function jn(){Nh()}function qh(){if(jn(),Qh(Qn))return YO(Qn).mode&511&63&&XO(Qn,384),Buffer.from(jh(Qn,"utf8"),"hex");let e=zh(32);return Bh(Qn,e.toString("hex"),{mode:384}),e}function Xl(e){let t=qh(),n=zh(ev),r=JO($h,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 Jl(e){let t=qh(),[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=ZO($h,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function js(){if(jn(),!Qh(Qo))return{version:1,credentials:{}};try{let e=jh(Qo,"utf8"),t=Jl(e),n=JSON.parse(t),r=Gh.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Wh(e){jn();let t=Xl(JSON.stringify(e,null,2));Bh(Qo,t,{mode:384})}var Uh,Qo,Qn,$h,ev,Vh=f(()=>{"use strict";Qs();Hh();Uh=zt.home,Qo=zt.credentials,Qn=zt.key,$h="aes-256-gcm",ev=16});var jo,Tr,Zl=f(()=>{"use strict";jo="178c6fc778ccc68e1d6a",Tr="github.com"});import{refreshToken as tv}from"@octokit/oauth-methods";import{request as nv}from"@octokit/request";function rv(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 ov(e){return e==="github.com"||e===Tr?"https://api.github.com":`https://${e}/api/v3`}async function Kh(e,t=Tr,n=jo){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(Gs(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await tv({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:nv.defaults({baseUrl:ov(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?rv(o.message):"Token refresh failed"}}}async function Yh(e,t=Tr,n=jo){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!xr(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Kh(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var Xh=f(()=>{"use strict";Hs();Zl()});import{execFile as iv}from"child_process";function eu(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=sv.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;iv("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var sv,tu=f(()=>{"use strict";sv=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});import{resolveEnvToken as av}from"@octocodeai/config";function Jh(e){nu=e}function cv(){if(!nu)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return nu}async function Bs(e){let t=e?.hostname??Tr,n=e?.clientId??jo,r=e?.getGhCliToken??eu,o=av();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await cv().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)}
9
+ `)}return null}var nu,Zh=f(()=>{"use strict";tu();Zl();nu=null});async function eg(e){let t=mn(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=js();return r.credentials[t]=n,Wh(r),Yl(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function ru(e="github.com",t){let n=mn(e);if(!t?.bypassCache){let i=Ih(n);if(i!==void 0)return i}let o=js().credentials[n]||null;return Mh(n,o),o}async function tg(e,t){let n=await ru(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await eg(n),!0):!1}async function ng(e,t){return Yh({getCredentials:ru,updateToken:tg},e,t)}var ou=f(()=>{"use strict";Dh();Vh();Xh();Zh();Hs();Jh({getTokenWithRefresh:ng})});var rg=f(()=>{"use strict";ou();tu()});import zs from"node:os";import hz from"node:path";var pv,mv,fv,hv,og=f(()=>{"use strict";pv=zs.platform()==="win32",mv=zs.platform()==="darwin",fv=zs.platform()==="linux",hv=zs.homedir()});var ig=f(()=>{"use strict";og()});import{z as X}from"zod";var gv,yv,Us,bv,$s,sg,ag,cg=f(()=>{"use strict";gv=X.object({rawChars:X.number(),responseChars:X.number(),savedChars:X.number(),calls:X.number()}),yv=X.object({hits:X.record(X.string(),X.number()).default({}),rateLimits:X.number().default(0)}),Us=X.record(X.string(),X.number()).default({}),bv=X.object({toolCalls:X.number(),errors:X.number(),rateLimits:X.number(),rateLimitsByProvider:Us,rawChars:X.number(),responseChars:X.number(),savedChars:X.number(),charSavingsCalls:X.number(),githubCacheHits:X.number(),githubCacheRateLimits:X.number(),packageRegistryFailures:X.number().default(0),packageRegistryFailuresByRegistry:Us}),$s=X.object({toolCalls:X.number(),errors:X.number(),rateLimits:X.number(),rateLimitsByProvider:Us,charsSavedByTool:X.record(X.string(),gv).default({}),githubCacheHits:yv.default({hits:{},rateLimits:0}),packageRegistryFailures:Us,totalUsage:bv.optional()}),sg=X.object({version:X.literal(1),sessionId:X.string(),createdAt:X.string(),lastActiveAt:X.string(),stats:$s.optional()}),ag=X.object({version:X.literal(1),stats:$s})});function lg(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Rv(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:lg(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:lg(o),packageRegistryFailuresByRegistry:o}}function fn(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Rv(t)}}function Er(){return fn({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var iu=f(()=>{"use strict"});import{existsSync as dg,readFileSync as pg,writeFileSync as Sv,unlinkSync as kz,renameSync as Pv}from"node:fs";import{isStatsEnabled as mg}from"@octocodeai/config";function ug(e,t){let n=`${e}.tmp`;Sv(n,JSON.stringify(t,null,2),{mode:384}),Pv(n,e)}function Cv(e){let t=JSON.parse(e),n=ag.safeParse(t);if(n.success)return fn(n.data.stats);let r=$s.safeParse(t);return r.success?fn(r.data):null}function xv(){if(!dg(zo))return Er();try{let e=pg(zo,"utf8");return Cv(e)??Er()}catch{return Er()}}function su(e){jn(),mg()&&ug(zo,{version:e.version,stats:fn(e.stats)});let{stats:t,...n}=e;ug(Bo,n)}function fg(){if(!dg(Bo))return null;try{let e=pg(Bo,"utf8"),t=JSON.parse(e),n=sg.safeParse(t);return n.success?{...n.data,stats:mg()?xv():Er()}:null}catch{return null}}var Bo,zo,qs=f(()=>{"use strict";ou();Qs();cg();iu();Bo=zt.session,zo=zt.stats});function Tv(){hg||(hg=!0,gg=()=>{Ws()},yg=()=>{Ws()},bg=()=>{Ws()},process.on("exit",gg),process.on("SIGINT",yg),process.on("SIGTERM",bg))}function Ev(){au||(au=setInterval(()=>{Uo&&hn&&(su(hn),Uo=!1)},wv),au.unref())}function Rg(){if(hn)return hn;let e=fg();return e&&(hn=e),e}function Sg(e){hn=e,Uo=!0,Tv(),Ev()}function Ws(){if(!cu&&Uo&&hn){cu=!0;try{su(hn),Uo=!1}catch{}finally{cu=!1}}}var wv,hn,Uo,au,hg,gg,yg,bg,cu,Pg=f(()=>{"use strict";qs();wv=6e4,hn=null,Uo=!1,au=null,hg=!1,gg=null,yg=null,bg=null,cu=!1});import{randomUUID as zz}from"node:crypto";function kv(e){return fn(e)}function Ov(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 Cg(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 vv(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 gn(e){let t=Rg();if(!t)return{success:!1,session:null};let n=kv(t.stats),r=fn({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Cg(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Ov(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:vv(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Cg(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Sg(o),{success:!0,session:o}}function lu(e=1){return gn({rateLimits:e})}function uu(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return gn({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function du(e,t=1){return gn({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function pu(e=1){return gn({githubCacheHits:{hits:{},rateLimits:e}})}var $o=f(()=>{"use strict";qs();iu();Pg();qs()});var xg=f(()=>{"use strict";$o();$o();$o();$o()});import{z as Ce}from"zod";var Av,wg=f(()=>{"use strict";Av=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{setRuntimeSurface as bU,invalidateConfigCache as RU}from"@octocodeai/config";var Tg=f(()=>{"use strict";wg()});import{existsSync as Lv,readdirSync as _v,lstatSync as Fv}from"node:fs";import{join as Iv}from"node:path";function Vs(e){if(!Lv(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=_v(r)}catch{continue}for(let i of o){let s=Iv(r,i);try{let a=Fv(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var Eg=f(()=>{"use strict"});var Ot=f(()=>{"use strict";rg();ig();xg();Tg();Qs();Eg()});var Bn,Ks=f(()=>{Bn="17.0.2"});var mu,qo,Wo,Dv,yn,bn,qe,Nv,Vo,Gv,LU,at=f(()=>{"use strict";mu={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},qo={PROMISES_NOT_ARRAY:{code:"VALIDATION_PROMISES_NOT_ARRAY",message:"promises must be an array"},TIMEOUT_NOT_POSITIVE:{code:"VALIDATION_TIMEOUT_NOT_POSITIVE",message:"timeout must be positive"},CONCURRENCY_NOT_POSITIVE:{code:"VALIDATION_CONCURRENCY_NOT_POSITIVE",message:"concurrency must be positive"}},Wo={FETCH_NOT_AVAILABLE:{code:"FETCH_NOT_AVAILABLE",message:"Global fetch is not available in this environment."},FETCH_FAILED_AFTER_RETRIES:{code:"FETCH_FAILED_AFTER_RETRIES",message:(e,t)=>`Failed to fetch after ${e} attempts: ${t}`},FETCH_HTTP_ERROR:{code:"FETCH_HTTP_ERROR",message:(e,t)=>`Failed to fetch (${e} ${t})`}},Dv={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"}},yn={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}`}},bn={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"}},qe={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}`}},Nv={NO_TOOLS_REGISTERED:{code:"STARTUP_NO_TOOLS_REGISTERED",message:"No tools were successfully registered"},UNCAUGHT_EXCEPTION:{code:"STARTUP_UNCAUGHT_EXCEPTION",message:e=>`Uncaught exception: ${e}`},UNHANDLED_REJECTION:{code:"STARTUP_UNHANDLED_REJECTION",message:e=>`Unhandled rejection: ${e}`},STARTUP_FAILED:{code:"STARTUP_FAILED",message:e=>`Startup failed: ${e}`}},Vo={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Gv={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}`}},LU={...mu,...qo,...Wo,...Dv,...yn,...bn,...qe,...Nv,...Vo,...Gv}});import{getConfigSync as kg,invalidateConfigCache as MU}from"@octocodeai/config";import{maskSensitiveData as Hv}from"@octocodeai/octocode-engine/mask";async function Og(){try{let e=await Qv({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:jv.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function vg(){if(Yo!==null)return;if(Ko!==null)return Ko;let e=(async()=>{let t=kg(),n=await Og();Yo={version:Bn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Ko=e;try{await e}catch(t){throw Ko===e&&(Yo=null,Ko=null),t}}function fu(){if(!Yo){let e=Hv(mu.NOT_INITIALIZED.message);throw new Error(e)}return Yo}async function hu(){return(await Og()).token}function gu(){return"github"}function yu(){let e=kg().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var Yo,Ko,Qv,jv,Xo=f(()=>{"use strict";Ot();Ks();at();Yo=null,Ko=null,Qv=Bs,jv=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});import{createRequire as Bv}from"node:module";function se(){if(Ys)return Ys;try{return Ys=Uv(),Ys}catch(e){throw new bu(e)}}var zv,Ag,Ys,Uv,bu,D,Ee=f(()=>{"use strict";zv=Bv(import.meta.url),Ag="@octocodeai/octocode-engine",Uv=()=>zv(Ag),bu=class extends Error{constructor(n){super(`Failed to load native dependency ${Ag}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return se().applyContentViewMinification(e,t)},applyMinification(e,t){return se().applyMinification(e,t)},minifyContent(e,t){return se().minifyContent(e,t)},minifyContentSync(e,t){return se().minifyContentSync(e,t)},minifyContentResult(e,t){return se().minifyContentResult(e,t)},minifyMarkdownCore(e){return se().minifyMarkdownCore(e)},extractSignatures(e,t){return se().extractSignatures(e,t)},extractJsSymbols(e,t){return se().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return se().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return se().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return se().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return se().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return se().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return se().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return se().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return se().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return se().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return se().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return se().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return se().parseRipgrepJson(e,t)},searchRipgrep(e){return se().searchRipgrep(e)},queryFileSystem(e){return se().queryFileSystem(e)},extractMatchingLines(e,t,n){return se().extractMatchingLines(e,t,n)},filterPatch(e,t){return se().filterPatch(e,t)},computeLineDiff(e,t){return se().computeLineDiff(e,t)},charToByteOffset(e,t){return se().charToByteOffset(e,t)},byteToCharOffset(e,t){return se().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return se().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return se().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return se().SIGNATURES_ONLY_HINT}}});function Rn(e){(e.provider?gn({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):lu(1)).session&&e.provider==="github"&&pu(1)}function Lg(e){gn({packageRegistryFailures:{[e]:1}})}var Xs=f(()=>{"use strict";Ot()});import{Octokit as $v}from"octokit";import{throttling as qv}from"@octokit/plugin-throttling";import{createHash as Wv}from"crypto";function Dg(e){return Wv("sha256").update(e).digest("hex").substring(0,16)}async function He(e){let t=e?.token??await hu(),n=t?Dg(t):"anon",r=fu().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}function Ng(e){return Date.now()-e.createdAt>Kv}function Gg(){for(let[e,t]of Ut.entries())Ng(t)&&Ut.delete(e);if(Ut.size>Ru){let e=Ut.size-Ru,t=0;for(let[n]of Ut){if(t>=e)break;Ut.delete(n),t++}}}function Xv(){Jo||(Jo=setInterval(Gg,Yv),typeof Jo=="object"&&"unref"in Jo&&Jo.unref())}function Ig(e,t,n){Rn({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function Zv(e){let t=fu(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Bn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:Jv(),log:r,...e&&{auth:e}};return new Vv(o)}async function ie(e){Xv();let t=e?.token??await hu(),n=t?Dg(t):"ANONYMOUS",r=Ut.get(n);if(r&&!Ng(r))return r.client;Ut.size>=Ru&&Gg();let o=Zv(t??void 0);return Ut.set(n,{client:o,createdAt:Date.now()}),o}async function We(e,t,n){let r=`${e}/${t}`,o=Zo.get(r);if(o)return o;let i=await ie(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Mg(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),Mg(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Mg(e,t){if(Zo.size>=eA){let n=Zo.keys().next().value;n!==void 0&&Zo.delete(n)}Zo.set(e,t)}var Vv,Kv,Ru,Yv,Ut,Jo,_g,Fg,Jv,eA,Zo,Ae=f(()=>{"use strict";Xo();Xo();Ks();Xs();Vv=$v.plugin(qv),Kv=300*1e3,Ru=50,Yv=60*1e3;Ut=new Map,Jo=null;_g=3,Fg=60;Jv=()=>({onRateLimit:(e,t,n,r)=>(Ig("primary",e,t),r<_g&&e<Fg),onSecondaryRateLimit:(e,t,n,r)=>(Ig("secondary",e,t),r<_g&&e<Fg)});eA=200,Zo=new Map});var V,Le,Hg,Su,Pu,Js,Qg=f(()=>{"use strict";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"},Le={[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."}},Hg={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},Su={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},Pu={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Js={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as jg}from"octokit";function vt(e){if(!(e instanceof jg)||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 tA.some(o=>r.includes(o))})}function ne(e){return e instanceof jg?nA(e):e instanceof Error?uA(e):{error:typeof e=="string"?e:Le[V.UNKNOWN].message,type:"unknown"}}function nA(e){let{status:t,message:n,response:r}=e;if(t===403)return oA(n,r);if(t===429)return rA(n,r);let o=Hg[t];return o?lA(o,t):kr(V.UNKNOWN,{error:n||Le[V.UNKNOWN].message,status:t})}function Cu(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function rA(e,t){let n=t?.headers,r=Cu(n,"retry-after"),o=Cu(n,"x-ratelimit-reset"),i=Cu(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Js.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"}),kr(V.RATE_LIMIT_PRIMARY,{error:e||Le[V.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Le[V.RATE_LIMIT_PRIMARY].suggestion})}function oA(e,t){let n=t?.headers;if(Pu.SECONDARY.test(e))return iA(n);let r=n?.["x-ratelimit-remaining"],o=cA(t);return r!==void 0&&String(r)==="0"||o?sA(n):aA(n)}function iA(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Js.SECONDARY_FALLBACK_SECONDS:t;return Rn({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),kr(V.RATE_LIMIT_SECONDARY,{error:Le[V.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Le[V.RATE_LIMIT_SECONDARY].suggestion})}function sA(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)+Js.RESET_BUFFER_SECONDS,0):void 0,i=r?Le[V.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Le[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"}),kr(V.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Le[V.RATE_LIMIT_PRIMARY].suggestion})}function aA(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Le[V.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=dA(String(t),String(n))),kr(V.FORBIDDEN_PERMISSIONS,{error:Le[V.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function cA(e){return e?.data?.errors?.some(n=>n.type===Pu.GRAPHQL_TYPE)??!1}function lA(e,t){let n=Le[e];return kr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function uA(e){return Su.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Le[V.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Le[V.NETWORK_CONNECTION_FAILED].suggestion}:Su.TIMEOUT.some(t=>e.message.includes(t))?{error:Le[V.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Le[V.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function kr(e,t){return{type:"http",...t}}function dA(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?Le[V.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Le[V.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var tA,rt=f(()=>{"use strict";Qg();Xs();tA=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function Bg(e){return`user:${e}`}function xu(e){return e.startsWith('"')||mA.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var pA,mA,$t,ei=f(()=>{"use strict";pA=/[@/]/,mA=/^[A-Za-z0-9_-]+$/;$t=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(Bg(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=pA.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}}});function Eu(e){return new wu().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ku(e){return new Tu().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var fA,wu,Tu,zg=f(()=>{"use strict";ei();fA=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,wu=class extends $t{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(xu))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(fA):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}},Tu=class extends $t{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(xu)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}}});function vu(e){return new Ou().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Au(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Ou,Ug=f(()=>{"use strict";ei();Ou=class extends $t{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});function _u(e){return new Lu().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Fu(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Lu,$g=f(()=>{"use strict";ei();Lu=class extends $t{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}}});var Or=f(()=>{"use strict";ei();zg();Ug();$g()});import hA from"crypto";function bA(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(yA.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function ke(e,t,n){let r=Iu(bA(t)),o=n?`${n}:${r}`:r,i=hA.createHash("sha256").update(o).digest("hex");return`${gA}-${e}:${i}`}function Iu(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=>Iu(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Iu(i,t)}`}).join(",")}}`)}var gA,yA,qg=f(()=>{"use strict";gA="v2",yA=new Set([])});import RA from"node-cache";function PA(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function CA(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function ti(e){let t=PA(e);if(!(!t||!CA(t)))try{du(t,1)}catch{}}function Zs(){let e=Date.now();for(let[t,n]of Ct.entries())e-n.startedAt>SA&&Ct.delete(t)}function ni(e){return Wg[e]||Wg.default}function ri(e,t,n){try{return Pt.set(e,t,n),ct.sets++,ct.totalKeys=Pt.keys().length,!0}catch{try{let r=Pt.keys();for(let o of r)Pt.get(o);return Pt.set(e,t,n),ct.sets++,ct.totalKeys=Pt.keys().length,!0}catch{return!1}}}var SA,Pt,ct,Wg,Ct,ea=f(()=>{"use strict";Ot();SA=300*1e3,Pt=new RA({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ct={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Wg={"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});async function Qe(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Pt.get(e);if(i!==void 0)return ct.hits++,ti(e),i}catch{}Zs();let r=Ct.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ct.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=ni(l)}ri(e,i,a)}return i}finally{Ct.delete(e)}})();return Ct.set(e,{promise:o,startedAt:Date.now()}),o}var Vg=f(()=>{"use strict";ea()});import xA from"node-cache";async function ta(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Pt.get(e);if(i!==void 0)return ct.hits++,ti(e),i}catch{}Zs();let r=Ct.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:Mu.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ct.hits++,ti(e);let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=ni(u)}return ri(e,i.data,c),i.data}if(n.forceRefresh||ct.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=ni(u)}ri(e,s.value,c),Mu.set(e,{data:s.value,etag:s.etag})}return s.value}finally{Ct.delete(e)}})();return Ct.set(e,{promise:o,startedAt:Date.now()}),o}var Mu,Du=f(()=>{"use strict";ea();Mu=new xA({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1})});var Kg=f(()=>{"use strict";ea();Du()});var lt=f(()=>{"use strict";qg();Vg();Du();Kg()});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as M$,DISCOVERY_IGNORED_FILE_NAMES as D$,DISCOVERY_IGNORED_FOLDER_NAMES as N$,getDiscoveryExtension as Yg,shouldIgnoreDiscoveryDir as oi,shouldIgnoreDiscoveryFile as vr}from"@octocodeai/octocode-engine/security";var ii=f(()=>{"use strict"});function j(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Jg(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function W(e,t){let n=typeof t=="number"?Jg(t):j(t);if(n===void 0)return e;try{Object.defineProperty(e,Xg,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function le(e){if(!(typeof e!="object"||e===null))return Jg(e[Xg])}var Xg,ue=f(()=>{"use strict";Xg=Symbol.for("octocode.rawResponseChars")});function si(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 Ar(e){let t=si(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}var Lr=f(()=>{"use strict"});import{ContentSanitizer as wA}from"@octocodeai/octocode-engine/contentSanitizer";async function ey(e,t,n){let r=await He(t),o=ke("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 Qe(o,async()=>await TA(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function TA(e,t){try{let n=await ie(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(b=>b&&b.trim()).length===0)return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let r=Eu(e);if(!r.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Zg,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 EA(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),h=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:h,...h?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:si(a.headers),rawResponseChars:j(a.data)}}catch(n){if(vt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Zg,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 ne(n)}}async function EA(e,t){let n=kA(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!vr(p.path)),c=0,l=0,u=await Promise.allSettled(a.map(async p=>{s.add(p.path);let h=[],g=await Promise.allSettled((p.text_matches||[]).map(async k=>{let E=k.fragment,_=wA.sanitizeContent(E||"",p.path);E=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(w=>r.add(`${p.path}: ${w}`));try{let w=await D.minifyContent(E||"",p.path);E=w.content,w.failed?o=!0:w.type!=="failed"&&(h.push(w.type),i.push(w.type))}catch{o=!0}return{context:E||"",positions:k.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),y=g.filter(k=>k.status==="fulfilled").map(k=>k.value),b=g.filter(k=>k.status==="rejected").length;b>0&&(l+=b);let S=p,x=Array.from(new Set(h));return{path:p.path,matches:y,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...x.length>0&&{minificationType:x.join(",")}}})),d=u.filter(p=>p.status==="fulfilled").map(p=>p.value);c=u.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function kA(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 Zg,ty=f(()=>{"use strict";Ee();Ae();rt();Or();lt();ii();at();ue();Lr();ae();Zg=30});function ry(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 oy(e,t,n){let r=await He(t),o=e,i=ke("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await Qe(i,async()=>await vA(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function OA(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){if(p?.status!==404)return ne(p);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return ne(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),y=g[0]||"",b=g[1]||"";return{owner:y,repo:b,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...ry(p)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),m=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:m,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:j(i)}}async function vA(e,t){try{let n=await ie(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await OA({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=ku(e);if(!i.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||ny,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let k=S.full_name.split("/"),E=k[0]||"",_=k[1]||"";return{owner:E,repo:_,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...ry(S)}}),m=u.data.total_count,p=Math.min(m,1e3),h=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,h)),y=g<h,b=Math.min(p,h*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:h,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:b,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:y,...y?{nextPage:g+1}:{}}},status:200,headers:si(u.headers),rawResponseChars:j(u.data)}}catch(n){if(vt(n)){let r=Math.min(e.limit||ny,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 ne(n)}}var ny,iy=f(()=>{"use strict";Ae();rt();Or();lt();at();ue();Lr();ae();ny=30});function At(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var _r=f(()=>{"use strict"});function _e(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 AA(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 qt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:AA(e)}}function na(e){return LA(e)?qt({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 LA(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||_A(n)}function _A(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var Lt=f(()=>{"use strict"});function ai(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}var Nu=f(()=>{"use strict"});function FA(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,...ai(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function IA(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,...ai(e.pagination)},nonExistentScope:e.nonExistentScope}}async function sy(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await ey(s,t);return At(a)?qt(a):a.data?{data:FA(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function ay(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await oy(n,t);return"error"in r?na(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:IA(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??j(r.data)}}var cy=f(()=>{"use strict";ty();iy();_r();ue();Lt();Lt();Nu()});import{completeMetadata as Gu}from"@octocodeai/octocode-core";var v,ly=f(()=>{"use strict";v=new Proxy({},{get(e,t){return Gu.toolNames[t]},ownKeys(){return Object.keys(Gu.toolNames)},getOwnPropertyDescriptor(e,t){let n=Gu.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as Hu}from"@octocodeai/octocode-core";function ra(e=Hu){if(Qu&&e===Hu)return Qu;let t=e,n=t.tools?.localFindFiles;n?.description&&uy.test(n.description)&&(t={...t,tools:{...t.tools,localFindFiles:{...n,description:n.description.replace(uy,DA)}}});let r=t.tools?.ghHistoryResearch;return r?.description&&dy.test(r.description)&&(t={...t,tools:{...t.tools,ghHistoryResearch:{...r,description:r.description.replace(dy,NA)}}}),e===Hu&&(Qu=t),t}var uy,DA,dy,NA,Qu,ju=f(()=>{"use strict";uy=/Default excludeDir skips common generated\/vendor dirs; pass \[\] to search all\./,DA='Nothing is excluded by default \u2014 pass excludeDir (e.g. ["node_modules","dist","coverage"]) to prune build/vendor dirs.',dy=/type:"prs" searches PRs; add prNumber to read selected content\. type:"commits" reads owner\/repo\/path history\./,NA='type:"prs" searches PRs; add prNumber to read selected content. type:"commits" reads owner/repo/path history. type:"issues" searches or reads GitHub issues; add issueNumber to read a specific issue (body + comments). type:"releases" lists repo releases.',Qu=null});var Bu,py=f(()=>{"use strict";ju();Bu=new Proxy({},{get(e,t){return ra().tools[t]?.description??""}})});import{completeMetadata as GA}from"@octocodeai/octocode-core";function zu(e){return Object.prototype.hasOwnProperty.call(GA.tools,e)}var my=f(()=>{"use strict"});import{completeMetadata as HA}from"@octocodeai/octocode-core";function Uu(){return HA.baseSchema}var QA,fy=f(()=>{"use strict";QA=new Proxy({},{get(e,t){return Uu()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Uu())]))},getOwnPropertyDescriptor(e,t){let n=Uu();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var pe=f(()=>{"use strict";ly();py();my();fy()});function $u(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function qu(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(p=>p.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>l.push(p.path)),l.length===0&&d.length>=3&&c.filter(h=>{let g=h.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(h=>l.push(h.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var hy=f(()=>{"use strict"});import{RequestError as Wu}from"octokit";async function jA(e,t,n,r,o,i,s,a){let c=await We(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=ne(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await qu(e,r,o,i,s||c);return m.length>0&&(u.hints=[...u.hints||[],...$u(i,m)]),{...u,...d&&{scopesSuggestion:d}}}async function BA(e,t,n,r,o,i){let s=ne(t),a=await qu(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...$u(o,a)]),s}async function gy(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:yn.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:yn.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:yn.DECODE_FAILED.message,type:"unknown",status:422}}}async function yy(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"?gy(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return ne(i)}}async function zA(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 We(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(m=>m.name===a&&m.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await yy(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return ne(s)}}async function ci(e,t,n={}){try{let r=await ie(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},l,u=a;try{l=await r.rest.repos.getContent(c)}catch(p){if(p instanceof Wu&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof Wu&&p.status===404)if(a){let h=await jA(r,p,c,o,i,s,a,t);if("result"in h)l=h.result,u=h.actualBranch;else return h}else return await BA(r,p,o,i,s,a);else{if(p instanceof Wu&&p.status===413)return await zA(r,o,i,s,a||u,t);throw p}}let d=l.data,m=Ar(l.headers);if(Array.isArray(d))return{error:yn.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",h=d.size??0,g;if(p.length>0)g=await gy(p,s);else if(h>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await yy(r,o,i,d.sha,s);else return{error:yn.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!u&&!a)try{u=await We(o,i,t)}catch{}return{data:{rawContent:g.data,branch:u||void 0,resolvedRef:u||a||"HEAD"},status:200,rawResponseChars:j(d),...m?{etag:m}:{}}}return{error:yn.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return ne(r)}}var by=f(()=>{"use strict";Ae();rt();pe();at();ue();Lr();hy()});var Vu=f(()=>{"use strict";by()});function li(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function _t(e){return li(e).length}var Fr=f(()=>{"use strict"});function oa(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(`
10
+ `),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 Ku=f(()=>{"use strict";Ee()});function $A(e){return UA.test(e.split(/[?#]/,1)[0]??e)}function Ry(e,t){return $A(t)?WA(qA(e)):null}function ia(e,t){let n=Ry(e,t);if(n===null||n.length===0)return null;let r=[];return Py(n,r),r.join(`
11
+ `)}function Sy(e,t){let n=Ry(e,t);return n===null?null:n.map(Cy)}function qA(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 WA(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 Py(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}`),Py(n.children,t)}}function Cy(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(Cy)}}var UA,sa=f(()=>{"use strict";UA=/\.(?:md|markdown|mdx)$/i});import{getConfigSync as VA,DEFAULT_OUTPUT_CONFIG as KA}from"@octocodeai/config";function zn(){try{return VA().output.pagination.defaultCharLength}catch{return KA.pagination.defaultCharLength}}var aa=f(()=>{"use strict"});function Yu(e,t){return D.byteToCharOffset(e,t)}function xy(e,t){return D.charToByteOffset(e,t)}function wy(e){return D.charToByteOffset(e,e.length)}function Xu(e,t,n,r){return D.sliceContent(e,t,n,r)}var Ty=f(()=>{"use strict";Ee()});function ca(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=wy(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,m,p,h,g;if(o==="bytes"){let y=Math.min(t,s),b=Math.min(y+n,s);d=Yu(e,y),m=Yu(e,b),m<i&&xy(e,m)<b&&(m+=1);let S=Xu(e,d,m-d);c=S.text,d=S.charOffset,m=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,p=u<s;let x=r.actualOffset??y;h=Math.floor(x/a)+1,g=Math.max(h,Math.ceil(s/a))}else{let y=Xu(e,t,n);c=y.text,d=y.charOffset,m=y.charOffset+y.charLength,l=y.byteOffset,u=y.byteOffset+y.byteLength,p=m<i;let b=r.actualOffset??d;h=Math.floor(b/a)+1,g=Math.max(h,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:p?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:h,totalPages:g}}function Ju(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 Zu=f(()=>{"use strict";Ty()});function JA(e){return e&&e.trim().length>0?e:XA}async function Ey(e,t){return(await D.getSemanticBoundaryOffsets(e,JA(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function ZA(e,t){let n=e.indexOf(`
12
12
  `,t);return n===-1?void 0:n+1}function la(e){let t=e.trimEnd().split(`
13
- `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function ua(e,t,n){let r=XA(e,Math.max(0,t));return r===void 0?void 0:(await Ey(e,n)).find(i=>i>=r&&i>t)}async function da(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=await Ey(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=VA?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var VA,KA,ed=f(()=>{"use strict";Ee();VA=8e3,KA="__octocode_generic__.unknown"});function ZA(){let e=zn();return Math.min(e,8e3)}async function td(e,t,n){let r=e.content??"",o=n??ZA();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await da(r,t,o,i),c=ca(r,t,s,{pageSize:o}),l;if(c.hasMore&&a==="char-limit"&&la(c.paginatedContent)){let u=c.charOffset+c.charLength;l=await ua(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function nd(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}var ky=f(()=>{"use strict";aa();ae();Zu();ed()});import{ContentSanitizer as rd}from"@octocodeai/octocode-engine/contentSanitizer";function li(e,t){return{sourceChars:e,sourceBytes:t}}async function Oy(e,t,n,r,o,i,s,a,c=5,l,u,d,m="standard"){let p=e.length,h=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",y=g?"standard":"none",b;if(m==="symbols"){let K=D.extractSignatures(e,o);if(K===null){let I=ia(e,o);if(I!==null){let ye=rd.sanitizeContent(I,o),Te=[D.SIGNATURES_ONLY_HINT];return ye.hasSecrets&&Te.push(`Secrets detected and redacted: ${ye.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ye.content,contentView:"symbols",branch:r,totalLines:_t(e),...li(p,h),isPartial:!1,signaturesExtracted:!0,hints:Te}}b=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(K!==null){let I=rd.sanitizeContent(K,o),ye=D.applyContentViewMinification(I.content,o),Te=[D.SIGNATURES_ONLY_HINT];return l&&Te.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),I.hasSecrets&&Te.push(`Secrets detected and redacted: ${I.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ye,contentView:"symbols",branch:r,totalLines:_t(e),...li(p,h),isPartial:!1,signaturesExtracted:!0,hints:Te}}}let S=new Set,x=e,k=x.split(`
14
- `),E=_t(x),_=e,w,G,M=!1,A;if(i)_=e;else if(l){let K=d===!0,I;try{I=oa(k,l,c,u??!1,K)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...li(p,h),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(I.matchCount===0){let Os=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${K?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${K?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...li(p,h),matchNotFound:!0,searchedFor:l,hints:Os}}_=I.lines.join(`
15
- `);let ye=I.matchRanges[0],Te=I.matchRanges[I.matchRanges.length-1];s=ye.start,a=Te.end,w=ye.start,G=Te.end,M=!0,I.matchRanges.length>1&&(A=I.matchRanges);let nn=I.matchingLines.slice(0,5).join(", "),lo=I.matchingLines.length>5?` and ${I.matchingLines.length-5} more`:"";S.add(I.matchCount>1?`Found ${I.matchCount} occurrences of "${l}" on lines ${nn}${lo} \u2014 all shown as ${I.matchRanges.length} slice${I.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${I.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let K=s||1,I=a||E;if(K<1||K>E)_=e,S.add(`Requested startLine ${K} is out of range for this ${E}-line file \u2014 returning the full file instead of a range.`);else if(I<K)_=e,S.add(`Requested range startLine=${K}, endLine=${I} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let ye=Math.max(1,K),Te=Math.min(E,I),nn=k.slice(ye-1,Te);w=ye,G=Te,M=!0,_=nn.join(`
16
- `),I>E&&S.add(`Requested endLine ${I} adjusted to ${E} (file end)`)}}let q=rd.sanitizeContent(_,o);if(_=g?D.applyContentViewMinification(q.content,o):q.content,q.hasSecrets&&S.add(`Secrets detected and redacted: ${q.secretsDetected.join(", ")}`),q.warnings.length>0&&q.warnings.forEach(K=>S.add(K)),E>2e3&&m!=="symbols"&&!l&&!s&&!a&&!i){let K=Math.max(1,E-200);S.add(`Large file (${E} lines) \u2014 minify:"symbols" for an export index, or startLine=${K} for the tail.`)}let H=Array.from(S);return{owner:t,repo:n,path:o,content:_,contentView:y,branch:r,totalLines:E,...li(p,h),...M&&{startLine:w,endLine:G,isPartial:M},...A&&{matchRanges:A},...H.length>0&&{matchLocations:H},...(H.length>0||b)&&{warnings:[...b?[b]:[],...H]}}}var vy=f(()=>{"use strict";Ee();_r();Ku();sa();ky()});async function Ay(e,t,n){let r=await He(t),o=ke("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await ta(o,async({ifNoneMatch:g})=>{let y=await ai(e,t,{ifNoneMatch:g}),{etag:b,notModified:S,...x}=y;return{value:x,etag:b,notModified:S}},{shouldCache:g=>"data"in g&&!g.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await Oy(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...l}=a,u=e.charOffset??0,d=e.charLength,m=e.fullContent===!0&&u===0&&d===void 0,p=c||m?l:await td(l,u,d),h=(e.charOffset??0)>0;if(!e.noTimestamp&&!h)try{let g=await ie(t),y=await Qe(ke("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>nd(g,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});y&&(p.lastModified=y.lastModified,p.lastModifiedBy=y.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:i.rawResponseChars}}var Ly=f(()=>{"use strict";Ae();lt();Vu();vy()});function eL(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:tL(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function tL(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function _y(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ay(i,t);if(At(s))return qt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:eL(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s.data),...a?.length?{hints:a}:{}}}var Fy=f(()=>{"use strict";Ly();Lr();ue();Lt();Lt()});function ui(e,t=oL){let n=e?ci(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Iy(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function My(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:rL}):""}var rL,oL,pa=f(()=>{"use strict";Ee();_r();rL=2,oL=20});import{ContentSanitizer as Dy}from"@octocodeai/octocode-engine/contentSanitizer";function od(e){let t=Dy.sanitizeContent(e.title??""),n=e.body?Dy.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function Gy(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function Fr(e,t={}){let n=t.charOffset??0,r=t.charLength??iL,o=t.charLength??sL,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=Gy(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((h,g)=>{let y=h.commentType==="review_inline"?0:1,b=g.commentType==="review_inline"?0:1;return y-b}),c=a.filter(h=>h.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Ny),d=u.map(h=>{let g=Gy(h.body,n,o,!t.includeFullCommentDetails);return{...h,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>u.length||d.some(h=>"body_pagination"in h)),p=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...m?[`PR comments are paginated/summarized to ${Ny} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(h=>({id:0,name:h,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((h,g)=>h+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((h,g)=>h+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(h=>({filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,patch:h.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function di(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function pi(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?Iy(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?My(a.patch):a.patch}))}var iL,sL,Ny,Ir=f(()=>{"use strict";pa();Ee();aa();iL=zn(),sL=Math.round(zn()/4),Ny=3});function Mr(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Hy(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function ma(e){let t=Hy(e);return t?t.discussion!==!1:!1}function fa(e){let t=Hy(e);return t?t.reviewInline!==!1:!1}function ha(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function ga(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function id(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:Mr(e)||ma(e)||fa(e)||ha(e)||ga(e)}function sd(e){return!!e.content?.comments?.includeBots}function ya(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
13
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function ua(e,t,n){let r=ZA(e,Math.max(0,t));return r===void 0?void 0:(await Ey(e,n)).find(i=>i>=r&&i>t)}async function da(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=await Ey(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=YA?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var YA,XA,ed=f(()=>{"use strict";Ee();YA=8e3,XA="__octocode_generic__.unknown"});function tL(){let e=zn();return Math.min(e,8e3)}async function td(e,t,n){let r=e.content??"",o=n??tL();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await da(r,t,o,i),c=ca(r,t,s,{pageSize:o}),l;if(c.hasMore&&a==="char-limit"&&la(c.paginatedContent)){let u=c.charOffset+c.charLength;l=await ua(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function nd(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}var ky=f(()=>{"use strict";aa();ae();Zu();ed()});import{ContentSanitizer as rd}from"@octocodeai/octocode-engine/contentSanitizer";function ui(e,t){return{sourceChars:e,sourceBytes:t}}async function Oy(e,t,n,r,o,i,s,a,c=5,l,u,d,m="standard"){let p=e.length,h=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",y=g?"standard":"none",b;if(m==="symbols"){let K=D.extractSignatures(e,o);if(K===null){let I=ia(e,o);if(I!==null){let ye=rd.sanitizeContent(I,o),Te=[D.SIGNATURES_ONLY_HINT];return ye.hasSecrets&&Te.push(`Secrets detected and redacted: ${ye.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ye.content,contentView:"symbols",branch:r,totalLines:_t(e),...ui(p,h),isPartial:!1,signaturesExtracted:!0,hints:Te}}b=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(K!==null){let I=rd.sanitizeContent(K,o),ye=D.applyContentViewMinification(I.content,o),Te=[D.SIGNATURES_ONLY_HINT];return l&&Te.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),I.hasSecrets&&Te.push(`Secrets detected and redacted: ${I.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:ye,contentView:"symbols",branch:r,totalLines:_t(e),...ui(p,h),isPartial:!1,signaturesExtracted:!0,hints:Te}}}let S=new Set,x=e,k=x.split(`
14
+ `),E=_t(x),_=e,w,G,M=!1,A;if(i)_=e;else if(l){let K=d===!0,I;try{I=oa(k,l,c,u??!1,K)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...ui(p,h),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(I.matchCount===0){let vs=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${K?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${K?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...ui(p,h),matchNotFound:!0,searchedFor:l,hints:vs}}_=I.lines.join(`
15
+ `);let ye=I.matchRanges[0],Te=I.matchRanges[I.matchRanges.length-1];s=ye.start,a=Te.end,w=ye.start,G=Te.end,M=!0,I.matchRanges.length>1&&(A=I.matchRanges);let nn=I.matchingLines.slice(0,5).join(", "),uo=I.matchingLines.length>5?` and ${I.matchingLines.length-5} more`:"";S.add(I.matchCount>1?`Found ${I.matchCount} occurrences of "${l}" on lines ${nn}${uo} \u2014 all shown as ${I.matchRanges.length} slice${I.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${I.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let K=s||1,I=a||E;if(K<1||K>E)_=e,S.add(`Requested startLine ${K} is out of range for this ${E}-line file \u2014 returning the full file instead of a range.`);else if(I<K)_=e,S.add(`Requested range startLine=${K}, endLine=${I} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let ye=Math.max(1,K),Te=Math.min(E,I),nn=k.slice(ye-1,Te);w=ye,G=Te,M=!0,_=nn.join(`
16
+ `),I>E&&S.add(`Requested endLine ${I} adjusted to ${E} (file end)`)}}let q=rd.sanitizeContent(_,o);if(_=g?D.applyContentViewMinification(q.content,o):q.content,q.hasSecrets&&S.add(`Secrets detected and redacted: ${q.secretsDetected.join(", ")}`),q.warnings.length>0&&q.warnings.forEach(K=>S.add(K)),E>2e3&&m!=="symbols"&&!l&&!s&&!a&&!i){let K=Math.max(1,E-200);S.add(`Large file (${E} lines) \u2014 minify:"symbols" for an export index, or startLine=${K} for the tail.`)}let H=Array.from(S);return{owner:t,repo:n,path:o,content:_,contentView:y,branch:r,totalLines:E,...ui(p,h),...M&&{startLine:w,endLine:G,isPartial:M},...A&&{matchRanges:A},...H.length>0&&{matchLocations:H},...(H.length>0||b)&&{warnings:[...b?[b]:[],...H]}}}var vy=f(()=>{"use strict";Ee();Fr();Ku();sa();ky()});async function Ay(e,t,n){let r=await He(t),o=ke("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await ta(o,async({ifNoneMatch:g})=>{let y=await ci(e,t,{ifNoneMatch:g}),{etag:b,notModified:S,...x}=y;return{value:x,etag:b,notModified:S}},{shouldCache:g=>"data"in g&&!g.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await Oy(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...l}=a,u=e.charOffset??0,d=e.charLength,m=e.fullContent===!0&&u===0&&d===void 0,p=c||m?l:await td(l,u,d),h=(e.charOffset??0)>0;if(!e.noTimestamp&&!h)try{let g=await ie(t),y=await Qe(ke("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>nd(g,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});y&&(p.lastModified=y.lastModified,p.lastModifiedBy=y.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:i.rawResponseChars}}var Ly=f(()=>{"use strict";Ae();lt();Vu();vy()});function nL(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:rL(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function rL(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function _y(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ay(i,t);if(At(s))return qt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:nL(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s.data),...a?.length?{hints:a}:{}}}var Fy=f(()=>{"use strict";Ly();_r();ue();Lt();Lt()});function di(e,t=sL){let n=e?li(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Iy(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function My(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:iL}):""}var iL,sL,pa=f(()=>{"use strict";Ee();Fr();iL=2,sL=20});import{ContentSanitizer as Dy}from"@octocodeai/octocode-engine/contentSanitizer";function od(e){let t=Dy.sanitizeContent(e.title??""),n=e.body?Dy.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function Gy(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function Ir(e,t={}){let n=t.charOffset??0,r=t.charLength??aL,o=t.charLength??cL,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=Gy(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((h,g)=>{let y=h.commentType==="review_inline"?0:1,b=g.commentType==="review_inline"?0:1;return y-b}),c=a.filter(h=>h.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Ny),d=u.map(h=>{let g=Gy(h.body,n,o,!t.includeFullCommentDetails);return{...h,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>u.length||d.some(h=>"body_pagination"in h)),p=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...m?[`PR comments are paginated/summarized to ${Ny} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(h=>({id:0,name:h,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((h,g)=>h+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((h,g)=>h+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(h=>({filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,patch:h.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function pi(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function mi(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?Iy(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?My(a.patch):a.patch}))}var aL,cL,Ny,Mr=f(()=>{"use strict";pa();Ee();aa();aL=zn(),cL=Math.round(zn()/4),Ny=3});function Dr(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Hy(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function ma(e){let t=Hy(e);return t?t.discussion!==!1:!1}function fa(e){let t=Hy(e);return t?t.reviewInline!==!1:!1}function ha(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function ga(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function id(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:Dr(e)||ma(e)||fa(e)||ha(e)||ga(e)}function sd(e){return!!e.content?.comments?.includeBots}function ya(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
17
17
 
18
- `).trim()}var ba=f(()=>{"use strict"});function Un(e){let t=e.toLowerCase();return t.endsWith("[bot]")||aL.has(t)}var aL,Ra=f(()=>{"use strict";aL=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});async function Sa(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=j(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function ad(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Sa(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return W({total_count:i.length,files:i},s)}async function cL(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Sa(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return W(i,s)}async function lL(e,t,n,r){try{let i=await(await ie(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return W(i.data.files||[],i.data)}catch{return null}}async function dL(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)break;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function cd(e,t,n,r,o){let i=await cL(e,t,n,o);if(!i)return null;let s=le(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await dL(a,uL,async l=>{let u=await lL(e,t,l.sha,o),d=[];return u&&(s+=le(u)??0,d=pi(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}});return W(c,s)}var uL,ld=f(()=>{"use strict";Ae();Ir();ue();uL=5});import{ContentSanitizer as ud}from"@octocodeai/octocode-engine/contentSanitizer";async function dd(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=j(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!Un(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(ya(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:ud.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return u>0&&m.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:W(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:W([],0)}}}async function pd(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Sa(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return W(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:ud.sanitizeContent(D.minifyMarkdownCore(ya(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return W([],0)}}async function md(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=j(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!Un(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(ya(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:ud.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return u>0&&m.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:W(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:W([],0)}}}var Qy=f(()=>{"use strict";Ee();Ra();ue();ba();ld()});async function fd(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=od(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&id(t))try{let{owner:l,repo:u}=di(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=j(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Mr(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Mr(t))){let m=await ad(l,u,e.number);m&&(s+=le(m)??0,m.files=pi(m.files,t),o.file_changes=m)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=ma(t),c=fa(t);if(a||c){let{owner:l,repo:u}=di(t);if(l&&u){let d=sd(t),m=()=>Promise.resolve({comments:W([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([a?dd(n,l,u,e.number,d):m(),c?md(n,l,u,e.number,d):m()]);o.comments=[...p,...g],s+=(le(p)??0)+(le(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(ga(t))try{let{owner:l,repo:u}=di(t);if(l&&u){let d=await pd(n,l,u,e.number);s+=le(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(ha(t))try{let{owner:l,repo:u}=di(t);if(l&&u){let d=await cd(l,u,e.number,t);d&&(s+=le(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return W(o,s)}async function mi(e,t,n,r){let{prData:o,sanitizationWarnings:i}=od(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Mr(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Mr(t))try{let d=await ad(a,c,e.number,r);d&&(s+=le(d)??0,d.files=pi(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=ma(t),u=fa(t);if(l||u){let d=sd(t),m=()=>Promise.resolve({comments:W([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([l?dd(n,a,c,e.number,d):m(),u?md(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(le(p)??0)+(le(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(ga(t))try{let d=await pd(n,a,c,e.number);s+=le(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(ha(t))try{let d=await cd(a,c,e.number,t,r);d&&(s+=le(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return W(o,s)}var jy=f(()=>{"use strict";Ir();ue();ba();Qy();ld()});var Pa=f(()=>{"use strict";ba();jy()});function pL(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function By(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:qe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:qe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ie(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await mi(a,e,i,t);return{pull_requests:[Fr(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:j(s.data)+(le(c)??0)}}catch(i){let s=ne(i);return pL(s,qe.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var zy=f(()=>{"use strict";at();Ae();rt();lt();Ir();Pa();ue()});function hd(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function gd(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Uy(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await mi(m,t,e))),c=a.reduce((m,p)=>m+(le(p)??0),0),l=a.map(m=>Fr(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:j(s.data)+c}}catch(n){if(vt(n))return gd(t);let r=ne(n);return hd(r,qe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var $y=f(()=>{"use strict";ae();at();rt();ue();Ir();Pa()});async function mL(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function fL(e,t,n="anon"){return ke("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function qy(e,t,n){let r=await He(t),o=fL(e,n,r);return await Qe(o,async()=>await hL(e,t,n),{shouldCache:s=>!s.error})}async function hL(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await By(e,t);let r=await ie(t);if(!Au(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Uy(r,e);let i=await mL(r,e),s=vu(i);if(!s)return{pull_requests:[],total_count:0,error:qe.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),m=d.data.items?.filter(_=>!!_.pull_request)||[],p=await Promise.all(m.map(async _=>await fd(_,i,r))),h=p.reduce((_,w)=>_+(le(w)??0),0),g=p.map(_=>Fr(_,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),y=d.data.total_count,b=Math.min(y,1e3),S=Math.min(Math.ceil(b/c),10),x=Math.min(l,Math.max(1,S)),k=x<S,E=Math.min(b,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:x,totalPages:S,perPage:c,totalMatches:b,reportedTotalMatches:y,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:y>b,hasMore:k,...k?{nextPage:x+1}:{}},rawResponseChars:j(d.data)+h}}catch(r){if(vt(r))return gd(e);let o=ne(r);return hd(o,qe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var Wy=f(()=>{"use strict";ae();at();Ae();rt();kr();lt();ue();Ir();Pa();zy();$y()});function gL(e,t,n=_e){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...si(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Vy(e,t,n=_e){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await qy(s,t);return a.error?qt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:gL(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a)}}var Ky=f(()=>{"use strict";Wy();ue();Lt();Lt();Nu()});var Sn,fi=f(()=>{"use strict";Sn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function Ca(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var yd=f(()=>{"use strict"});function Yy(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:M,...A}=e;return A}let r=t.itemsPerPage??Sn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,m=M=>{let A=M;d&&M.startsWith(d)&&(A=M.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let q=A.lastIndexOf("/");return q===-1?".":A.slice(0,q)},p=M=>{let A=M.lastIndexOf("/");return A===-1?M:M.slice(A+1)};for(let M of l){let A=m(M.path);u[A]||(u[A]={files:[],folders:[]});let q=p(M.path);M.type==="file"?u[A].files.push(q):u[A].folders.push(q)}for(let M of Object.keys(u)){let A=u[M];A&&(A.files.sort(),A.folders.sort())}let h=Object.create(null),g=Object.keys(u).sort((M,A)=>M==="."?-1:A==="."?1:M.localeCompare(A));for(let M of g){let A=u[M];A&&(h[M]=A)}let y=l.filter(M=>M.type==="file").length,b=l.filter(M=>M.type==="dir").length,S=n.filter(M=>M.type==="file").length,x=n.filter(M=>M.type==="dir").length,k=o<s,E={currentPage:o,totalPages:s,hasMore:k,...k?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=Ca(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:y,pageFolders:b,allFiles:S,allFolders:x}),w,G=e._cachedFileSizeMap;if(G){let M=new Set(l.filter(H=>H.type==="file").map(H=>H.path)),A=e.path==="/"?"":e.path,q=Object.create(null);for(let[H,K]of Object.entries(G))for(let[I,ye]of Object.entries(K)){let Te=H==="."?A?`${A}/${I}`:I:A?`${A}/${H}/${I}`:`${H}/${I}`;M.has(Te)&&(q[H]||(q[H]=Object.create(null)),q[H][I]=ye)}Object.keys(q).length>0&&(w=q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:x,truncated:k,filtered:!0,originalCount:i},structure:h,...w!==void 0&&{fileSizeMap:w},...G!==void 0&&{_cachedFileSizeMap:G},pagination:E,hints:_,rawResponseChars:e.rawResponseChars}}var Xy=f(()=>{"use strict";fi();yd()});import{RequestError as bL}from"octokit";function Jy(e){return e instanceof bL&&RL.has(e.status)}function bd(e,t){try{Object.defineProperty(e,Zy,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function hi(e){if(typeof e!="object"||e===null)return 0;let t=e[Zy];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function gi(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return bd(W([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(h){if(Jy(h))throw h;return bd(W([],0),1)}let l=j(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(h=>h.type==="file"||h.type==="dir").map(h=>({name:h.name,path:h.path,type:h.type,size:"size"in h?h.size:void 0,download_url:"download_url"in h?h.download_url:void 0,url:h.url,html_url:h.html_url,git_url:h.git_url,sha:h.sha})),m=[...d],p=0;if(i<s){let h=d.filter(y=>y.type==="dir"),g=3;for(let y=0;y<h.length;y+=g){let b=h.slice(y,y+g),S=await Promise.allSettled(b.map(x=>gi(e,t,n,r,x.path,i+1,s,a)));for(let x of S)if(x.status==="fulfilled"){let k=x.value;l+=le(k)??0,p+=hi(k),m.push(...k)}else{if(Jy(x.reason))throw x.reason;p+=1}}}return bd(W(m,l),p)}var Zy,RL,eb=f(()=>{"use strict";ue();Zy=Symbol.for("octocode.recursiveFetchFailures"),RL=new Set([401,403,429])});import{RequestError as SL}from"octokit";function PL(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let l=a.lastIndexOf("/"),u=l===-1?a:a.slice(l+1);i.push({name:u,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function tb(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function nb(e,t){let{data:n}=await e.rest.repos.getBranch({owner:t.owner,repo:t.repo,branch:t.workingBranch}),r=n.commit.commit.tree.sha;if(!r)throw new Error(`Could not resolve tree SHA for ${t.owner}/${t.repo}@${t.workingBranch}`);let o;try{o=await e.rest.git.getTree({owner:t.owner,repo:t.repo,tree_sha:r,recursive:"true",...t.ifNoneMatch?{headers:{"If-None-Match":t.ifNoneMatch}}:{}})}catch(c){if(c instanceof SL&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=vr(o.headers);return{items:PL(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:j(n)+j(i),...s?{etag:s}:{}}}var rb=f(()=>{"use strict";ue();Ar()});import{RequestError as ob}from"octokit";async function Rd(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await We(t,n,i),a=c)}catch(l){let u=ne(l);return{error:bn.NOT_FOUND.message(t,n,u.error),status:u.status}}try{let l=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),u=vr(l.headers);return{data:l.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...u?{etag:u}:{}}}catch(l){if(l instanceof ob&&l.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(l instanceof ob&&l.status===404)){let d=ne(l);return{error:bn.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let u=ne(l);return{error:bn.PATH_NOT_FOUND.message(r,t,n,a),status:u.status}}}function ib(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}var sb=f(()=>{"use strict";rt();at();Ae();Ar()});function CL(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function ab(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}function xa(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:l,includeSizes:u,extraHints:d=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!ri(I.name):!Or(I.path));m.sort((I,ye)=>{if(I.type!==ye.type)return I.type==="dir"?-1:1;let Te=I.path.split("/").length,nn=ye.path.split("/").length;return Te!==nn?Te-nn:I.path.localeCompare(ye.path)});let p=e.itemsPerPage??Sn.ENTRIES_PER_PAGE,h=e.page??1,g=m.length,y=Math.max(1,Math.ceil(g/p)),b=(h-1)*p,S=Math.min(b+p,g),x=m.slice(b,S),k=CL(x,i),E=u?ab(m,i):void 0,_=E!==void 0?ab(x,i):void 0,w=x.filter(I=>I.type==="file").length,G=x.filter(I=>I.type==="dir").length,M=m.filter(I=>I.type==="file").length,A=m.filter(I=>I.type==="dir").length,q=h<y,H={currentPage:h,totalPages:y,hasMore:q,...q?{nextPage:h+1}:{},entriesPerPage:p,totalEntries:g},K=Ca(H,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:w,pageFolders:G,allFiles:M,allFolders:A});a>0&&K.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let I of d)K.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:M,totalFolders:A,truncated:q,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:k,..._!==void 0&&{fileSizeMap:_},...E!==void 0&&{_cachedFileSizeMap:E},pagination:H,hints:K,rawResponseChars:l,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}var cb=f(()=>{"use strict";fi();yd();oi()});async function Sd(e,t,n){let r=await He(t),o=ke("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await ta(o,async({ifNoneMatch:s})=>{let a=await xL({...e,itemsPerPage:e.itemsPerPage??Sn.ENTRIES_PER_PAGE,page:e.page??1},t,s);return{value:a.result,etag:a.etag,notModified:a.notModified}},{shouldCache:s=>!("error"in s)});return!("error"in i)&&i.structure?Yy(i,e):i}async function xL(e,t,n){try{let r=await ie(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,l=a.replace(/^\/+|\/+$/g,"");if(c>1&&tb())return await wL(r,e,l,c,t,n);let u=await Rd(r,o,i,l,s,t,c===1?n:void 0);if("error"in u)return{result:u};if(u.notModified)return{result:{error:"not-modified",status:304},etag:u.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:h}=u,g=j(d),y=Array.isArray(d)?d:[d],b=ib(y),S=0;if(c>1){let x=await gi(r,o,i,m,l,1,c);S=hi(x),g=le(x)??0,b=x}return{result:xa({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:l,depth:c,allItems:b,partialTreeFailures:S,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&h?{etag:h}:{}}}catch(r){let o=ne(r);return{result:{error:bn.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function wL(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,l,u;try{c?l=c:(u=await We(s,a,o),l=u)}catch(b){let S=ne(b);return{result:{error:bn.NOT_FOUND.message(s,a,S.error),status:S.status}}}let d;try{d=await nb(e,{owner:s,repo:a,workingBranch:l,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(b){let S=await Rd(e,s,a,n,l,o);if("error"in S)return{result:S};let x=await gi(e,s,a,S.workingBranch,n,1,r);return{result:xa({owner:s,repo:a,workingBranch:S.workingBranch,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:x,partialTreeFailures:hi(x),incompleteTree:!1,rawResponseChars:le(x)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${b instanceof Error?b.message:String(b)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,h=d.rawResponseChars,g=d.truncated,y=[];if(g){y.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let b=await gi(e,s,a,l,n,1,r);p=hi(b),h+=le(b)??0,m=[...m,...b].filter((x,k,E)=>E.findIndex(_=>_.path===x.path)===k)}catch{}}return{result:xa({owner:s,repo:a,workingBranch:l,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:h,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:y}),...d.etag&&!g?{etag:d.etag}:{}}}var lb=f(()=>{"use strict";fi();Ae();rt();lt();at();ue();Xy();eb();rb();sb();cb()});var ub=f(()=>{"use strict";lb()});function TL(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function db(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Sd(i,t);return"error"in s?na(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:TL(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s)}}var pb=f(()=>{"use strict";ub();ue();Lt();Lt()});var mb,fb=f(()=>{"use strict";mb={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var wa,hb=f(()=>{"use strict";cy();Fy();Ky();pb();rt();Ae();fb();Lt();wa=class{type="github";capabilities=mb.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await sy(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await _y(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await ay(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Vy(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await db(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=_e(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return We(n,r,this.authInfo)}handleError(t){let n=ne(t);return qt(n)}}});import{createHash as kL}from"crypto";function gb(e){return Date.now()-e.createdAt<OL}function vL(){for(let[e,t]of Ft.entries())gb(t)||Ft.delete(e);if(Ft.size>Pd){let e=[...Ft.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Ft.size-Pd;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ft.delete(r[0])}}}function AL(e){return e?kL("sha256").update(e).digest("hex").slice(0,16):"default"}function LL(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function _L(e,t){let n=LL(t?.baseUrl||"default"),r=AL(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Cd(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=_L(e,t),r=Ft.get(n);if(r&&gb(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Ft.delete(n),Ft.size>=Pd&&vL();let o=new wa({...t,type:e}),i=Date.now();return Ft.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function yb(){try{return Cd("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
19
- `),[{provider:"github",ok:!1,error:t}]}}var OL,Pd,Ft,xd=f(()=>{"use strict";hb();OL=3600*1e3,Pd=20,Ft=new Map});async function bb(e,t={}){if(!Array.isArray(e))throw new Error($o.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error($o.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error($o.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Wo.NOT_A_FUNCTION.message(l))));if(r<i.length)return FL(i,r,n,o);let s=i.map((c,l)=>Rb(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function Rb(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Wo.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function FL(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Wo.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await Rb(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Sb=f(()=>{"use strict";at()});function Cb(e,t,n){if(e<=1)return Pb;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(IL/o),s=Math.max(ML,Math.min(i,Pb));return n?Math.max(s,n):s}async function xb(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await bb(s,{timeout:Cb(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function yi(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function bi(e){let t=new Set;return e.map((n,r)=>{let o=yi(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}var Pb,IL,ML,wd=f(()=>{"use strict";Sb();Pb=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,IL=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,ML=5e3});import{ContentSanitizer as DL}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as NL}from"@octocodeai/config";function GL(){try{return NL().output.format}catch{return"yaml"}}function xt(e){if(e==null)return e;if(typeof e=="string")return DL.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>xt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=xt(r);return t}return e}function HL(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
18
+ `).trim()}var ba=f(()=>{"use strict"});function Un(e){let t=e.toLowerCase();return t.endsWith("[bot]")||lL.has(t)}var lL,Ra=f(()=>{"use strict";lL=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});async function Sa(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=j(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function ad(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Sa(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return W({total_count:i.length,files:i},s)}async function uL(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Sa(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return W(i,s)}async function dL(e,t,n,r){try{let i=await(await ie(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return W(i.data.files||[],i.data)}catch{return null}}async function mL(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)break;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function cd(e,t,n,r,o){let i=await uL(e,t,n,o);if(!i)return null;let s=le(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await mL(a,pL,async l=>{let u=await dL(e,t,l.sha,o),d=[];return u&&(s+=le(u)??0,d=mi(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}});return W(c,s)}var pL,ld=f(()=>{"use strict";Ae();Mr();ue();pL=5});import{ContentSanitizer as ud}from"@octocodeai/octocode-engine/contentSanitizer";async function dd(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=j(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!Un(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(ya(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:ud.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return u>0&&m.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:W(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:W([],0)}}}async function pd(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Sa(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return W(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:ud.sanitizeContent(D.minifyMarkdownCore(ya(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return W([],0)}}async function md(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=j(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let l=o?i:i.filter(p=>!Un(p.user?.login??"")),u=i.length-l.length,d=l.map(p=>{let h=D.minifyMarkdownCore(ya(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:ud.sanitizeContent(h).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return u>0&&m.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:W(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:W([],0)}}}var Qy=f(()=>{"use strict";Ee();Ra();ue();ba();ld()});async function fd(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=od(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&id(t))try{let{owner:l,repo:u}=pi(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=j(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Dr(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Dr(t))){let m=await ad(l,u,e.number);m&&(s+=le(m)??0,m.files=mi(m.files,t),o.file_changes=m)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=ma(t),c=fa(t);if(a||c){let{owner:l,repo:u}=pi(t);if(l&&u){let d=sd(t),m=()=>Promise.resolve({comments:W([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([a?dd(n,l,u,e.number,d):m(),c?md(n,l,u,e.number,d):m()]);o.comments=[...p,...g],s+=(le(p)??0)+(le(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}}if(ga(t))try{let{owner:l,repo:u}=pi(t);if(l&&u){let d=await pd(n,l,u,e.number);s+=le(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(ha(t))try{let{owner:l,repo:u}=pi(t);if(l&&u){let d=await cd(l,u,e.number,t);d&&(s+=le(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return W(o,s)}async function fi(e,t,n,r){let{prData:o,sanitizationWarnings:i}=od(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Dr(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Dr(t))try{let d=await ad(a,c,e.number,r);d&&(s+=le(d)??0,d.files=mi(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=ma(t),u=fa(t);if(l||u){let d=sd(t),m=()=>Promise.resolve({comments:W([],0)}),[{comments:p,note:h},{comments:g,note:y}]=await Promise.all([l?dd(n,a,c,e.number,d):m(),u?md(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(le(p)??0)+(le(g)??0);let b=[h,y].filter(S=>typeof S=="string");b.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...b])}if(ga(t))try{let d=await pd(n,a,c,e.number);s+=le(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(ha(t))try{let d=await cd(a,c,e.number,t,r);d&&(s+=le(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return W(o,s)}var jy=f(()=>{"use strict";Mr();ue();ba();Qy();ld()});var Pa=f(()=>{"use strict";ba();jy()});function fL(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function By(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:qe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:qe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ie(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await fi(a,e,i,t);return{pull_requests:[Ir(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:j(s.data)+(le(c)??0)}}catch(i){let s=ne(i);return fL(s,qe.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var zy=f(()=>{"use strict";at();Ae();rt();lt();Mr();Pa();ue()});function hd(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function gd(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Uy(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await fi(m,t,e))),c=a.reduce((m,p)=>m+(le(p)??0),0),l=a.map(m=>Ir(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:j(s.data)+c}}catch(n){if(vt(n))return gd(t);let r=ne(n);return hd(r,qe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var $y=f(()=>{"use strict";ae();at();rt();ue();Mr();Pa()});async function hL(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function gL(e,t,n="anon"){return ke("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function qy(e,t,n){let r=await He(t),o=gL(e,n,r);return await Qe(o,async()=>await yL(e,t,n),{shouldCache:s=>!s.error})}async function yL(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await By(e,t);let r=await ie(t);if(!Au(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Uy(r,e);let i=await hL(r,e),s=vu(i);if(!s)return{pull_requests:[],total_count:0,error:qe.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),m=d.data.items?.filter(_=>!!_.pull_request)||[],p=await Promise.all(m.map(async _=>await fd(_,i,r))),h=p.reduce((_,w)=>_+(le(w)??0),0),g=p.map(_=>Ir(_,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),y=d.data.total_count,b=Math.min(y,1e3),S=Math.min(Math.ceil(b/c),10),x=Math.min(l,Math.max(1,S)),k=x<S,E=Math.min(b,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:x,totalPages:S,perPage:c,totalMatches:b,reportedTotalMatches:y,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:y>b,hasMore:k,...k?{nextPage:x+1}:{}},rawResponseChars:j(d.data)+h}}catch(r){if(vt(r))return gd(e);let o=ne(r);return hd(o,qe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}var Wy=f(()=>{"use strict";ae();at();Ae();rt();Or();lt();ue();Mr();Pa();zy();$y()});function bL(e,t,n=_e){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ai(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Vy(e,t,n=_e){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await qy(s,t);return a.error?qt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:bL(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??j(a)}}var Ky=f(()=>{"use strict";Wy();ue();Lt();Lt();Nu()});var Sn,hi=f(()=>{"use strict";Sn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function Ca(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var yd=f(()=>{"use strict"});function Yy(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:M,...A}=e;return A}let r=t.itemsPerPage??Sn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,m=M=>{let A=M;d&&M.startsWith(d)&&(A=M.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let q=A.lastIndexOf("/");return q===-1?".":A.slice(0,q)},p=M=>{let A=M.lastIndexOf("/");return A===-1?M:M.slice(A+1)};for(let M of l){let A=m(M.path);u[A]||(u[A]={files:[],folders:[]});let q=p(M.path);M.type==="file"?u[A].files.push(q):u[A].folders.push(q)}for(let M of Object.keys(u)){let A=u[M];A&&(A.files.sort(),A.folders.sort())}let h=Object.create(null),g=Object.keys(u).sort((M,A)=>M==="."?-1:A==="."?1:M.localeCompare(A));for(let M of g){let A=u[M];A&&(h[M]=A)}let y=l.filter(M=>M.type==="file").length,b=l.filter(M=>M.type==="dir").length,S=n.filter(M=>M.type==="file").length,x=n.filter(M=>M.type==="dir").length,k=o<s,E={currentPage:o,totalPages:s,hasMore:k,...k?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=Ca(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:y,pageFolders:b,allFiles:S,allFolders:x}),w,G=e._cachedFileSizeMap;if(G){let M=new Set(l.filter(H=>H.type==="file").map(H=>H.path)),A=e.path==="/"?"":e.path,q=Object.create(null);for(let[H,K]of Object.entries(G))for(let[I,ye]of Object.entries(K)){let Te=H==="."?A?`${A}/${I}`:I:A?`${A}/${H}/${I}`:`${H}/${I}`;M.has(Te)&&(q[H]||(q[H]=Object.create(null)),q[H][I]=ye)}Object.keys(q).length>0&&(w=q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:x,truncated:k,filtered:!0,originalCount:i},structure:h,...w!==void 0&&{fileSizeMap:w},...G!==void 0&&{_cachedFileSizeMap:G},pagination:E,hints:_,rawResponseChars:e.rawResponseChars}}var Xy=f(()=>{"use strict";hi();yd()});import{RequestError as SL}from"octokit";function Jy(e){return e instanceof SL&&PL.has(e.status)}function bd(e,t){try{Object.defineProperty(e,Zy,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function gi(e){if(typeof e!="object"||e===null)return 0;let t=e[Zy];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function yi(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return bd(W([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(h){if(Jy(h))throw h;return bd(W([],0),1)}let l=j(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(h=>h.type==="file"||h.type==="dir").map(h=>({name:h.name,path:h.path,type:h.type,size:"size"in h?h.size:void 0,download_url:"download_url"in h?h.download_url:void 0,url:h.url,html_url:h.html_url,git_url:h.git_url,sha:h.sha})),m=[...d],p=0;if(i<s){let h=d.filter(y=>y.type==="dir"),g=3;for(let y=0;y<h.length;y+=g){let b=h.slice(y,y+g),S=await Promise.allSettled(b.map(x=>yi(e,t,n,r,x.path,i+1,s,a)));for(let x of S)if(x.status==="fulfilled"){let k=x.value;l+=le(k)??0,p+=gi(k),m.push(...k)}else{if(Jy(x.reason))throw x.reason;p+=1}}}return bd(W(m,l),p)}var Zy,PL,eb=f(()=>{"use strict";ue();Zy=Symbol.for("octocode.recursiveFetchFailures"),PL=new Set([401,403,429])});import{RequestError as CL}from"octokit";function xL(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let l=a.lastIndexOf("/"),u=l===-1?a:a.slice(l+1);i.push({name:u,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function tb(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function nb(e,t){let{data:n}=await e.rest.repos.getBranch({owner:t.owner,repo:t.repo,branch:t.workingBranch}),r=n.commit.commit.tree.sha;if(!r)throw new Error(`Could not resolve tree SHA for ${t.owner}/${t.repo}@${t.workingBranch}`);let o;try{o=await e.rest.git.getTree({owner:t.owner,repo:t.repo,tree_sha:r,recursive:"true",...t.ifNoneMatch?{headers:{"If-None-Match":t.ifNoneMatch}}:{}})}catch(c){if(c instanceof CL&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=Ar(o.headers);return{items:xL(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:j(n)+j(i),...s?{etag:s}:{}}}var rb=f(()=>{"use strict";ue();Lr()});import{RequestError as ob}from"octokit";async function Rd(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await We(t,n,i),a=c)}catch(l){let u=ne(l);return{error:bn.NOT_FOUND.message(t,n,u.error),status:u.status}}try{let l=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),u=Ar(l.headers);return{data:l.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...u?{etag:u}:{}}}catch(l){if(l instanceof ob&&l.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(l instanceof ob&&l.status===404)){let d=ne(l);return{error:bn.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let u=ne(l);return{error:bn.PATH_NOT_FOUND.message(r,t,n,a),status:u.status}}}function ib(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}var sb=f(()=>{"use strict";rt();at();Ae();Lr()});function wL(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function ab(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}function xa(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:l,includeSizes:u,extraHints:d=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!oi(I.name):!vr(I.path));m.sort((I,ye)=>{if(I.type!==ye.type)return I.type==="dir"?-1:1;let Te=I.path.split("/").length,nn=ye.path.split("/").length;return Te!==nn?Te-nn:I.path.localeCompare(ye.path)});let p=e.itemsPerPage??Sn.ENTRIES_PER_PAGE,h=e.page??1,g=m.length,y=Math.max(1,Math.ceil(g/p)),b=(h-1)*p,S=Math.min(b+p,g),x=m.slice(b,S),k=wL(x,i),E=u?ab(m,i):void 0,_=E!==void 0?ab(x,i):void 0,w=x.filter(I=>I.type==="file").length,G=x.filter(I=>I.type==="dir").length,M=m.filter(I=>I.type==="file").length,A=m.filter(I=>I.type==="dir").length,q=h<y,H={currentPage:h,totalPages:y,hasMore:q,...q?{nextPage:h+1}:{},entriesPerPage:p,totalEntries:g},K=Ca(H,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:w,pageFolders:G,allFiles:M,allFolders:A});a>0&&K.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let I of d)K.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:M,totalFolders:A,truncated:q,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:k,..._!==void 0&&{fileSizeMap:_},...E!==void 0&&{_cachedFileSizeMap:E},pagination:H,hints:K,rawResponseChars:l,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}var cb=f(()=>{"use strict";hi();yd();ii()});async function Sd(e,t,n){let r=await He(t),o=ke("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await ta(o,async({ifNoneMatch:s})=>{let a=await TL({...e,itemsPerPage:e.itemsPerPage??Sn.ENTRIES_PER_PAGE,page:e.page??1},t,s);return{value:a.result,etag:a.etag,notModified:a.notModified}},{shouldCache:s=>!("error"in s)});return!("error"in i)&&i.structure?Yy(i,e):i}async function TL(e,t,n){try{let r=await ie(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,l=a.replace(/^\/+|\/+$/g,"");if(c>1&&tb())return await EL(r,e,l,c,t,n);let u=await Rd(r,o,i,l,s,t,c===1?n:void 0);if("error"in u)return{result:u};if(u.notModified)return{result:{error:"not-modified",status:304},etag:u.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:h}=u,g=j(d),y=Array.isArray(d)?d:[d],b=ib(y),S=0;if(c>1){let x=await yi(r,o,i,m,l,1,c);S=gi(x),g=le(x)??0,b=x}return{result:xa({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:l,depth:c,allItems:b,partialTreeFailures:S,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&h?{etag:h}:{}}}catch(r){let o=ne(r);return{result:{error:bn.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function EL(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,l,u;try{c?l=c:(u=await We(s,a,o),l=u)}catch(b){let S=ne(b);return{result:{error:bn.NOT_FOUND.message(s,a,S.error),status:S.status}}}let d;try{d=await nb(e,{owner:s,repo:a,workingBranch:l,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(b){let S=await Rd(e,s,a,n,l,o);if("error"in S)return{result:S};let x=await yi(e,s,a,S.workingBranch,n,1,r);return{result:xa({owner:s,repo:a,workingBranch:S.workingBranch,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:x,partialTreeFailures:gi(x),incompleteTree:!1,rawResponseChars:le(x)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${b instanceof Error?b.message:String(b)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,h=d.rawResponseChars,g=d.truncated,y=[];if(g){y.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let b=await yi(e,s,a,l,n,1,r);p=gi(b),h+=le(b)??0,m=[...m,...b].filter((x,k,E)=>E.findIndex(_=>_.path===x.path)===k)}catch{}}return{result:xa({owner:s,repo:a,workingBranch:l,repoDefaultBranch:u,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:h,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:y}),...d.etag&&!g?{etag:d.etag}:{}}}var lb=f(()=>{"use strict";hi();Ae();rt();lt();at();ue();Xy();eb();rb();sb();cb()});var ub=f(()=>{"use strict";lb()});function kL(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function db(e,t,n=_e){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Sd(i,t);return"error"in s?na(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:kL(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??j(s)}}var pb=f(()=>{"use strict";ub();ue();Lt();Lt()});var mb,fb=f(()=>{"use strict";mb={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var wa,hb=f(()=>{"use strict";cy();Fy();Ky();pb();rt();Ae();fb();Lt();wa=class{type="github";capabilities=mb.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await sy(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await _y(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await ay(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Vy(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await db(t,this.authInfo,_e)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=_e(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return We(n,r,this.authInfo)}handleError(t){let n=ne(t);return qt(n)}}});import{createHash as vL}from"crypto";function gb(e){return Date.now()-e.createdAt<AL}function LL(){for(let[e,t]of Ft.entries())gb(t)||Ft.delete(e);if(Ft.size>Pd){let e=[...Ft.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Ft.size-Pd;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ft.delete(r[0])}}}function _L(e){return e?vL("sha256").update(e).digest("hex").slice(0,16):"default"}function FL(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function IL(e,t){let n=FL(t?.baseUrl||"default"),r=_L(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Cd(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=IL(e,t),r=Ft.get(n);if(r&&gb(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Ft.delete(n),Ft.size>=Pd&&LL();let o=new wa({...t,type:e}),i=Date.now();return Ft.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function yb(){try{return Cd("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
19
+ `),[{provider:"github",ok:!1,error:t}]}}var AL,Pd,Ft,xd=f(()=>{"use strict";hb();AL=3600*1e3,Pd=20,Ft=new Map});async function bb(e,t={}){if(!Array.isArray(e))throw new Error(qo.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(qo.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(qo.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Vo.NOT_A_FUNCTION.message(l))));if(r<i.length)return ML(i,r,n,o);let s=i.map((c,l)=>Rb(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function Rb(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Vo.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function ML(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Vo.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await Rb(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Sb=f(()=>{"use strict";at()});function Cb(e,t,n){if(e<=1)return Pb;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(DL/o),s=Math.max(NL,Math.min(i,Pb));return n?Math.max(s,n):s}async function xb(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await bb(s,{timeout:Cb(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function bi(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function Ri(e){let t=new Set;return e.map((n,r)=>{let o=bi(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}var Pb,DL,NL,wd=f(()=>{"use strict";Sb();Pb=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,DL=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,NL=5e3});import{ContentSanitizer as GL}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as HL}from"@octocodeai/config";function QL(){try{return HL().output.format}catch{return"yaml"}}function xt(e){if(e==null)return e;if(typeof e=="string")return GL.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>xt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=xt(r);return t}return e}function jL(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
20
20
 
21
- `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function qn(e,t){let n=$n(e)??{},r=xt(n),o=GL(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ta(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Ta(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ta(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ta(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ta(n[o],t));return r}function BL(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>QL.has(r))||jL.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function $n(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>$n(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(BL(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=$n(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var QL,jL,Dr=f(()=>{"use strict";Ee();QL=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]),jL=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});function zL(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function Td(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Td(o,t,n+1);return}let r=e;for(let o of Ed){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))wb.has(o)||i&&typeof i=="object"&&Td(i,t,n+1)}function Ea(e){let t=[];for(let i of e)Td(i?.data,t,0);if(t.length===0)return;let n=zL(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return UL(e,r),n}function UL(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(wb.has(s))continue;let a=i[s];typeof a=="string"?!Ed.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function $L(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function qL(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function ka(e){let t=$L(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(WL.has(i))continue;let s=n[i];qL(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var Ed,wb,WL,kd=f(()=>{"use strict";Ed=["path","uri"],wb=new Set(["next","location"]);WL=new Set([...Ed,"owner","repo","name","id"])});function Od(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
22
- `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function VL(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Od(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function KL(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Od(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function vd(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=Od(e,s,i),c=a<o,l=VL(e,s,i),u=KL(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
21
+ `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function qn(e,t){let n=$n(e)??{},r=xt(n),o=QL(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ta(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Ta(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ta(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ta(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ta(n[o],t));return r}function UL(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>BL.has(r))||zL.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function $n(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>$n(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(UL(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=$n(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var BL,zL,Nr=f(()=>{"use strict";Ee();BL=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]),zL=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});function $L(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function Td(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Td(o,t,n+1);return}let r=e;for(let o of Ed){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))wb.has(o)||i&&typeof i=="object"&&Td(i,t,n+1)}function Ea(e){let t=[];for(let i of e)Td(i?.data,t,0);if(t.length===0)return;let n=$L(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return qL(e,r),n}function qL(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(wb.has(s))continue;let a=i[s];typeof a=="string"?!Ed.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function WL(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function VL(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function ka(e){let t=WL(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(KL.has(i))continue;let s=n[i];VL(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var Ed,wb,KL,kd=f(()=>{"use strict";Ed=["path","uri"],wb=new Set(["next","location"]);KL=new Set([...Ed,"owner","repo","name","id"])});function Od(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
22
+ `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function YL(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Od(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function XL(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Od(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function vd(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=Od(e,s,i),c=a<o,l=YL(e,s,i),u=XL(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
23
23
  `:`# Response page ${l}/${u}.
24
- `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Ad(e,t){return t?{...e,responsePagination:t}:e}var Tb=f(()=>{"use strict"});async function me(e,t,n,r){let o=n.concurrency??YL,{results:i,errors:s}=await xb(e,t,o,n.minQueryTimeoutMs);return XL(n,i,s,e,r)}function XL(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length),l=bi(r);t.forEach(y=>{let b=y.result.status;c[y.queryIndex]={id:l[y.queryIndex]??yi(y.originalQuery,y.queryIndex),...b!==void 0?{status:b}:{},data:JL(y.result)}}),n.forEach(y=>{let b=r[y.queryIndex];b&&(c[y.queryIndex]={id:l[y.queryIndex]??yi(b,y.queryIndex),status:"error",data:{error:y.error}})});let u=c.filter(y=>y!==void 0);if(e.finalize){let y=e.finalize({queries:r,results:u,config:e}),b=vd(y.text,o),S=Ad(y.structuredContent,b.pagination);return Eb(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:S,isError:y.isError??(u.length>0&&u.every(k=>k.status==="error"))}}let d={results:u};if(Array.isArray(d.results)){let y=Ea(d.results);y&&(d.base=y);let b=ka(d.results);b&&(d.shared=b)}let m=qn(d,a),p=vd(m,o),h=Ad(xt($n(d)??{}),p.pagination);return Eb(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:h,isError:u.length>0&&u.every(y=>y.status==="error")}}function Eb(e,t,n,r){let o=t.reduce((i,s)=>i+(le(s.result)??j(s.result)),0)+n.reduce((i,s)=>i+j(s),0);try{uu(e,o,r)}catch{}}function JL(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}var YL,kb=f(()=>{"use strict";Ot();Dr();ue();kd();Tb();wd();YL=3});var Ke=f(()=>{"use strict";wd();kb()});var $,Ob,Wn=f(()=>{"use strict";$={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"},Ob={[$.PATH_VALIDATION_FAILED]:{code:$.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[$.FILE_ACCESS_FAILED]:{code:$.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[$.FILE_READ_FAILED]:{code:$.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[$.FILE_TOO_LARGE]:{code:$.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[$.BINARY_FILE_UNSUPPORTED]:{code:$.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[$.NO_MATCHES]:{code:$.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[$.OUTPUT_TOO_LARGE]:{code:$.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[$.COMMAND_NOT_AVAILABLE]:{code:$.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[$.COMMAND_EXECUTION_FAILED]:{code:$.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[$.COMMAND_TIMEOUT]:{code:$.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[$.TOOL_EXECUTION_FAILED]:{code:$.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[$.LSP_SERVER_UNAVAILABLE]:{code:$.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function Ld(e){return e instanceof je}function vb(e,t=$.TOOL_EXECUTION_FAILED,n){if(Ld(e))return e;if(e instanceof Error)return new je(t,e.message,n,e);let r=String(e);return new je(t,r,n)}var je,Oa=f(()=>{"use strict";Wn();je=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Ob[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
25
- Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}}});function ZL(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function N(e,t,n={}){let{extra:r}=n,o={status:"error"};if(ZL(e))o.error=e;else if(Ld(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=vb(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:W(o,n.rawResponse)}function ot(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:N(i,t,{toolName:n.toolName})}}var _d=f(()=>{"use strict";Oa();ue()});function xe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:W(s,o.rawResponse)}function va(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return N(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ze(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return N(i,t,{toolName:r})}var De=f(()=>{"use strict";_d();ue()});async function ut({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ze(o,t,r,e)}}var Vn=f(()=>{"use strict";De()});function Fd(e){return e.data!==void 0&&!e.error}var Ab=f(()=>{"use strict"});import{maskSensitiveData as Lb}from"@octocodeai/octocode-engine/mask";function e_(){return yu().provider??gu()}function t_(e){let t=yu(),n=t.provider??gu(),{baseUrl:r,token:o}=t;try{let i=Cd(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=Lb(s);throw new Id(n,`Failed to initialize ${n} provider: ${a}`)}}function dt(e){let t;return()=>t??=t_(e)}function Aa(e,t){return e.capabilities[t]}async function Wt(e,t){let n=await t();return Fd(n)?{ok:!0,response:n}:{ok:!1,result:va(n,e)}}async function _b(e,t){let n=t??e_(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:Lb(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Fd(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Id,Pn=f(()=>{"use strict";xd();Ab();Yo();De();Id=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});function Ib(e={},t=La){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}var La,Ri,Fb,Md=f(()=>{"use strict";La=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Ri=[...La,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Fb=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"]});import{spawn as n_}from"child_process";function Kn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=La,maxOutputSize:a=r_}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),m={cwd:o,env:Ib(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=n_(e,t,m)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let h,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},o_),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),y=()=>{clearTimeout(g),h!==void 0&&(clearTimeout(h),h=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",S=>{if(l.killed)return;let x=S.toString();l.totalOutputSize+=Buffer.byteLength(x),!b()&&l.stdoutChunks.push(x)}),p.stderr?.on("data",S=>{if(l.killed)return;let x=S.toString();l.totalOutputSize+=Buffer.byteLength(x),!b()&&l.stderrChunks.push(x)}),p.on("close",S=>{l.killed||(y(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),p.on("error",S=>{l.killed||(l.killed=!0,y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function Mb(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var r_,o_,bK,Db=f(()=>{"use strict";Md();r_=10*1024*1024,o_=5e3;bK=1*1024*1024});var _a=f(()=>{"use strict";Md();Db()});import{join as Fa}from"node:path";import{createHash as Nb}from"node:crypto";function Ia(e){return Fa(e,"tmp","clone")}function Ma(e){return Fa(e,"tmp","tree")}function i_(e){return e?`__sp_${Nb("sha256").update(e).digest("hex").substring(0,6)}`:""}function Gb(e){if(!/[\\/]/.test(e))return e;let t=Nb("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function Dd(e,t,n,r,o){let i=`${Gb(r)}${i_(o)}`;return Fa(Ia(e),t,n,i)}function Si(e,t,n,r){return Fa(Ma(e),t,n,Gb(r))}var Nd=f(()=>{"use strict"});import{existsSync as xi,readFileSync as s_,writeFileSync as a_,mkdirSync as c_,rmSync as Ci,readdirSync as l_,statSync as u_}from"node:fs";import{join as Cn}from"node:path";function f_(e){return typeof e=="object"&&e!==null}function h_(e){if(!f_(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 Gd(e){let t=Cn(e,Qb);if(!xi(t))return null;try{return h_(JSON.parse(s_(t,"utf-8")))}catch{return null}}function Nr(e,t){try{a_(Cn(e,Qb),JSON.stringify(t,null,2),"utf-8")}catch{}}function jb(e){return Date.now()<new Date(e.expiresAt).getTime()}function Gr(e){let t=Gd(e);return t?jb(t)?xi(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function g_(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return d_}function y_(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return p_}function b_(){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 m_}function Hr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+g_()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function xn(e){let t=Cn(e,"..");try{xi(t)||c_(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 Da(e){try{xi(e)&&Ci(e,{recursive:!0,force:!0})}catch{}}function Pi(e){try{return u_(e).isDirectory()}catch{return!1}}function Yn(e){try{return l_(e)}catch{return[]}}function*Bb(e){for(let t of Yn(e)){let n=Cn(e,t);if(Pi(n))for(let r of Yn(n)){let o=Cn(n,r);if(Pi(o))for(let i of Yn(o)){let s=Cn(o,i);Pi(s)&&(yield s)}}}}function Hb(e){for(let t of[...Yn(e)]){let n=Cn(e,t);if(Pi(n)){for(let r of[...Yn(n)]){let o=Cn(n,r);if(Pi(o)&&Yn(o).length===0)try{Ci(o,{recursive:!0,force:!0})}catch{}}if(Yn(n).length===0)try{Ci(n,{recursive:!0,force:!0})}catch{}}}}function R_(e){let t=0;for(let n of Bb(e))try{let r=Gd(n);(!r||!jb(r))&&(Ci(n,{recursive:!0,force:!0}),t++)}catch{}return t}function S_(e){let t=[];for(let n of Bb(e)){let r=Gd(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??Vs(n)})}return t}function P_(e,t,n){let r=e.reduce((s,a)=>s+a.sizeBytes,0),o=e.length;if(r<=t&&o<=n)return 0;e.sort((s,a)=>s.clonedAtMs-a.clonedAtMs);let i=0;for(let s of e){if(r<=t&&o<=n)break;try{Ci(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function zb(e){if(!xi(e))return 0;let t=0;try{t+=R_(e)}catch{return t}Hb(e);let n=P_(S_(e),y_(),b_());return t+=n,n>0&&Hb(e),t}function Ub(e){return zb(Ia(e))}function Na(e){return zb(Ma(e))}var d_,LK,p_,m_,Qb,Ga=f(()=>{"use strict";Ot();Nd();Nd();d_=1440*60*1e3,LK=600*1e3,p_=2*1024*1024*1024,m_=50,Qb=".octocode-clone-meta.json"});import{existsSync as C_,mkdirSync as Hd,renameSync as x_,rmSync as w_}from"fs";import{join as wi}from"path";import{createHash as T_}from"crypto";async function Vb(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await G_();let a=e.branch??await We(r,o,t),c=xr(),l=Dd(c,r,o,a,i);return A_(c,l,async()=>{let u=Gr(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Ub(c),xn(l);let d=N_(t,n),m=__(c,l);Da(m);try{if(i){if(await D_(r,o,a,m,i,d),!C_(wi(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await M_(r,o,a,m,d);let p=Hr(r,o,a,"clone",i);return Nr(m,p),F_(m,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw Da(m),p}})}async function A_(e,t,n){xn(t);let r=L_(e,t);Hd(wi(e,"tmp",qb),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Hd(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>k_)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await I_(O_)}try{return await n()}finally{w_(r,{recursive:!0,force:!0})}}function Kb(e){return T_("sha256").update(e).digest("hex").slice(0,16)}function L_(e,t){return wi(e,"tmp",qb,Kb(t))}function __(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=wi(e,"tmp",v_);return Hd(r,{recursive:!0,mode:448}),wi(r,`${Kb(t)}-${n}`)}function F_(e,t){Da(t),xn(t),x_(e,t)}function I_(e){return new Promise(t=>setTimeout(t,e))}async function M_(e,t,n,r,o){let i=Xb(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Yb(e,t),r),await Qd(i,$b,`full clone of ${e}/${t}`,o)}async function D_(e,t,n,r,o,i){let s=Xb(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Yb(e,t),r),await Qd(s,$b,`sparse clone of ${e}/${t}`,i),await Qd(["-C",r,"sparse-checkout","set","--skip-checks","--",o],E_,`sparse-checkout set ${o}`,void 0)}function Yb(e,t){return`https://github.com/${e}/${t}.git`}function Xb(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function N_(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function G_(){try{if(!(await Kn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Wb,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function H_(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function Qd(e,t,n,r){let o=await Kn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Wb,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=H_(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var $b,E_,k_,O_,qb,v_,Wb,Jb=f(()=>{"use strict";Ot();Ae();_a();Ga();$b=120*1e3,E_=30*1e3,k_=300*1e3,O_=100,qb="clone-locks",v_="clone-tmp",Wb=[...Ri,"GIT_TERMINAL_PROMPT"]});async function Zb(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>ut({toolName:v.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Aa(s,"cloneRepo"))return ze(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",v.GITHUB_CLONE_REPO);let a;try{a=await Vb(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return N(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=Vs(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return xe(o,d,!0,v.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:v.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","location","error"]},e)}var eR=f(()=>{"use strict";Ot();pe();Ke();De();Vn();Pn();Jb()});import{readdirSync as Q_,statSync as tR}from"node:fs";import{join as j_}from"node:path";function zd(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function oR(e){return Object.values(e).every(t=>t===0)}function Ud(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 iR(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 U_(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function U_(e,t){try{let o=new URL(e);if(!z_.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(),B_);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 sR(e,t){let n=[],r=0;function o(i){let s;try{s=Q_(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=j_(i,a);try{let l=tR(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 aR(e){try{return tR(e).size}catch{return 0}}var Ti,Ha,jd,nR,B_,rR,Bd,z_,Qa=f(()=>{"use strict";Ti=50,Ha=5*1024*1024,jd=300*1024,nR=5,B_=1e4,rR=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"]),Bd={maxDirectoryFiles:Ti,maxTotalSize:Ha,maxFileSize:jd};z_=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});import{writeFileSync as $_,mkdirSync as cR,existsSync as $d,rmSync as q_}from"node:fs";import{join as lR,dirname as W_,resolve as uR,sep as dR}from"node:path";async function qd(e,t,n,r,o,i=!1){let s=xr(),a=Si(s,e,t,r),c=uR(lR(a,n));if(!c.startsWith(a+dR)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Gr(a);if(l.hit&&!i&&$d(c)){let A=sR(c,a),q=zd();return{localPath:c,repoRoot:a,files:A.files,fileCount:A.fileCount,totalSize:A.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:A.fileCount,eligibleFileCount:A.fileCount,savedFileCount:A.fileCount,skipped:q,limits:Bd,warnings:Ud(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await ie(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let p=m,h=zd(),g=[];for(let A of p){if(A.type!=="file"){h.nonFile+=1;continue}if(!A.download_url){h.missingDownloadUrl+=1;continue}if(A.size>jd){h.oversized+=1;continue}let q=Yg(A.name,{lowercase:!0,leadingDot:!0});if(rR.has(q)){h.binary+=1;continue}g.push(A)}h.fileLimit=Math.max(0,g.length-Ti);let y=g.slice(0,Ti),b=o?.token,S=await iR(y,nR,b);h.fetchFailed=y.length-S.length;let x=0,k=[];for(let A=0;A<S.length;A+=1){let{entry:q,content:H}=S[A];if(x+H.length>Ha){h.totalSizeLimit=S.length-A;break}x+=H.length,k.push({entry:q,content:H})}Na(s),xn(a),$d(c)&&q_(c,{recursive:!0,force:!0}),cR(c,{recursive:!0,mode:448});let E=[];for(let{entry:A,content:q}of k){let H=uR(lR(a,A.path));if(!H.startsWith(a+dR)){h.pathTraversal+=1;continue}let K=W_(H);$d(K)||cR(K,{recursive:!0,mode:448}),$_(H,q,"utf-8"),E.push({path:A.path,size:q.length,type:"file"})}let _=Hr(e,t,r,"treeFetch",void 0,void 0,d);Nr(a,_);let w=oR(h),G=w,M=h.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:x,complete:w,verified:G,...d?{commitSha:d}:{},...M?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:h,limits:Bd,warnings:Ud(w,G),cached:!1,expiresAt:_.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}var pR=f(()=>{"use strict";Ot();Ae();Ga();oi();Qa()});import{writeFileSync as V_,mkdirSync as K_,existsSync as mR}from"node:fs";import{join as Y_,dirname as X_,resolve as J_,sep as Z_}from"node:path";async function Wd(e,t,n,r,o,i=!1){let s=xr(),a=Si(s,e,t,r),c=J_(Y_(a,n));if(!c.startsWith(a+Z_)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Gr(a);if(!i&&l.hit&&mR(c))return{localPath:c,repoRoot:a,path:n,size:aR(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await ai({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let h="error"in u?u.error:void 0;throw new Error(h||`Failed to fetch ${e}/${t}/${n}`)}Na(s),xn(a);let d=X_(c);mR(d)||K_(d,{recursive:!0,mode:448}),V_(c,u.data.rawContent,"utf-8");let m=u.data.branch||r,p=Hr(e,t,m,"treeFetch");return Nr(a,p),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}var fR=f(()=>{"use strict";Ot();Vu();Ga();Qa()});var hR=f(()=>{"use strict";Qa();pR();fR()});function ja(e,t){return e&&t?`${e}/${t}`:void 0}function Ba(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function za(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}var Ua=f(()=>{"use strict"});function tF(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function gR(e){return{keywords:e.keywords??[],projectId:ja(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function yR(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=Ba(a),u=`${c}/${l}`,d=s,m=o.get(u);if(m||(m={id:u,owner:c,repo:l,matches:[]},o.set(u,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let p=!0,h=!1;for(let g of s.matches){if(!g.context)continue;let y={path:s.path,value:tF(g.context)};g.positions?.length>0&&(y.matchIndices=g.positions.map(([b,S])=>({start:b,end:S,lineOffset:(g.context??"").substring(0,b).split(`
26
- `).length-1}))),r&&p&&d.url&&(y.url=d.url,p=!1),m.matches.push(y),h=!0}h||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...za(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}var bR=f(()=>{"use strict";ae();Ua()});function RR(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function SR(e){return e.map(t=>{let{owner:n,repo:r}=Ba(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}var PR=f(()=>{"use strict";Ua()});function $a(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}var Vd=f(()=>{"use strict"});function CR(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map($a),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ja(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function nF(e,t){let n=[];t.some(o=>o.state==="APPROVED")&&n.push("approval"),t.some(o=>o.state==="CHANGES_REQUESTED")&&n.push("changes-requested");let r=e.filter(o=>!Un(o.author??"")).map(o=>o.body.toLowerCase());return n.length===0&&r.some(o=>/\b(lgtm|looks good|approved|ship it)\b/.test(o))&&n.push("approval"),!n.includes("changes-requested")&&r.some(o=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(o))&&n.push("changes-requested"),r.some(o=>o.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function rF(e,t){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(i=>i.author))),r=e.map(i=>i.updatedAt||i.createdAt).filter(Boolean).sort().at(-1),o=e.filter(i=>i.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:o,discussionComments:e.length-o,commenters:n.slice(0,8),...r?{latestCommentAt:r}:{},themes:nF(e,t??[])}}function xR(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=rF(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...za(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}var wR=f(()=>{"use strict";ae();Vd();Ra();Ua()});function TR(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function ER(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}var kR=f(()=>{"use strict"});function Kd(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Sn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function OR(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([m],[p])=>m==="."?-1:p==="."?1:m.localeCompare(p)).map(([m,p])=>({dir:m,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[m,p]of Object.entries(c))if(n[m]){let h=new Set(n[m].files);for(let[g,y]of Object.entries(p))if(h.has(g)){let b=m==="."?g:`${m}/${g}`;l[b]=y}}}let u=Object.values(n).reduce((m,p)=>(m.totalFiles+=p.files.length,m.totalFolders+=p.folders.length,m),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var vR=f(()=>{"use strict";fi()});var Qr=f(()=>{"use strict";bR();PR();wR();kR();vR()});function qa(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function oF(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:qa(t.status),retryAfterSeconds:qa(t.retryAfter),rateLimitRemaining:qa(t.rateLimitRemaining),rateLimitReset:qa(t.rateLimitReset)}}return{message:"Provider error"}}function Wa(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=oF(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function Va(e,t,n){let r=qn(e,[...t]);return{structuredContent:xt($n(e)??{}),text:r,isError:n}}var Yd=f(()=>{"use strict";Dr()});function Ka(e){return typeof e=="object"&&e!==null}function pt(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function AR(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function wt(e,t){return Ye(e[t])??0}function iF(e){if(Ka(e))return{nonFile:wt(e,"nonFile"),missingDownloadUrl:wt(e,"missingDownloadUrl"),oversized:wt(e,"oversized"),binary:wt(e,"binary"),fileLimit:wt(e,"fileLimit"),fetchFailed:wt(e,"fetchFailed"),totalSizeLimit:wt(e,"totalSizeLimit"),pathTraversal:wt(e,"pathTraversal")}}function sF(e){if(Ka(e))return{maxDirectoryFiles:wt(e,"maxDirectoryFiles"),maxTotalSize:wt(e,"maxTotalSize"),maxFileSize:wt(e,"maxFileSize")}}function cF(e){if(!Ka(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of aF){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function lF(e,t){return _s("ghGetFileContent",{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,...t.minify!==void 0?{minify:t.minify}:{}},e)}function uF(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"lspGetSemantics (definitions/references) only works on local files \u2014 clone this path locally, then run localSearchCode or lspGetSemantics on it",confidence:"exact"}}function LR(e,t){let n=cF(e.pagination),r={...lF(n,t),cloneForSemantics:uF(t)};return{path:pt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:pt(e.localPath),repoRoot:pt(e.repoRoot),...Ye(e.fileSize)!==void 0?{fileSize:Ye(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:Ye(e.totalLines),sourceChars:Ye(e.sourceChars),sourceBytes:Ye(e.sourceBytes),resolvedBranch:pt(e.resolvedBranch),pagination:n,next:r,...e.isPartial===!0?{isPartial:!0}:{},startLine:Ye(e.startLine),endLine:Ye(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:pt(e.lastModified),lastModifiedBy:pt(e.lastModifiedBy),warnings:AR(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:pt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function _R(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Ka).map(c=>({path:pt(c.path)??"",size:Ye(c.size)??0,type:pt(c.type)??"file"})),o=iF(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:pt(e.localPath)??"",repoRoot:pt(e.repoRoot),fileCount:Ye(e.fileCount)??r.length,totalSize:Ye(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ye(e.directoryEntryCount),eligibleFileCount:Ye(e.eligibleFileCount),savedFileCount:Ye(e.savedFileCount),skipped:o,limits:sF(e.limits),warnings:AR(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:pt(e.resolvedBranch)}}var aF,FR=f(()=>{"use strict";Be();aF=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});function dF(e,t){return`${e}/${t}`}function pF(e,t,n){let r=dF(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function mF(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=pF(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(_R(c,o)),a.directories=u;return}let l=a.files??[];l.push(LR(c,o)),a.files=l}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function fF(e,t){return Wa(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function IR(){return({queries:e,results:t})=>{let n=new Map,r=bi(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=mF(t,n),i=fF(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Va(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}var MR=f(()=>{"use strict";Yd();Ke();FR()});async function DR(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{let s=ot(Fn,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?hF(a,n,c):gF(a,n,c)}catch(s){return ze(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:IR()},e)}async function hF(e,t,n){if(!Aa(n,"fetchDirectoryToDisk"))return ze(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",v.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return N("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await We(e.owner,e.repo,t),o=await qd(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return xe(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??j(o)})}async function gF(e,t,n){let r=await Wt(e,()=>n.provider.getFileContent(TR(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await yF(e,t):void 0,i={...ER(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return xe(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function yF(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await We(e.owner,e.repo,t);return Wd(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var NR=f(()=>{"use strict";pe();Ke();De();Ol();hR();Ae();ue();Qr();Pn();MR()});function Ei(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function GR(e,t){let n=Ei(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function HR(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{},...t?.repoState?{repoState:t.repoState}:{}}}function bF(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function RF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function SF(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${RF(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function PF(e,t){return{...e,matches:t}}function Xd(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?bF(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:SF(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:PF(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}var Ya=f(()=>{"use strict"});function jR(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function QR(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function BR(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:QR(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:QR(r.get(i)),...s?{pagination:s}:{}}}})}function zR(e,t,n){let r=Ei(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),l=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!l)continue;let u=e.length===1?"getLines":`getLines:${i.id}`;o[u]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:l},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"heuristic"}}return Object.keys(o).length>0?o:void 0}var UR=f(()=>{"use strict";Ya()});function Jd(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Ei(e);t.forEach((x,k)=>{if(x.status==="error")return;let E=HR(x);E.repoState&&s.push({id:x.id,state:E.repoState,query:a.get(x.id)}),E.incompleteResults&&(i=!0),E.results.reduce((G,M)=>G+M.matches.length,0)===0&&o.push({id:x.id,...E.nonExistentScope?{nonExistentScope:!0}:{},...E.incompleteResults?{incompleteResults:!0}:{}});let w=E.results;n.push({id:x.id,groups:w}),E.pagination&&r.set(x.id,E.pagination)});let c=Array.from(new Set(e.flatMap(x=>{let k=x.keywords;return Array.isArray(k)?k.filter(E=>typeof E=="string"):[]}))),l=Xd(jR(n),c),u=Wa(t),d=e.some(x=>x.concise===!0),m=BR(e,l,r),p=zR(m,e,c);if(d)for(let x of m)x.data.files=x.data.files.map(k=>`${k.owner}/${k.repo}:${k.path}`);let h={results:m,...p?{next:p}:{}};o.length>0&&(h.emptyQueries=o.map(({id:x,nonExistentScope:k,incompleteResults:E})=>({id:x,...k?{nonExistentScope:k}:{},...E?{incompleteResults:E}:{}}))),u.length>0&&(h.errors=u);let g=[],y=(x,k,E="warning")=>{h.warnings=[...h.warnings??[],k],g.push({level:E,code:x,message:k})};i&&y("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&GR(o,e)&&y("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let b=8,S=o.filter(({id:x,nonExistentScope:k,incompleteResults:E})=>{if(k||E)return!1;let _=a.get(x)?.keywords;return Array.isArray(_)&&_.length>b});S.length>0&&y("ghQueryPossiblyTooComplex",`Quer${S.length>1?"ies":"y"} ${S.map(x=>x.id).join(", ")} used more than ${b} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:x,state:k,query:E}of s)if(k.kind==="renamed"){let[_,w]=k.fullName.split("/");y("ghRepoRenamed",`Query ${x}: the repository was RENAMED to ${k.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let G=E?.keywords;h.next={...h.next??{},[`retryRenamed:${x}`]:{tool:"ghSearchCode",query:{owner:_,repo:w,...Array.isArray(G)?{keywords:G}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else k.kind==="archived"?y("ghRepoArchived",`Query ${x}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):y("ghRepoNotFound",`Query ${x}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`,"error");return g.length>0&&(h.diagnostics=g),Va(h,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],l.length===0&&u.length>0)}}var $R=f(()=>{"use strict";Yd();Ya();UR()});var qR=f(()=>{"use strict";Ya();$R()});function CF(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function xF(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function wF(e,t,n){try{let r=await ie(n),{data:o}=await r.rest.repos.get({owner:e,repo:t}),i=`${e}/${t}`.toLowerCase();return o.full_name&&o.full_name.toLowerCase()!==i?{kind:"renamed",fullName:o.full_name}:o.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function WR(e){let{queries:t}=e,n=dt(e.authInfo);return me(t,async(r,o)=>{try{let i=xF(r);if(i)return N(i.error,r);if(!CF(r))return N("At least one search term or scope filter is required.",r);let s=n(),a=await Wt(r,()=>s.provider.searchCode(gR(r)));if(a.ok===!1)return a.result;let c=yR(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let l=await wF(String(r.owner),String(r.repo),e.authInfo);l&&(c.repoState=l)}return xe(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ze(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:Jd()},e)}var VR=f(()=>{"use strict";pe();Ke();Ae();De();Qr();Pn();qR()});function jr(e){return e?e.includes('rel="next"'):!1}async function EF(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}function KR(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function YR(e,t,n){let r=await He(t),o=ke("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return Qe(o,()=>kF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function kF(e,t){try{let n=await ie(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=jr(i),a=o.data.map(u=>{let d=u.commit.author,m=u.commit.committer,p=m?.date??d?.date??"",h=u.commit.message,g=h.split(`
24
+ `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Ad(e,t){return t?{...e,responsePagination:t}:e}var Tb=f(()=>{"use strict"});async function me(e,t,n,r){let o=n.concurrency??JL,{results:i,errors:s}=await xb(e,t,o,n.minQueryTimeoutMs);return ZL(n,i,s,e,r)}function ZL(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length),l=Ri(r);t.forEach(y=>{let b=y.result.status;c[y.queryIndex]={id:l[y.queryIndex]??bi(y.originalQuery,y.queryIndex),...b!==void 0?{status:b}:{},data:e_(y.result)}}),n.forEach(y=>{let b=r[y.queryIndex];b&&(c[y.queryIndex]={id:l[y.queryIndex]??bi(b,y.queryIndex),status:"error",data:{error:y.error}})});let u=c.filter(y=>y!==void 0);if(e.finalize){let y=e.finalize({queries:r,results:u,config:e}),b=vd(y.text,o),S=Ad(y.structuredContent,b.pagination);return Eb(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:S,isError:y.isError??(u.length>0&&u.every(k=>k.status==="error"))}}let d={results:u};if(Array.isArray(d.results)){let y=Ea(d.results);y&&(d.base=y);let b=ka(d.results);b&&(d.shared=b)}let m=qn(d,a),p=vd(m,o),h=Ad(xt($n(d)??{}),p.pagination);return Eb(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:h,isError:u.length>0&&u.every(y=>y.status==="error")}}function Eb(e,t,n,r){let o=t.reduce((i,s)=>i+(le(s.result)??j(s.result)),0)+n.reduce((i,s)=>i+j(s),0);try{uu(e,o,r)}catch{}}function e_(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}var JL,kb=f(()=>{"use strict";Ot();Nr();ue();kd();Tb();wd();JL=3});var Ke=f(()=>{"use strict";wd();kb()});var $,Ob,Wn=f(()=>{"use strict";$={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"},Ob={[$.PATH_VALIDATION_FAILED]:{code:$.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[$.FILE_ACCESS_FAILED]:{code:$.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[$.FILE_READ_FAILED]:{code:$.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[$.FILE_TOO_LARGE]:{code:$.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[$.BINARY_FILE_UNSUPPORTED]:{code:$.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[$.NO_MATCHES]:{code:$.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[$.OUTPUT_TOO_LARGE]:{code:$.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[$.COMMAND_NOT_AVAILABLE]:{code:$.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[$.COMMAND_EXECUTION_FAILED]:{code:$.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[$.COMMAND_TIMEOUT]:{code:$.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[$.TOOL_EXECUTION_FAILED]:{code:$.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[$.LSP_SERVER_UNAVAILABLE]:{code:$.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function Ld(e){return e instanceof je}function vb(e,t=$.TOOL_EXECUTION_FAILED,n){if(Ld(e))return e;if(e instanceof Error)return new je(t,e.message,n,e);let r=String(e);return new je(t,r,n)}var je,Oa=f(()=>{"use strict";Wn();je=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Ob[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
25
+ Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}}});function t_(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function N(e,t,n={}){let{extra:r}=n,o={status:"error"};if(t_(e))o.error=e;else if(Ld(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=vb(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:W(o,n.rawResponse)}function ot(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:N(i,t,{toolName:n.toolName})}}var _d=f(()=>{"use strict";Oa();ue()});function xe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:W(s,o.rawResponse)}function va(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return N(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ze(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return N(i,t,{toolName:r})}var De=f(()=>{"use strict";_d();ue()});async function ut({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ze(o,t,r,e)}}var Vn=f(()=>{"use strict";De()});function Fd(e){return e.data!==void 0&&!e.error}var Ab=f(()=>{"use strict"});import{maskSensitiveData as Lb}from"@octocodeai/octocode-engine/mask";function n_(){return yu().provider??gu()}function r_(e){let t=yu(),n=t.provider??gu(),{baseUrl:r,token:o}=t;try{let i=Cd(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=Lb(s);throw new Id(n,`Failed to initialize ${n} provider: ${a}`)}}function dt(e){let t;return()=>t??=r_(e)}function Aa(e,t){return e.capabilities[t]}async function Wt(e,t){let n=await t();return Fd(n)?{ok:!0,response:n}:{ok:!1,result:va(n,e)}}async function _b(e,t){let n=t??n_(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:Lb(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)Fd(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Id,Pn=f(()=>{"use strict";xd();Ab();Xo();De();Id=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});function Ib(e={},t=La){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}var La,Si,Fb,Md=f(()=>{"use strict";La=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Si=[...La,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Fb=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"]});import{spawn as o_}from"child_process";function Kn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=La,maxOutputSize:a=i_}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),m={cwd:o,env:Ib(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=o_(e,t,m)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let h,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{p.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},s_),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),y=()=>{clearTimeout(g),h!==void 0&&(clearTimeout(h),h=void 0)},b=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{p.kill("SIGKILL")}catch{}y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",S=>{if(l.killed)return;let x=S.toString();l.totalOutputSize+=Buffer.byteLength(x),!b()&&l.stdoutChunks.push(x)}),p.stderr?.on("data",S=>{if(l.killed)return;let x=S.toString();l.totalOutputSize+=Buffer.byteLength(x),!b()&&l.stderrChunks.push(x)}),p.on("close",S=>{l.killed||(y(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),p.on("error",S=>{l.killed||(l.killed=!0,y(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function Mb(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var i_,s_,RK,Db=f(()=>{"use strict";Md();i_=10*1024*1024,s_=5e3;RK=1*1024*1024});var _a=f(()=>{"use strict";Md();Db()});import{join as Fa}from"node:path";import{createHash as Nb}from"node:crypto";function Ia(e){return Fa(e,"tmp","clone")}function Ma(e){return Fa(e,"tmp","tree")}function a_(e){return e?`__sp_${Nb("sha256").update(e).digest("hex").substring(0,6)}`:""}function Gb(e){if(!/[\\/]/.test(e))return e;let t=Nb("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function Dd(e,t,n,r,o){let i=`${Gb(r)}${a_(o)}`;return Fa(Ia(e),t,n,i)}function Pi(e,t,n,r){return Fa(Ma(e),t,n,Gb(r))}var Nd=f(()=>{"use strict"});import{existsSync as wi,readFileSync as c_,writeFileSync as l_,mkdirSync as u_,rmSync as xi,readdirSync as d_,statSync as p_}from"node:fs";import{join as Cn}from"node:path";function g_(e){return typeof e=="object"&&e!==null}function y_(e){if(!g_(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 Gd(e){let t=Cn(e,Qb);if(!wi(t))return null;try{return y_(JSON.parse(c_(t,"utf-8")))}catch{return null}}function Gr(e,t){try{l_(Cn(e,Qb),JSON.stringify(t,null,2),"utf-8")}catch{}}function jb(e){return Date.now()<new Date(e.expiresAt).getTime()}function Hr(e){let t=Gd(e);return t?jb(t)?wi(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function b_(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return m_}function R_(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return f_}function S_(){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 h_}function Qr(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+b_()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function xn(e){let t=Cn(e,"..");try{wi(t)||u_(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 Da(e){try{wi(e)&&xi(e,{recursive:!0,force:!0})}catch{}}function Ci(e){try{return p_(e).isDirectory()}catch{return!1}}function Yn(e){try{return d_(e)}catch{return[]}}function*Bb(e){for(let t of Yn(e)){let n=Cn(e,t);if(Ci(n))for(let r of Yn(n)){let o=Cn(n,r);if(Ci(o))for(let i of Yn(o)){let s=Cn(o,i);Ci(s)&&(yield s)}}}}function Hb(e){for(let t of[...Yn(e)]){let n=Cn(e,t);if(Ci(n)){for(let r of[...Yn(n)]){let o=Cn(n,r);if(Ci(o)&&Yn(o).length===0)try{xi(o,{recursive:!0,force:!0})}catch{}}if(Yn(n).length===0)try{xi(n,{recursive:!0,force:!0})}catch{}}}}function P_(e){let t=0;for(let n of Bb(e))try{let r=Gd(n);(!r||!jb(r))&&(xi(n,{recursive:!0,force:!0}),t++)}catch{}return t}function C_(e){let t=[];for(let n of Bb(e)){let r=Gd(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??Vs(n)})}return t}function x_(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{xi(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function zb(e){if(!wi(e))return 0;let t=0;try{t+=P_(e)}catch{return t}Hb(e);let n=x_(C_(e),R_(),S_());return t+=n,n>0&&Hb(e),t}function Ub(e){return zb(Ia(e))}function Na(e){return zb(Ma(e))}var m_,_K,f_,h_,Qb,Ga=f(()=>{"use strict";Ot();Nd();Nd();m_=1440*60*1e3,_K=600*1e3,f_=2*1024*1024*1024,h_=50,Qb=".octocode-clone-meta.json"});import{existsSync as w_,mkdirSync as Hd,renameSync as T_,rmSync as E_}from"fs";import{join as Ti}from"path";import{createHash as k_}from"crypto";async function Vb(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await Q_();let a=e.branch??await We(r,o,t),c=wr(),l=Dd(c,r,o,a,i);return __(c,l,async()=>{let u=Hr(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Ub(c),xn(l);let d=H_(t,n),m=I_(c,l);Da(m);try{if(i){if(await G_(r,o,a,m,i,d),!w_(Ti(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await N_(r,o,a,m,d);let p=Qr(r,o,a,"clone",i);return Gr(m,p),M_(m,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw Da(m),p}})}async function __(e,t,n){xn(t);let r=F_(e,t);Hd(Ti(e,"tmp",qb),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Hd(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>v_)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await D_(A_)}try{return await n()}finally{E_(r,{recursive:!0,force:!0})}}function Kb(e){return k_("sha256").update(e).digest("hex").slice(0,16)}function F_(e,t){return Ti(e,"tmp",qb,Kb(t))}function I_(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Ti(e,"tmp",L_);return Hd(r,{recursive:!0,mode:448}),Ti(r,`${Kb(t)}-${n}`)}function M_(e,t){Da(t),xn(t),T_(e,t)}function D_(e){return new Promise(t=>setTimeout(t,e))}async function N_(e,t,n,r,o){let i=Xb(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Yb(e,t),r),await Qd(i,$b,`full clone of ${e}/${t}`,o)}async function G_(e,t,n,r,o,i){let s=Xb(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Yb(e,t),r),await Qd(s,$b,`sparse clone of ${e}/${t}`,i),await Qd(["-C",r,"sparse-checkout","set","--skip-checks","--",o],O_,`sparse-checkout set ${o}`,void 0)}function Yb(e,t){return`https://github.com/${e}/${t}.git`}function Xb(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function H_(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function Q_(){try{if(!(await Kn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Wb,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function j_(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function Qd(e,t,n,r){let o=await Kn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Wb,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=j_(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var $b,O_,v_,A_,qb,L_,Wb,Jb=f(()=>{"use strict";Ot();Ae();_a();Ga();$b=120*1e3,O_=30*1e3,v_=300*1e3,A_=100,qb="clone-locks",L_="clone-tmp",Wb=[...Si,"GIT_TERMINAL_PROMPT"]});async function Zb(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>ut({toolName:v.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Aa(s,"cloneRepo"))return ze(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",v.GITHUB_CLONE_REPO);let a;try{a=await Vb(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return N(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=Vs(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return xe(o,d,!0,v.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:v.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","location","error"]},e)}var eR=f(()=>{"use strict";Ot();pe();Ke();De();Vn();Pn();Jb()});import{readdirSync as B_,statSync as tR}from"node:fs";import{join as z_}from"node:path";function zd(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function oR(e){return Object.values(e).every(t=>t===0)}function Ud(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 iR(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 q_(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function q_(e,t){try{let o=new URL(e);if(!$_.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(),U_);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 sR(e,t){let n=[],r=0;function o(i){let s;try{s=B_(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=z_(i,a);try{let l=tR(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 aR(e){try{return tR(e).size}catch{return 0}}var Ei,Ha,jd,nR,U_,rR,Bd,$_,Qa=f(()=>{"use strict";Ei=50,Ha=5*1024*1024,jd=300*1024,nR=5,U_=1e4,rR=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"]),Bd={maxDirectoryFiles:Ei,maxTotalSize:Ha,maxFileSize:jd};$_=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});import{writeFileSync as W_,mkdirSync as cR,existsSync as $d,rmSync as V_}from"node:fs";import{join as lR,dirname as K_,resolve as uR,sep as dR}from"node:path";async function qd(e,t,n,r,o,i=!1){let s=wr(),a=Pi(s,e,t,r),c=uR(lR(a,n));if(!c.startsWith(a+dR)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Hr(a);if(l.hit&&!i&&$d(c)){let A=sR(c,a),q=zd();return{localPath:c,repoRoot:a,files:A.files,fileCount:A.fileCount,totalSize:A.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:A.fileCount,eligibleFileCount:A.fileCount,savedFileCount:A.fileCount,skipped:q,limits:Bd,warnings:Ud(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await ie(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let p=m,h=zd(),g=[];for(let A of p){if(A.type!=="file"){h.nonFile+=1;continue}if(!A.download_url){h.missingDownloadUrl+=1;continue}if(A.size>jd){h.oversized+=1;continue}let q=Yg(A.name,{lowercase:!0,leadingDot:!0});if(rR.has(q)){h.binary+=1;continue}g.push(A)}h.fileLimit=Math.max(0,g.length-Ei);let y=g.slice(0,Ei),b=o?.token,S=await iR(y,nR,b);h.fetchFailed=y.length-S.length;let x=0,k=[];for(let A=0;A<S.length;A+=1){let{entry:q,content:H}=S[A];if(x+H.length>Ha){h.totalSizeLimit=S.length-A;break}x+=H.length,k.push({entry:q,content:H})}Na(s),xn(a),$d(c)&&V_(c,{recursive:!0,force:!0}),cR(c,{recursive:!0,mode:448});let E=[];for(let{entry:A,content:q}of k){let H=uR(lR(a,A.path));if(!H.startsWith(a+dR)){h.pathTraversal+=1;continue}let K=K_(H);$d(K)||cR(K,{recursive:!0,mode:448}),W_(H,q,"utf-8"),E.push({path:A.path,size:q.length,type:"file"})}let _=Qr(e,t,r,"treeFetch",void 0,void 0,d);Gr(a,_);let w=oR(h),G=w,M=h.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:x,complete:w,verified:G,...d?{commitSha:d}:{},...M?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:h,limits:Bd,warnings:Ud(w,G),cached:!1,expiresAt:_.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}var pR=f(()=>{"use strict";Ot();Ae();Ga();ii();Qa()});import{writeFileSync as Y_,mkdirSync as X_,existsSync as mR}from"node:fs";import{join as J_,dirname as Z_,resolve as eF,sep as tF}from"node:path";async function Wd(e,t,n,r,o,i=!1){let s=wr(),a=Pi(s,e,t,r),c=eF(J_(a,n));if(!c.startsWith(a+tF)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Hr(a);if(!i&&l.hit&&mR(c))return{localPath:c,repoRoot:a,path:n,size:aR(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await ci({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let h="error"in u?u.error:void 0;throw new Error(h||`Failed to fetch ${e}/${t}/${n}`)}Na(s),xn(a);let d=Z_(c);mR(d)||X_(d,{recursive:!0,mode:448}),Y_(c,u.data.rawContent,"utf-8");let m=u.data.branch||r,p=Qr(e,t,m,"treeFetch");return Gr(a,p),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}var fR=f(()=>{"use strict";Ot();Vu();Ga();Qa()});var hR=f(()=>{"use strict";Qa();pR();fR()});function ja(e,t){return e&&t?`${e}/${t}`:void 0}function Ba(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function za(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}var Ua=f(()=>{"use strict"});function rF(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function gR(e){return{keywords:e.keywords??[],projectId:ja(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function yR(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=Ba(a),u=`${c}/${l}`,d=s,m=o.get(u);if(m||(m={id:u,owner:c,repo:l,matches:[]},o.set(u,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let p=!0,h=!1;for(let g of s.matches){if(!g.context)continue;let y={path:s.path,value:rF(g.context)};g.positions?.length>0&&(y.matchIndices=g.positions.map(([b,S])=>({start:b,end:S,lineOffset:(g.context??"").substring(0,b).split(`
26
+ `).length-1}))),r&&p&&d.url&&(y.url=d.url,p=!1),m.matches.push(y),h=!0}h||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...za(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}var bR=f(()=>{"use strict";ae();Ua()});function RR(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function SR(e){return e.map(t=>{let{owner:n,repo:r}=Ba(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}var PR=f(()=>{"use strict";Ua()});function $a(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}var Vd=f(()=>{"use strict"});function CR(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map($a),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ja(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function oF(e,t){let n=[];t.some(o=>o.state==="APPROVED")&&n.push("approval"),t.some(o=>o.state==="CHANGES_REQUESTED")&&n.push("changes-requested");let r=e.filter(o=>!Un(o.author??"")).map(o=>o.body.toLowerCase());return n.length===0&&r.some(o=>/\b(lgtm|looks good|approved|ship it)\b/.test(o))&&n.push("approval"),!n.includes("changes-requested")&&r.some(o=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(o))&&n.push("changes-requested"),r.some(o=>o.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function iF(e,t){if(!e||e.length===0)return;let n=Array.from(new Set(e.map(i=>i.author))),r=e.map(i=>i.updatedAt||i.createdAt).filter(Boolean).sort().at(-1),o=e.filter(i=>i.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:o,discussionComments:e.length-o,commenters:n.slice(0,8),...r?{latestCommentAt:r}:{},themes:oF(e,t??[])}}function xR(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=iF(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...za(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}var wR=f(()=>{"use strict";ae();Vd();Ra();Ua()});function TR(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function ER(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}var kR=f(()=>{"use strict"});function Kd(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Sn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function OR(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([m],[p])=>m==="."?-1:p==="."?1:m.localeCompare(p)).map(([m,p])=>({dir:m,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[m,p]of Object.entries(c))if(n[m]){let h=new Set(n[m].files);for(let[g,y]of Object.entries(p))if(h.has(g)){let b=m==="."?g:`${m}/${g}`;l[b]=y}}}let u=Object.values(n).reduce((m,p)=>(m.totalFiles+=p.files.length,m.totalFolders+=p.folders.length,m),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var vR=f(()=>{"use strict";hi()});var jr=f(()=>{"use strict";bR();PR();wR();kR();vR()});function qa(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function sF(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:qa(t.status),retryAfterSeconds:qa(t.retryAfter),rateLimitRemaining:qa(t.rateLimitRemaining),rateLimitReset:qa(t.rateLimitReset)}}return{message:"Provider error"}}function Wa(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=sF(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function Va(e,t,n){let r=qn(e,[...t]);return{structuredContent:xt($n(e)??{}),text:r,isError:n}}var Yd=f(()=>{"use strict";Nr()});function Ka(e){return typeof e=="object"&&e!==null}function pt(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function AR(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function wt(e,t){return Ye(e[t])??0}function aF(e){if(Ka(e))return{nonFile:wt(e,"nonFile"),missingDownloadUrl:wt(e,"missingDownloadUrl"),oversized:wt(e,"oversized"),binary:wt(e,"binary"),fileLimit:wt(e,"fileLimit"),fetchFailed:wt(e,"fetchFailed"),totalSizeLimit:wt(e,"totalSizeLimit"),pathTraversal:wt(e,"pathTraversal")}}function cF(e){if(Ka(e))return{maxDirectoryFiles:wt(e,"maxDirectoryFiles"),maxTotalSize:wt(e,"maxTotalSize"),maxFileSize:wt(e,"maxFileSize")}}function uF(e){if(!Ka(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of lF){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function dF(e,t){return _s("ghGetFileContent",{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,...t.minify!==void 0?{minify:t.minify}:{}},e)}function pF(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"lspGetSemantics (definitions/references) only works on local files \u2014 clone this path locally, then run localSearchCode or lspGetSemantics on it",confidence:"exact"}}function LR(e,t){let n=uF(e.pagination),r={...dF(n,t),cloneForSemantics:pF(t)};return{path:pt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:pt(e.localPath),repoRoot:pt(e.repoRoot),...Ye(e.fileSize)!==void 0?{fileSize:Ye(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:Ye(e.totalLines),sourceChars:Ye(e.sourceChars),sourceBytes:Ye(e.sourceBytes),resolvedBranch:pt(e.resolvedBranch),pagination:n,next:r,...e.isPartial===!0?{isPartial:!0}:{},startLine:Ye(e.startLine),endLine:Ye(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:pt(e.lastModified),lastModifiedBy:pt(e.lastModifiedBy),warnings:AR(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:pt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function _R(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Ka).map(c=>({path:pt(c.path)??"",size:Ye(c.size)??0,type:pt(c.type)??"file"})),o=aF(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:pt(e.localPath)??"",repoRoot:pt(e.repoRoot),fileCount:Ye(e.fileCount)??r.length,totalSize:Ye(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ye(e.directoryEntryCount),eligibleFileCount:Ye(e.eligibleFileCount),savedFileCount:Ye(e.savedFileCount),skipped:o,limits:cF(e.limits),warnings:AR(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:pt(e.resolvedBranch)}}var lF,FR=f(()=>{"use strict";Be();lF=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});function mF(e,t){return`${e}/${t}`}function fF(e,t,n){let r=mF(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function hF(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=fF(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(_R(c,o)),a.directories=u;return}let l=a.files??[];l.push(LR(c,o)),a.files=l}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function gF(e,t){return Wa(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function IR(){return({queries:e,results:t})=>{let n=new Map,r=Ri(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=hF(t,n),i=gF(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Va(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}var MR=f(()=>{"use strict";Yd();Ke();FR()});async function DR(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{let s=ot(Fn,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?yF(a,n,c):bF(a,n,c)}catch(s){return ze(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:IR()},e)}async function yF(e,t,n){if(!Aa(n,"fetchDirectoryToDisk"))return ze(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",v.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return N("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await We(e.owner,e.repo,t),o=await qd(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return xe(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??j(o)})}async function bF(e,t,n){let r=await Wt(e,()=>n.provider.getFileContent(TR(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await RF(e,t):void 0,i={...ER(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return xe(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function RF(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await We(e.owner,e.repo,t);return Wd(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var NR=f(()=>{"use strict";pe();Ke();De();Ol();hR();Ae();ue();jr();Pn();MR()});function ki(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function GR(e,t){let n=ki(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function HR(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{},...t?.repoState?{repoState:t.repoState}:{}}}function SF(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function PF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function CF(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${PF(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function xF(e,t){return{...e,matches:t}}function Xd(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?SF(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:CF(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:xF(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}var Ya=f(()=>{"use strict"});function jR(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function QR(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function BR(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:QR(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:QR(r.get(i)),...s?{pagination:s}:{}}}})}function zR(e,t,n){let r=ki(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),l=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!l)continue;let u=e.length===1?"getLines":`getLines:${i.id}`;o[u]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:l},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"heuristic"}}return Object.keys(o).length>0?o:void 0}var UR=f(()=>{"use strict";Ya()});function Jd(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=ki(e);t.forEach((x,k)=>{if(x.status==="error")return;let E=HR(x);E.repoState&&s.push({id:x.id,state:E.repoState,query:a.get(x.id)}),E.incompleteResults&&(i=!0),E.results.reduce((G,M)=>G+M.matches.length,0)===0&&o.push({id:x.id,...E.nonExistentScope?{nonExistentScope:!0}:{},...E.incompleteResults?{incompleteResults:!0}:{}});let w=E.results;n.push({id:x.id,groups:w}),E.pagination&&r.set(x.id,E.pagination)});let c=Array.from(new Set(e.flatMap(x=>{let k=x.keywords;return Array.isArray(k)?k.filter(E=>typeof E=="string"):[]}))),l=Xd(jR(n),c),u=Wa(t),d=e.some(x=>x.concise===!0),m=BR(e,l,r),p=zR(m,e,c);if(d)for(let x of m)x.data.files=x.data.files.map(k=>`${k.owner}/${k.repo}:${k.path}`);let h={results:m,...p?{next:p}:{}};o.length>0&&(h.emptyQueries=o.map(({id:x,nonExistentScope:k,incompleteResults:E})=>({id:x,...k?{nonExistentScope:k}:{},...E?{incompleteResults:E}:{}}))),u.length>0&&(h.errors=u);let g=[],y=(x,k,E="warning")=>{h.warnings=[...h.warnings??[],k],g.push({level:E,code:x,message:k})};i&&y("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&GR(o,e)&&y("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let b=8,S=o.filter(({id:x,nonExistentScope:k,incompleteResults:E})=>{if(k||E)return!1;let _=a.get(x)?.keywords;return Array.isArray(_)&&_.length>b});S.length>0&&y("ghQueryPossiblyTooComplex",`Quer${S.length>1?"ies":"y"} ${S.map(x=>x.id).join(", ")} used more than ${b} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:x,state:k,query:E}of s)if(k.kind==="renamed"){let[_,w]=k.fullName.split("/");y("ghRepoRenamed",`Query ${x}: the repository was RENAMED to ${k.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let G=E?.keywords;h.next={...h.next??{},[`retryRenamed:${x}`]:{tool:"ghSearchCode",query:{owner:_,repo:w,...Array.isArray(G)?{keywords:G}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else k.kind==="archived"?y("ghRepoArchived",`Query ${x}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):y("ghRepoNotFound",`Query ${x}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`,"error");return g.length>0&&(h.diagnostics=g),Va(h,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],l.length===0&&u.length>0)}}var $R=f(()=>{"use strict";Yd();Ya();UR()});var qR=f(()=>{"use strict";Ya();$R()});function wF(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function TF(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function EF(e,t,n){try{let r=await ie(n),{data:o}=await r.rest.repos.get({owner:e,repo:t}),i=`${e}/${t}`.toLowerCase();return o.full_name&&o.full_name.toLowerCase()!==i?{kind:"renamed",fullName:o.full_name}:o.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function WR(e){let{queries:t}=e,n=dt(e.authInfo);return me(t,async(r,o)=>{try{let i=TF(r);if(i)return N(i.error,r);if(!wF(r))return N("At least one search term or scope filter is required.",r);let s=n(),a=await Wt(r,()=>s.provider.searchCode(gR(r)));if(a.ok===!1)return a.result;let c=yR(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let l=await EF(String(r.owner),String(r.repo),e.authInfo);l&&(c.repoState=l)}return xe(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ze(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:Jd()},e)}var VR=f(()=>{"use strict";pe();Ke();Ae();De();jr();Pn();qR()});function Br(e){return e?e.includes('rel="next"'):!1}async function OF(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}function KR(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function YR(e,t,n){let r=await He(t),o=ke("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return Qe(o,()=>vF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function vF(e,t){try{let n=await ie(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=Br(i),a=o.data.map(u=>{let d=u.commit.author,m=u.commit.committer,p=m?.date??d?.date??"",h=u.commit.message,g=h.split(`
27
27
  `)[0]??h,y=h.slice(g.length).trim(),b=y.length>500,S=y.length===0?g:`${g}
28
- ${b?`${y.slice(0,500)}\u2026`:y}`,x=m?.name===d?.name&&m?.email===d?.email||u.committer?.login==="web-flow";return{sha:u.sha,date:p,...S===g?{}:{message:S},...b?{messageTruncated:!0}:{},messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...m&&!x?{committer:{name:m.name??"unknown",email:m.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await EF(a,TF,async(u,d)=>{try{let m=o.data[d]?.sha??u.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let h=e.path,g=p.data.files?.find(y=>y.filename===h||y.previous_filename===h);if(g){let y=g.patch!==void 0?KR(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...y!==void 0?{patch:y.patch,...y.patchPagination?{patchPagination:y.patchPagination}:{},diff:ui(y.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let h=e.path,g=(p.data.files??[]).filter(w=>!h||w.filename.startsWith(h)).map(w=>{let G=w.patch!==void 0?KR(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...G!==void 0?{patch:G.patch,...G.patchPagination?{patchPagination:G.patchPagination}:{},diff:ui(G.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),y=Math.max(1,e.filePage??1),b=Math.max(1,e.itemsPerPage??20),S=g.length,x=Math.max(1,Math.ceil(S/b)),k=Math.min(y,x),E=(k-1)*b,_=g.slice(E,E+b);return{...u,files:_,filesPagination:{currentPage:k,totalPages:x,itemsPerPage:b,totalFiles:S,hasMore:k<x,...k<x?{nextFilePage:k+1}:{}}}}}catch{}return u});return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return ne(n)}}var TF,Xa=f(()=>{"use strict";Ae();rt();pa();lt();TF=5});async function XR(e,t,n){let r=await He(t),o=ke("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,auth:r},n);return Qe(o,()=>OF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function OF(e,t){try{let n=await ie(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},url:c.html_url})),a=jr(r.headers.link);return{data:{type:"releases",owner:e.owner,repo:e.repo,releases:s,...i?{latest:{tagName:i.tag_name,...i.published_at?{publishedAt:i.published_at}:{}}}:{},pagination:{currentPage:e.page,perPage:e.perPage,hasMore:a,...a?{nextPage:e.page+1}:{}}},status:200}}catch(n){return ne(n)}}var JR=f(()=>{"use strict";Ae();rt();Xa();lt()});async function ZR(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for releases mode.",e);let o=r.perPage!==void 0&&r.perPage!==Zd?r.perPage:r.limit!==void 0&&r.limit!==30?r.limit:r.perPage??Zd,i=await XR({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:Number(o)||Zd},n);if(At(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=i.data.releases.length>0||i.data.latest!==void 0,a=i.data.pagination?.nextPage,c={...i.data,...a!==void 0?{next:{nextPage:{tool:"ghHistoryResearch",query:{type:"releases",owner:r.owner,repo:r.repo,page:a,perPage:o},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return xe(e,c,s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var Zd,eS=f(()=>{"use strict";pe();De();JR();Lr();ae();Zd=30});function It(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function ep(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map($a),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function tS(e,t,n){if(!n&&!t)return{text:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{text:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Ja(e){return e.pull_request!=null}function vF(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function Za(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:vF(e.labels),created_at:e.created_at??"",updated_at:e.updated_at??"",...e.closed_at?{closed_at:e.closed_at}:{},url:e.html_url??""}}function Br(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function tp(e,t,n="anon"){return ke("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:ep(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,locked:e.locked,visibility:e.visibility,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}var ec=f(()=>{"use strict";Vd();lt()});import{ContentSanitizer as nS}from"@octocodeai/octocode-engine/contentSanitizer";async function rS(e,t){let n=It(e.owner),r=It(e.repo),o=e.issueNumber;if(!n||!r||o==null)return Br("owner, repo, and issueNumber are required for issue detail mode.");let i=await ie(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(Ja(s.data))return Br(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,l=e.content?.comments?.includeBots===!0,u=Za(s.data),d={};if(a){let m=nS.sanitizeContent(s.data.body??"").content,p=tS(m,e.charOffset,e.charLength);u.body=p.text,p.pagination&&(d.body=p.pagination)}if(c){let m=Math.max(1,e.commentPage??1),p=Math.max(1,e.itemsPerPage??30),h=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=l?h.data:h.data.filter(b=>!Un(b.user?.login??""));u.comments=g.map(b=>({id:String(b.id),user:b.user?.login??"unknown",body:nS.sanitizeContent(b.body??"").content,created_at:b.created_at??"",updated_at:b.updated_at??"",commentType:"discussion"}));let y=jr(h.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:u.comments.length,hasMore:y,...y?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(u.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[u],total_count:1},status:200}}async function oS(e,t,n){let r=It(t.owner)??"",o=It(t.repo)??"",i=await ie(n),s=_u(e),a=Math.min(t.limit??30,100),c=t.page??1,l=t.sort&&t.sort!=="best-match"?t.sort:void 0,u=await i.rest.search.issuesAndPullRequests({q:s,sort:l,order:t.order||"desc",per_page:a,page:c}),d=(u.data.items??[]).filter(h=>!Ja(h)).map(h=>Za(h)),m=u.data.total_count??d.length,p=c*a<m&&d.length===a;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?d.map(h=>`#${h.number} ${h.title}`):d,total_count:m,effectiveQuery:s,...u.data.incomplete_results?{incomplete_results:!0}:{},pagination:{currentPage:c,perPage:a,hasMore:p,...p?{nextPage:c+1}:{},totalMatches:m,reportedTotalMatches:m,totalMatchesKind:"reported"}},status:200}}async function iS(e,t){let n=It(e.owner),r=It(e.repo);if(!n||!r)return Br("owner and repo are required for issues mode.");let o=await ie(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),l=c.data.filter(d=>!Ja(d)).map(d=>Za(d)),u=jr(c.headers.link);return{data:{type:"issues",owner:n,repo:r,issues:e.concise?l.map(d=>`#${d.number} ${d.title}`):l,total_count:l.length,pagination:{currentPage:s,perPage:i,hasMore:u,...u?{nextPage:s+1}:{}}},status:200}}var sS=f(()=>{"use strict";Ae();Ra();Xa();kr();ae();ec()});async function np(e,t,n){let r=await He(t),o=tp(e,n,r);return Qe(o,()=>AF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function AF(e,t){try{if(e.state==="merged")return Br('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await rS(e,t);let n={...e,query:ep(e)};return Fu(n)?await oS(n,e,t):await iS(e,t)}catch(n){return vt(n)?{data:{type:"issues",owner:It(e.owner)??"",repo:It(e.repo)??"",issues:[],total_count:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:ne(n)}}var aS=f(()=>{"use strict";Ae();rt();kr();lt();ae();ec();sS()});var cS=f(()=>{"use strict";ec();aS()});async function lS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await np({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,involves:r.involves,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,interactions:r.interactions,locked:r.locked,visibility:r.visibility,"no-assignee":r["no-assignee"],"no-label":r["no-label"],"no-milestone":r["no-milestone"],"no-project":r["no-project"],match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(At(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let u=a[0];if(typeof u=="number")return u;if(typeof u=="string"){let d=u.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(u&&typeof u=="object"&&typeof u.number=="number")return u.number})(),l={};return o==null&&c!=null&&(l.readIssue={tool:"ghHistoryResearch",query:{type:"issues",owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"heuristic"}),l.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"heuristic"},xe(e,{...i.data,next:l},s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var uS=f(()=>{"use strict";pe();De();cS();Lr()});async function dS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for commits mode.",e);let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return N("path is required when querying a specific file in commits mode.",e);let s=await YR({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,page:Number(r.page)||1,perPage:Number(r.perPage)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof r.itemsPerPage=="number"?r.itemsPerPage:void 0,includeDiff:!!r.includeDiff,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);if(At(s))return N(s,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:a}=s.data,c=a.length>0,l=a.map(d=>d.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),u={...s.data,...l?{next:{prDetail:{tool:"ghHistoryResearch",query:{type:"prs",owner:r.owner,repo:r.repo,prNumber:Number(l)},why:`Open PR #${l} referenced by the first commit for review context`,confidence:"heuristic"}}}:{}};return xe(e,u,c,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:s.rawResponseChars})}var pS=f(()=>{"use strict";pe();De();Xa();Lr()});function LF(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function _F(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function FF(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function mS(e){let{content:t,reviewMode:n}=e,r=LF(t,n),o=_F(t,n),i=FF(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}var fS=f(()=>{"use strict"});function ki(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function zr(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Oi(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function Xn(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function tc(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function rp(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function IF(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function vi(e,t,n){return IF({...rp(e,t),...n})}function op(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return vi(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function nc(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return vi(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Ur(e){return typeof e=="object"&&e!==null}function rc(e){if(Ur(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function oc(e){if(Ur(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}var Ai=f(()=>{"use strict";ae()});function MF(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function hS(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=MF(r,n.comments),i=ki(t),s=i?o.filter(l=>zr(l.body,i)):o,{items:a,pagination:c}=Oi(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=Xn(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:tc(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function gS(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=ki(t);return{reviews:(o?r.filter(s=>zr(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Xn(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function yS(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Oi(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}var bS=f(()=>{"use strict";ae();Ai()});function ic(e){return String(e.path??e.filename??"")}function DF(e,t){return{path:ic(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function NF(e){return e.split(`
28
+ ${b?`${y.slice(0,500)}\u2026`:y}`,x=m?.name===d?.name&&m?.email===d?.email||u.committer?.login==="web-flow";return{sha:u.sha,date:p,...S===g?{}:{message:S},...b?{messageTruncated:!0}:{},messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...m&&!x?{committer:{name:m.name??"unknown",email:m.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await OF(a,kF,async(u,d)=>{try{let m=o.data[d]?.sha??u.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let h=e.path,g=p.data.files?.find(y=>y.filename===h||y.previous_filename===h);if(g){let y=g.patch!==void 0?KR(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...y!==void 0?{patch:y.patch,...y.patchPagination?{patchPagination:y.patchPagination}:{},diff:di(y.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let h=e.path,g=(p.data.files??[]).filter(w=>!h||w.filename.startsWith(h)).map(w=>{let G=w.patch!==void 0?KR(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...G!==void 0?{patch:G.patch,...G.patchPagination?{patchPagination:G.patchPagination}:{},diff:di(G.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),y=Math.max(1,e.filePage??1),b=Math.max(1,e.itemsPerPage??20),S=g.length,x=Math.max(1,Math.ceil(S/b)),k=Math.min(y,x),E=(k-1)*b,_=g.slice(E,E+b);return{...u,files:_,filesPagination:{currentPage:k,totalPages:x,itemsPerPage:b,totalFiles:S,hasMore:k<x,...k<x?{nextFilePage:k+1}:{}}}}}catch{}return u});return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return ne(n)}}var kF,Xa=f(()=>{"use strict";Ae();rt();pa();lt();kF=5});async function XR(e,t,n){let r=await He(t),o=ke("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,auth:r},n);return Qe(o,()=>AF(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function AF(e,t){try{let n=await ie(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},url:c.html_url})),a=Br(r.headers.link);return{data:{type:"releases",owner:e.owner,repo:e.repo,releases:s,...i?{latest:{tagName:i.tag_name,...i.published_at?{publishedAt:i.published_at}:{}}}:{},pagination:{currentPage:e.page,perPage:e.perPage,hasMore:a,...a?{nextPage:e.page+1}:{}}},status:200}}catch(n){return ne(n)}}var JR=f(()=>{"use strict";Ae();rt();Xa();lt()});async function ZR(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for releases mode.",e);let o=r.perPage!==void 0&&r.perPage!==Zd?r.perPage:r.limit!==void 0&&r.limit!==30?r.limit:r.perPage??Zd,i=await XR({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:Number(o)||Zd},n);if(At(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=i.data.releases.length>0||i.data.latest!==void 0,a=i.data.pagination?.nextPage,c={...i.data,...a!==void 0?{next:{nextPage:{tool:"ghHistoryResearch",query:{type:"releases",owner:r.owner,repo:r.repo,page:a,perPage:o},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return xe(e,c,s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var Zd,eS=f(()=>{"use strict";pe();De();JR();_r();ae();Zd=30});function It(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function ep(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map($a),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function tS(e,t,n){if(!n&&!t)return{text:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{text:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Ja(e){return e.pull_request!=null}function LF(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function Za(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:LF(e.labels),created_at:e.created_at??"",updated_at:e.updated_at??"",...e.closed_at?{closed_at:e.closed_at}:{},url:e.html_url??""}}function zr(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function tp(e,t,n="anon"){return ke("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:ep(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,locked:e.locked,visibility:e.visibility,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}var ec=f(()=>{"use strict";Vd();lt()});import{ContentSanitizer as nS}from"@octocodeai/octocode-engine/contentSanitizer";async function rS(e,t){let n=It(e.owner),r=It(e.repo),o=e.issueNumber;if(!n||!r||o==null)return zr("owner, repo, and issueNumber are required for issue detail mode.");let i=await ie(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(Ja(s.data))return zr(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,l=e.content?.comments?.includeBots===!0,u=Za(s.data),d={};if(a){let m=nS.sanitizeContent(s.data.body??"").content,p=tS(m,e.charOffset,e.charLength);u.body=p.text,p.pagination&&(d.body=p.pagination)}if(c){let m=Math.max(1,e.commentPage??1),p=Math.max(1,e.itemsPerPage??30),h=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=l?h.data:h.data.filter(b=>!Un(b.user?.login??""));u.comments=g.map(b=>({id:String(b.id),user:b.user?.login??"unknown",body:nS.sanitizeContent(b.body??"").content,created_at:b.created_at??"",updated_at:b.updated_at??"",commentType:"discussion"}));let y=Br(h.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:u.comments.length,hasMore:y,...y?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(u.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[u],total_count:1},status:200}}async function oS(e,t,n){let r=It(t.owner)??"",o=It(t.repo)??"",i=await ie(n),s=_u(e),a=Math.min(t.limit??30,100),c=t.page??1,l=t.sort&&t.sort!=="best-match"?t.sort:void 0,u=await i.rest.search.issuesAndPullRequests({q:s,sort:l,order:t.order||"desc",per_page:a,page:c}),d=(u.data.items??[]).filter(h=>!Ja(h)).map(h=>Za(h)),m=u.data.total_count??d.length,p=c*a<m&&d.length===a;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?d.map(h=>`#${h.number} ${h.title}`):d,total_count:m,effectiveQuery:s,...u.data.incomplete_results?{incomplete_results:!0}:{},pagination:{currentPage:c,perPage:a,hasMore:p,...p?{nextPage:c+1}:{},totalMatches:m,reportedTotalMatches:m,totalMatchesKind:"reported"}},status:200}}async function iS(e,t){let n=It(e.owner),r=It(e.repo);if(!n||!r)return zr("owner and repo are required for issues mode.");let o=await ie(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),l=c.data.filter(d=>!Ja(d)).map(d=>Za(d)),u=Br(c.headers.link);return{data:{type:"issues",owner:n,repo:r,issues:e.concise?l.map(d=>`#${d.number} ${d.title}`):l,total_count:l.length,pagination:{currentPage:s,perPage:i,hasMore:u,...u?{nextPage:s+1}:{}}},status:200}}var sS=f(()=>{"use strict";Ae();Ra();Xa();Or();ae();ec()});async function np(e,t,n){let r=await He(t),o=tp(e,n,r);return Qe(o,()=>_F(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function _F(e,t){try{if(e.state==="merged")return zr('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await rS(e,t);let n={...e,query:ep(e)};return Fu(n)?await oS(n,e,t):await iS(e,t)}catch(n){return vt(n)?{data:{type:"issues",owner:It(e.owner)??"",repo:It(e.repo)??"",issues:[],total_count:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:ne(n)}}var aS=f(()=>{"use strict";Ae();rt();Or();lt();ae();ec();sS()});var cS=f(()=>{"use strict";ec();aS()});async function lS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await np({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,involves:r.involves,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,interactions:r.interactions,locked:r.locked,visibility:r.visibility,"no-assignee":r["no-assignee"],"no-label":r["no-label"],"no-milestone":r["no-milestone"],"no-project":r["no-project"],match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(At(i))return N(i,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let u=a[0];if(typeof u=="number")return u;if(typeof u=="string"){let d=u.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(u&&typeof u=="object"&&typeof u.number=="number")return u.number})(),l={};return o==null&&c!=null&&(l.readIssue={tool:"ghHistoryResearch",query:{type:"issues",owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"heuristic"}),l.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"heuristic"},xe(e,{...i.data,next:l},s,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:i.rawResponseChars})}var uS=f(()=>{"use strict";pe();De();cS();_r()});async function dS(e,t,n){let r=t;if(!r.owner||!r.repo)return N("owner and repo are required for commits mode.",e);let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return N("path is required when querying a specific file in commits mode.",e);let s=await YR({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,page:Number(r.page)||1,perPage:Number(r.perPage)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof r.itemsPerPage=="number"?r.itemsPerPage:void 0,includeDiff:!!r.includeDiff,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);if(At(s))return N(s,e,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:a}=s.data,c=a.length>0,l=a.map(d=>d.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),u={...s.data,...l?{next:{prDetail:{tool:"ghHistoryResearch",query:{type:"prs",owner:r.owner,repo:r.repo,prNumber:Number(l)},why:`Open PR #${l} referenced by the first commit for review context`,confidence:"heuristic"}}}:{}};return xe(e,u,c,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:s.rawResponseChars})}var pS=f(()=>{"use strict";pe();De();Xa();_r()});function FF(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function IF(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function MF(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function mS(e){let{content:t,reviewMode:n}=e,r=FF(t,n),o=IF(t,n),i=MF(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}var fS=f(()=>{"use strict"});function Oi(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Ur(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function vi(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function Xn(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function tc(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function rp(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function DF(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Ai(e,t,n){return DF({...rp(e,t),...n})}function op(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Ai(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function nc(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Ai(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function $r(e){return typeof e=="object"&&e!==null}function rc(e){if($r(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function oc(e){if($r(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}var Li=f(()=>{"use strict";ae()});function NF(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function hS(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=NF(r,n.comments),i=Oi(t),s=i?o.filter(l=>Ur(l.body,i)):o,{items:a,pagination:c}=vi(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=Xn(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:tc(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function gS(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Oi(t);return{reviews:(o?r.filter(s=>Ur(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Xn(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function yS(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=vi(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}var bS=f(()=>{"use strict";ae();Li()});function ic(e){return String(e.path??e.filename??"")}function GF(e,t){return{path:ic(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function HF(e){return e.split(`
29
29
  `).filter(t=>{if(!t.startsWith("+"))return!0;let n=t.slice(1).trim();return n!==""&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")}).map(t=>t.startsWith("+")?"+"+t.slice(1).replace(/\s*\/\/.*$/,"").trimEnd():t).join(`
30
- `)}function RS(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(ic(p))):o,a=ki(t),c=a?s.filter(p=>zr(ic(p),a)||zr(p.patch,a)):s,{items:l,pagination:u}=Oi(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=l.map(p=>{let h=DF(p,!1);if(!d||typeof p.patch!="string")return h;let g=r&&!a?NF(p.patch):p.patch,y=Xn(g,t.charOffset??0,t.charLength??12e3);return{...h,patch:y?.content??"",diff:ui(y?.content),...y?{patchPagination:y.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(ic).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}var SS=f(()=>{"use strict";ae();pa();Ai()});function Jn(e,t){return{...e,content:t}}function GF(e,t){return{...e,...t}}function PS(e,t,n,r){let o=rp(e,t);return{target:o,...n.body?{}:{getBody:Jn(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:Jn(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:Jn(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:Jn(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:Jn(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:Jn(o,{reviews:!0})},...n.commits?{}:{getCommits:Jn(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:GF(o,{reviewMode:"full"})}}}var CS=f(()=>{"use strict";Ai()});function HF(e){return e.replace(/\n{3,}/g,`
30
+ `)}function RS(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(ic(p))):o,a=Oi(t),c=a?s.filter(p=>Ur(ic(p),a)||Ur(p.patch,a)):s,{items:l,pagination:u}=vi(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=l.map(p=>{let h=GF(p,!1);if(!d||typeof p.patch!="string")return h;let g=r&&!a?HF(p.patch):p.patch,y=Xn(g,t.charOffset??0,t.charLength??12e3);return{...h,patch:y?.content??"",diff:di(y?.content),...y?{patchPagination:y.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(ic).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}var SS=f(()=>{"use strict";ae();pa();Li()});function Jn(e,t){return{...e,content:t}}function QF(e,t){return{...e,...t}}function PS(e,t,n,r){let o=rp(e,t);return{target:o,...n.body?{}:{getBody:Jn(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:Jn(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:Jn(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:Jn(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:Jn(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:Jn(o,{reviews:!0})},...n.commits?{}:{getCommits:Jn(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:QF(o,{reviewMode:"full"})}}}var CS=f(()=>{"use strict";Li()});function jF(e){return e.replace(/\n{3,}/g,`
31
31
 
32
- `)}function QF(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function jF(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Ur(n))continue;let r=oc(n.patchPagination);if(r?.hasMore)return r}}function BF(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Ur(n))continue;let r=oc(n.bodyPagination);if(r?.hasMore)return r}}function zF(e,t,n,r){let o={},i=oc(e.bodyPagination),s=rc(e.filePagination),a=rc(e.commentPagination),c=rc(e.commitPagination),l=jF(e),u=BF(e),d=QF(n);i&&(o.body={...i,nextQuery:op(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:nc(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:nc(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:vi(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:nc(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:op(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return Ur(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?vi(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function UF(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function xS(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?HF(s):s,c=n.body?Xn(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,p=RS(e,t,n,r),h=Array.isArray(p.changedFiles)?p.changedFiles.find(S=>S.path)?.path:void 0,y={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:tc(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:PS(t,i,n,h)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...p,...hS(e,t,n),...gS(e,t,n),...yS(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},b=zF(y,t,n,i);return UF(y),b&&(y.contentPagination=b),y}var wS=f(()=>{"use strict";bS();SS();CS();Ai()});async function TS(e,t,n){let r=n(),o={...t},i=mS(o),s=o.prNumber!==void 0;if(s||(o.content=void 0,o.reviewMode=void 0),!(o.keywordsToSearch?.length||o.owner||o.repo||o.author||o.assignee||o.prNumber&&o.owner&&o.repo))return N("At least one valid search parameter, filter, or PR number is required.",e);let c=await Wt(o,()=>r.provider.searchPullRequests(CR(o)));if(c.ok===!1)return c.result;let l=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:u,resultData:d}=xR(c.response.data,{includeFileChanges:l});o.prNumber!==void 0&&delete d.pagination;let m=!s&&(!!e.content||!!e.reviewMode),p={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},h=o.minify==="standard",g=!0,y=u.map(S=>xS(S,o,m?p:i,h,g));d.pull_requests=y,!s&&o.concise===!0&&(d.pull_requests=y.map(S=>{let x=S;return`#${x.number} ${x.title}`}));let b=y.length>0;return xe(o,d,b,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}var ES=f(()=>{"use strict";pe();De();Qr();Pn();fS();wS()});async function kS(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{let s=ot(In,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?ZR(o,s.data,n):a==="issues"?lS(o,s.data,n):a==="commits"?dS(o,s.data,n):TS(o,s.data,r)}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","total_count","error"]},e)}var OS=f(()=>{"use strict";pe();Ke();De();Pn();eS();uS();pS();ES();vl()});function AS(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function LS(e){return!!(e.keywords&&e.keywords.length>0)}function _S(e){return!!(LS(e)||AS(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function vS(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function FS(e){let t=AS(e),n=LS(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:vS(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:vS(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}var IS=f(()=>{"use strict"});function MS(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var DS=f(()=>{"use strict"});function GS(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function HS(e,t){return[...e].sort((n,r)=>{let o=$F(n,r,t.sort);if(o!==0)return o;let i=NS(r,t)-NS(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:ip(n).localeCompare(ip(r))})}function $F(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return MS(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function NS(e,t){let n=qF(t),r=ip(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function qF(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function ip(e){return`${e.owner}/${e.repo}`}var QS=f(()=>{"use strict";DS()});function sp(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function ap(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function cp(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function jS(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??j(n.response.data??n.response)),0)}var lp=f(()=>{"use strict";ue()});function WF(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt?t.createdAt.slice(0,10):void 0,updatedAt:t.updatedAt?t.updatedAt.slice(0,10):void 0,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function VF(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"heuristic"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"heuristic"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(WF),...o?{next:o}:{}}}}async function BS(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{if(!_S(o))return N("At least one repository search term or filter is required.",o);let s=r(),a=FS(o),{successes:c,failures:l}=await _b(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(RR(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?va(w.response,o):ze(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=HS(GS(u.flatMap(w=>SR(w.response.data.repositories))),o),h=m!=null?p.slice(0,m):p,g=u.length===1?u[0]:void 0,b=u.length>1?cp(u,p.length):g?.response.data.pagination,S=b?sp(b):void 0,x=h.length>0,k=VF({repositories:h,pagination:S},o),E=ap(d),_=E?{...k.data,warnings:E}:k.data;return xe(o,_,x,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:jS([...u,...d])})}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var zS=f(()=>{"use strict";pe();Ke();De();Qr();Pn();IS();QS();lp();lp()});function KF(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function YF(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&ri(o))continue;let i=r.files.filter(a=>!Or(a)),s=r.folders.filter(a=>!ri(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function US(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,l=c??await s.provider.resolveDefaultBranch(a),u=await Wt(o,()=>s.provider.getRepoStructure(Kd(o,l))),d=l,m;if(u.ok===!1&&c){let x=u.result.error;if((typeof x=="object"&&x!==null?x.status:void 0)===404){let E=await s.provider.resolveDefaultBranch(a);if(E!==c){let _=await Wt(o,()=>s.provider.getRepoStructure(Kd(o,E)));_.ok!==!1&&(u=_,d=E,m=`Branch/ref '${c}' was not found. Showing '${E}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(u.ok===!1)return KF(u.result,o);let p=YF(u.response.data.structure),h=Object.keys(p).length>0,g=OR(u.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let b=g.structure?.find(x=>(x.files?.length??0)>0),S=b?b.dir==="."?b.files[0]:`${b.dir}/${b.files[0]}`:void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...o.branch?{branch:o.branch}:{}},why:"Read the first listed file",confidence:"heuristic"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...o.branch?{branch:o.branch}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},xe(o,g,h,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return ze(s,o,"Failed to explore repository structure",v.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:v.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var $S=f(()=>{"use strict";pe();Ke();oi();De();Qr();Pn()});import{existsSync as qS}from"fs";import{delimiter as XF,dirname as JF,join as WS}from"path";function VS(){return process.platform==="win32"?"npm.cmd":"npm"}function ZF(){let e=JF(process.execPath);return WS(e,VS())}function eI(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function tI(){let e=(process.env.PATH??"").split(XF).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...eI()])]}function nI(){let e=ZF();if(qS(e))return{command:process.execPath,argsPrefix:[e]};let t=VS();for(let n of tI()){let r=WS(n,t);if(qS(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function Zn(e,t,n={}){if(!rI.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Mb(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=nI(),c=await Kn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:oI});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var rI,oI,Li=f(()=>{"use strict";_a();rI=["view","search","ping","config","whoami"],oI=[...Ri,...Fb]});async function ac(){if(sc)return sc;try{let e=await Zn("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return sc=t,t}}catch{}return sc=$r,$r}var $r,sc,_i=f(()=>{"use strict";Li();$r="https://registry.npmjs.org",sc=null});function Ii(e){try{return new URL(e).host||e}catch{return e}}function KS(e,t=Date.now()){let n=Fi.get(Ii(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<up)throw new dp(Ii(e),up-r);n.state="half-open"}}function pp(e){let t=Fi.get(Ii(e));t&&(t.failures=0,t.state="closed")}function YS(e,t=Date.now()){let n=Ii(e),r=Fi.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=iI&&(r.state="open",r.openedAt=t)),Fi.set(n,r)}function XS(e,t=Date.now()){let n=Fi.get(Ii(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<up:!1}var Fi,iI,up,dp,mp=f(()=>{"use strict";Fi=new Map,iI=5,up=3e4;dp=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});import{z as L}from"zod";var cc,sI,JS,aI,lc=f(()=>{"use strict";cc=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),sI=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),JS=L.looseObject({objects:L.array(sI),total:L.union([L.number(),L.string()]).optional()}),aI=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});function ZS(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function lI(e,t,n,r){e&&Rn({limit_type:"primary",retry_after_seconds:ZS(r),api_method:t,api_url:n,provider:e})}function uI(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(qo.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Lg(r),e.status===429&&lI(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function dI(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=ZS(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Mt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=cI,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let y=e.includes("?")?"&":"?";d=`${e}${y}version=${encodeURIComponent(Bn)}`}let m={"User-Agent":`Octocode-MCP/${Bn}`,...i},p=globalThis.fetch;if(!p)throw new Error(qo.FETCH_NOT_AVAILABLE.message);KS(d);let h,g=n+1;for(let y=1;y<=g;y++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(d,{method:s,headers:m,signal:c});if(!b.ok)throw uI(b,s,d,u,l);if(b.status===204)return pp(d),null;let S=await b.json();return pp(d),S}catch(b){let S=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw b;if(h=b instanceof Error?b:new Error(String(b)),y===g)break;let x=dI(y,r,o,S);await new Promise(k=>setTimeout(k,x))}}throw YS(d),new Error(qo.FETCH_FAILED_AFTER_RETRIES.message(g,h?.message||""))}var cI,uc=f(()=>{"use strict";Ks();at();Xs();mp();cI=6e4});function wn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function Ve(e){return e===void 0?0:j(e)}async function dc(e){try{let t=`${pI}/${encodeURIComponent(e)}`,n=await Mt(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Ve(n)}}catch{return{rawResponseChars:0}}}function eP(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function tP(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function mI(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function pc(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=wn(e.repository):(e.repository.url&&(r=wn(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:mI(e),...o?{repositoryDirectory:o}:{},...eP(e.exports)?{exports:eP(e.exports)}:{},...tP(e.bin,e.name)?{bin:tP(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function fI(e){return typeof e.links?.repository=="string"?wn(e.links.repository):typeof e.repository=="string"?wn(e.repository):typeof e.repository?.url=="string"?wn(e.repository.url):null}function nP(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:fI(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function fp(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function rP(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}var pI,hp=f(()=>{"use strict";uc();ue();pI="https://api.npmjs.org/downloads/point/last-week"});function gp(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}async function yp(e){try{let t=await ac(),n=fp(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Mt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ve(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Mt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ve(i)}}catch{return{rawResponseChars:0}}}async function fc(e,t,n){let[r,o]=await Promise.all([dc(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):yp(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function mc(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function gI(e,t){try{let n=await Zn("view",[e,"--json"],{timeout:hI});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...mc(c)?{}:{errorDetail:c},rawResponseChars:Ve(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Ve(o),s=cc.safeParse(o);return s.success?{pkg:pc(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...mc(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function yI(e,t){try{let n=await ac(),r=fp(e),o=`${n}/${r}/latest`,i;try{i=await Mt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Ve(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=cc.safeParse(i);return a.success?{pkg:pc(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...mc(r)?{}:{errorDetail:r},rawResponseChars:0}}}function bI(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function bp(e,t){let n=0,r;for(let o of bI(e)){let i;try{i=await Mt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);mc(l)||(r=l);continue}if(n+=Ve(i),!i||typeof i!="object")continue;let s=cc.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:pc(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function hc(e,t=!1){let[n,r]=await Promise.allSettled([gI(e,t),yI(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?fc(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function oP(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await hc(e,t);if(!r){if(o){let s=gp(o);if(s&&n){let a=await bp(e,t);if(a.pkg){let c=await fc(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}var hI,Rp=f(()=>{"use strict";Li();uc();lc();_i();hp();hI=3e3});async function RI(e,t,n,r=0){let o=Math.max(t+r,t),i=await Zn("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Ve(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Ve(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((h,g)=>{let y=h?.score?.final??0;return(g?.score?.final??0)-y}).slice(r,r+t),d=await Promise.all(u.map(async h=>{if(!h||typeof h!="object")return null;let g=h;if(!g.name)return null;if(n){let y=await hc(g.name,!0);if(y.pkg)return y}return{pkg:nP(g),rawResponseChars:0}})),m=d.map(h=>h?.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function SI(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${$r}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Mt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(h){return{error:`NPM registry search failed: ${h instanceof Error?h.message:String(h)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ve(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=JS.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((h,g)=>{let y=h.score?.final??0;return(g.score?.final??0)-y}).map(h=>h.package).filter(h=>typeof h.name=="string"&&h.name.length>0).slice(0,t),d=await Promise.all(u.map(async h=>{if(n){let g=await hc(h.name,!0);if(g.pkg)return g}return{pkg:{name:h.name,npmUrl:(h.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(h.name)}`,repoUrl:h.links?.repository&&typeof h.links.repository=="string"?wn(h.links.repository):null,version:h.version??"unknown",source:"registry",...h.description?{description:h.description}:{},...h.links?.homepage?{homepage:h.links.homepage}:{}},rawResponseChars:0}})),m=d.map(h=>h.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+g.rawResponseChars,0);return{packages:m,totalFound:rP(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Sp(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await Mt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Ve(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ve(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?wn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Ve(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Pp(e,t,n,r=0){try{let o=await RI(e,t,n,r);if(!("error"in o))return o}catch{}return SI(e,t,n,r)}async function Cp(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):dc(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):yp(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}var iP=f(()=>{"use strict";Li();uc();lc();_i();hp();Rp()});function Mi(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function sP(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function xp(e,t,n,r=0){let o=ke("npm-search",{name:e,limit:t,metadata:n,from:r});return Qe(o,async()=>{if(XS($r)){if(r===0&&t===1&&Mi(e)){let u=await bp(e,n);if(u.pkg){let d=await fc(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await Sp(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Mi(e)){let l=await oP(e,n,t===1);if("error"in l){if(!gp(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Pp(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Cp(s);let a=sP(e);if(a!==e){let l=await Pp(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return Cp(l)}let c=await Sp(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}var aP=f(()=>{"use strict";Li();lt();mp();lc();_i();Rp();iP()});var cP=f(()=>{"use strict";_i();aP()});async function lP(e){let t=Mi(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return xp(e.name,n,!0,r)}var uP=f(()=>{"use strict";cP()});function CI(e){return"error"in e}function gc(e){return"npmUrl"in e}function xI(e){return gc(e)&&e.path?e.path:e.name}function wI(e){return gc(e)?e.repoUrl:e.repository}function TI(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function EI(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function wp(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function dP(e,t){let n=wp(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghHistoryResearch",query:{type:"releases",owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function kI(e){let t=xI(e),n=EI(wI(e)),r={name:t};gc(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=TI(gc(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=dP(n,o);if(i&&(r.next=i),r.version&&wp(n)){let s=`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`;r.warnings=[s],r.diagnostics=[{level:"warning",code:"npmRepoTagDivergence",message:s}]}return r}function OI(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=wp(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:dP(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function vI(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function pP(e){return me(e.queries,async t=>{try{if(!t.packageName)return N("Package name is required for package search",t);let n=await lP({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(CI(n))return N(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(kI),i=o.length>0,s=r.length>1||n.totalFound>1,a=vI(t,n.totalFound,o.length,s),l={...OI(o),pagination:a};return xe(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return N(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var mP=f(()=>{"use strict";uP();Ke();De();pe()});import{redactPath as Di}from"@octocodeai/octocode-engine/pathUtils";var fP=f(()=>{"use strict"});var mt,yc=f(()=>{"use strict";Oa();Wn();fP();mt={pathValidationFailed:(e,t,n)=>new je($.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Di(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Di(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new je($.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new je($.FILE_READ_FAILED,`Failed to read file: ${Di(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new je($.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new je($.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Di(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new je($.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new je($.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 je($.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new je($.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});import hP from"path";import{pathValidator as AI}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as LI}from"@octocodeai/config";function ft(e,t){if(!e.path?.trim()){let s=mt.pathValidationFailed("","path is required");return{isValid:!1,errorResult:N(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||LI().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=hP.isAbsolute(r)?r:hP.resolve(n,r),i=AI.validate(o);if(!i.isValid){let s=mt.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:N(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}var Vt=f(()=>{"use strict";yc();_d()});var Dt,Ni=f(()=>{"use strict";Dt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function gP(e,t){return n=>t}var yP=f(()=>{"use strict"});import{open as _I,readFile as FI,stat as II}from"fs/promises";function Tp(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ep(e,t,n){return{...e,...Tp(t,n)}}function bP(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function RP(e,t){try{return{fileStats:await II(t)}}catch(n){let r=mt.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function SP(e,t){return t>Dt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function PP(e,t,n){let r=mt.fileTooLarge(e.path,n,Dt.LARGE_FILE_THRESHOLD_KB);return N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function CP(e,t){let n=mt.binaryFileUnsupported(e.path);return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function xP(e){let n=Buffer.alloc(8192),r;try{r=await _I(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(gP("binary sample handle close",void 0))}}async function wP(e,t){try{return{content:await FI(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?mt.fileAccessFailed(e.path,r):mt.fileReadFailed(e.path,r);return{errorResult:N(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function TP(e,t){return{status:"empty",errorCode:$.NO_MATCHES,totalLines:t}}var bc=f(()=>{"use strict";Ni();pe();Vt();yc();Wn();yP()});function MI(e,t,n){let r=oa(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:TP(e,n)};let o=r.lines.join(`
33
- `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(l=m.start,u=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function DI(e){return e.startLine!==void 0&&e.endLine!==void 0}function NI(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:$.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:$.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
34
- `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function EP(e,t,n){let r=t.split(`
35
- `),o=_t(t);return e.matchString?MI(e,r,o):DI(e)?NI(e,r,o):{resultContent:t,isPartial:!1}}var kP=f(()=>{"use strict";Ku();_r();Wn();bc()});async function OP(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",d=s;if(s!==void 0){let g=await da(e,l,s,r);u=g.chunkMode,d=g.length}let m=ca(e,l,d,s!==void 0?{pageSize:s}:void 0),p;if(m.hasMore&&u==="char-limit"&&la(m.paginatedContent)){let g=m.charOffset+m.charLength;p=await ua(e,g,r)}let h=_s("localGetFileContent",{path:r,charLength:s??m.charLength,minify:t.minify},m);return{windowedContent:m.paginatedContent,pagination:m,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:p,next:h,showPagination:s!==void 0||i>0||a}}async function vP(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=await OP(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,contentView:s,...d&&{isPartial:d},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...Ju(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}async function kp(e,t,n,r,o,i,s){let a=await OP(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...Tp(r,o),...a.showPagination&&{pagination:{...Ju(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function AP(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}var LP=f(()=>{"use strict";Ee();Zu();ed();Be();bc()});import{ContentSanitizer as GI}from"@octocodeai/octocode-engine/contentSanitizer";async function Rc(e){let t=zn();try{let n=ft(e,v.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=bP(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await RP(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await xP(o))return W(CP(e,o),c);if(SP(e,l))return W(PP(e,o,l),c);let{content:u,errorResult:d}=await wP(e,o);if(d||u===void 0)return d;let m=GI.sanitizeContent(u,i),p=m.content,h=p.length,g=Buffer.byteLength(p,"utf-8"),y=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,b=e.minify,S=b==="standard"||b==="symbols",x=S?"standard":"none",k;if(b==="symbols"){let M=D.extractSignatures(p,i);if(M===null){let A=ia(p,i);if(A!==null)return W(await kp(e,A,_t(p),h,g,y,t),h);k=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(M!==null){let A=_t(p),q=D.applyContentViewMinification(M,i);return W(await kp(e,q,A,h,g,y,t),h)}}let E=_t(p),_=EP(e,p,t),w=M=>{let A=[...k?[k]:[],...y?[y]:[]];if(A.length===0)return M;let q=M.warnings??[];return{...M,warnings:[...q,...A]}};if(_.earlyResult){let M=_.earlyResult.content,A=S&&typeof M=="string"?{..._.earlyResult,content:D.applyContentViewMinification(M,i)}:_.earlyResult;return W(Ep(w(Op(AP(A,x),e,E)),h,g),h)}let G=await vP(e,_,s,E,t,S,x);return W(Ep(w(Op(G,e,E)),h,g),h)}catch(n){return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT})}}function Op(e,t,n){return e}var Sc=f(()=>{"use strict";Ee();_r();aa();pe();Vt();ue();sa();bc();kP();LP()});async function _P(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=ot(Mn,n);return r.ok===!1?r.error:await Rc(r.data)}}),{toolName:v.LOCAL_FETCH_CONTENT,finalize:HI()},e)}function HI(){return({results:e})=>{let t={results:QI(e)},n=Ea(t.results);n&&(t.base=n);let r=ka(t.results);return r&&(t.shared=r),{structuredContent:xt(t),text:jI(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function QI(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function jI(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=qn({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(qn({shared:e.shared},["shared"]).trimEnd()),t.join(`
32
+ `)}function BF(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function zF(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!$r(n))continue;let r=oc(n.patchPagination);if(r?.hasMore)return r}}function UF(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!$r(n))continue;let r=oc(n.bodyPagination);if(r?.hasMore)return r}}function $F(e,t,n,r){let o={},i=oc(e.bodyPagination),s=rc(e.filePagination),a=rc(e.commentPagination),c=rc(e.commitPagination),l=zF(e),u=UF(e),d=BF(n);i&&(o.body={...i,nextQuery:op(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:nc(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:nc(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:Ai(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:nc(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:op(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return $r(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Ai(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function qF(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function xS(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?jF(s):s,c=n.body?Xn(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,m=t.prNumber!==void 0||t.verbose===!0,p=RS(e,t,n,r),h=Array.isArray(p.changedFiles)?p.changedFiles.find(S=>S.path)?.path:void 0,y={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:tc(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:PS(t,i,n,h)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...p,...hS(e,t,n),...gS(e,t,n),...yS(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},b=$F(y,t,n,i);return qF(y),b&&(y.contentPagination=b),y}var wS=f(()=>{"use strict";bS();SS();CS();Li()});async function TS(e,t,n){let r=n(),o={...t},i=mS(o),s=o.prNumber!==void 0;if(s||(o.content=void 0,o.reviewMode=void 0),!(o.keywordsToSearch?.length||o.owner||o.repo||o.author||o.assignee||o.prNumber&&o.owner&&o.repo))return N("At least one valid search parameter, filter, or PR number is required.",e);let c=await Wt(o,()=>r.provider.searchPullRequests(CR(o)));if(c.ok===!1)return c.result;let l=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:u,resultData:d}=xR(c.response.data,{includeFileChanges:l});o.prNumber!==void 0&&delete d.pagination;let m=!s&&(!!e.content||!!e.reviewMode),p={...i,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},h=o.minify==="standard",g=!0,y=u.map(S=>xS(S,o,m?p:i,h,g));d.pull_requests=y,!s&&o.concise===!0&&(d.pull_requests=y.map(S=>{let x=S;return`#${x.number} ${x.title}`}));let b=y.length>0;return xe(o,d,b,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}var ES=f(()=>{"use strict";pe();De();jr();Pn();fS();wS()});async function kS(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{let s=ot(In,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?ZR(o,s.data,n):a==="issues"?lS(o,s.data,n):a==="commits"?dS(o,s.data,n):TS(o,s.data,r)}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","total_count","error"]},e)}var OS=f(()=>{"use strict";pe();Ke();De();Pn();eS();uS();pS();ES();vl()});function AS(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function LS(e){return!!(e.keywords&&e.keywords.length>0)}function _S(e){return!!(LS(e)||AS(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function vS(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function FS(e){let t=AS(e),n=LS(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:vS(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:vS(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}var IS=f(()=>{"use strict"});function MS(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var DS=f(()=>{"use strict"});function GS(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function HS(e,t){return[...e].sort((n,r)=>{let o=WF(n,r,t.sort);if(o!==0)return o;let i=NS(r,t)-NS(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:ip(n).localeCompare(ip(r))})}function WF(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return MS(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function NS(e,t){let n=VF(t),r=ip(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function VF(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function ip(e){return`${e.owner}/${e.repo}`}var QS=f(()=>{"use strict";DS()});function sp(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function ap(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function cp(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function jS(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??j(n.response.data??n.response)),0)}var lp=f(()=>{"use strict";ue()});function KF(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt?t.createdAt.slice(0,10):void 0,updatedAt:t.updatedAt?t.updatedAt.slice(0,10):void 0,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function YF(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"heuristic"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"heuristic"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(KF),...o?{next:o}:{}}}}async function BS(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{if(!_S(o))return N("At least one repository search term or filter is required.",o);let s=r(),a=FS(o),{successes:c,failures:l}=await _b(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(RR(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?va(w.response,o):ze(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=HS(GS(u.flatMap(w=>SR(w.response.data.repositories))),o),h=m!=null?p.slice(0,m):p,g=u.length===1?u[0]:void 0,b=u.length>1?cp(u,p.length):g?.response.data.pagination,S=b?sp(b):void 0,x=h.length>0,k=YF({repositories:h,pagination:S},o),E=ap(d),_=E?{...k.data,warnings:E}:k.data;return xe(o,_,x,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:jS([...u,...d])})}catch(s){return ze(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var zS=f(()=>{"use strict";pe();Ke();De();jr();Pn();IS();QS();lp();lp()});function XF(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function JF(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&oi(o))continue;let i=r.files.filter(a=>!vr(a)),s=r.folders.filter(a=>!oi(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function US(e){let{queries:t,authInfo:n}=e,r=dt(n);return me(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,l=c??await s.provider.resolveDefaultBranch(a),u=await Wt(o,()=>s.provider.getRepoStructure(Kd(o,l))),d=l,m;if(u.ok===!1&&c){let x=u.result.error;if((typeof x=="object"&&x!==null?x.status:void 0)===404){let E=await s.provider.resolveDefaultBranch(a);if(E!==c){let _=await Wt(o,()=>s.provider.getRepoStructure(Kd(o,E)));_.ok!==!1&&(u=_,d=E,m=`Branch/ref '${c}' was not found. Showing '${E}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(u.ok===!1)return XF(u.result,o);let p=JF(u.response.data.structure),h=Object.keys(p).length>0,g=OR(u.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let b=g.structure?.find(x=>(x.files?.length??0)>0),S=b?b.dir==="."?b.files[0]:`${b.dir}/${b.files[0]}`:void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...o.branch?{branch:o.branch}:{}},why:"Read the first listed file",confidence:"heuristic"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...o.branch?{branch:o.branch}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},xe(o,g,h,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return ze(s,o,"Failed to explore repository structure",v.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:v.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var $S=f(()=>{"use strict";pe();Ke();ii();De();jr();Pn()});import{existsSync as qS}from"fs";import{delimiter as ZF,dirname as eI,join as WS}from"path";function VS(){return process.platform==="win32"?"npm.cmd":"npm"}function tI(){let e=eI(process.execPath);return WS(e,VS())}function nI(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function rI(){let e=(process.env.PATH??"").split(ZF).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...nI()])]}function oI(){let e=tI();if(qS(e))return{command:process.execPath,argsPrefix:[e]};let t=VS();for(let n of rI()){let r=WS(n,t);if(qS(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function Zn(e,t,n={}){if(!iI.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Mb(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=oI(),c=await Kn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:sI});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var iI,sI,_i=f(()=>{"use strict";_a();iI=["view","search","ping","config","whoami"],sI=[...Si,...Fb]});async function ac(){if(sc)return sc;try{let e=await Zn("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return sc=t,t}}catch{}return sc=qr,qr}var qr,sc,Fi=f(()=>{"use strict";_i();qr="https://registry.npmjs.org",sc=null});function Mi(e){try{return new URL(e).host||e}catch{return e}}function KS(e,t=Date.now()){let n=Ii.get(Mi(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<up)throw new dp(Mi(e),up-r);n.state="half-open"}}function pp(e){let t=Ii.get(Mi(e));t&&(t.failures=0,t.state="closed")}function YS(e,t=Date.now()){let n=Mi(e),r=Ii.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=aI&&(r.state="open",r.openedAt=t)),Ii.set(n,r)}function XS(e,t=Date.now()){let n=Ii.get(Mi(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<up:!1}var Ii,aI,up,dp,mp=f(()=>{"use strict";Ii=new Map,aI=5,up=3e4;dp=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});import{z as L}from"zod";var cc,cI,JS,lI,lc=f(()=>{"use strict";cc=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),cI=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),JS=L.looseObject({objects:L.array(cI),total:L.union([L.number(),L.string()]).optional()}),lI=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});function ZS(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function dI(e,t,n,r){e&&Rn({limit_type:"primary",retry_after_seconds:ZS(r),api_method:t,api_url:n,provider:e})}function pI(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Wo.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Lg(r),e.status===429&&dI(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function mI(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=ZS(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Mt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=uI,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let y=e.includes("?")?"&":"?";d=`${e}${y}version=${encodeURIComponent(Bn)}`}let m={"User-Agent":`Octocode-MCP/${Bn}`,...i},p=globalThis.fetch;if(!p)throw new Error(Wo.FETCH_NOT_AVAILABLE.message);KS(d);let h,g=n+1;for(let y=1;y<=g;y++){if(c?.aborted)throw new Error("Request aborted");try{let b=await p(d,{method:s,headers:m,signal:c});if(!b.ok)throw pI(b,s,d,u,l);if(b.status===204)return pp(d),null;let S=await b.json();return pp(d),S}catch(b){let S=b;if(c?.aborted||b instanceof Error&&b.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw b;if(h=b instanceof Error?b:new Error(String(b)),y===g)break;let x=mI(y,r,o,S);await new Promise(k=>setTimeout(k,x))}}throw YS(d),new Error(Wo.FETCH_FAILED_AFTER_RETRIES.message(g,h?.message||""))}var uI,uc=f(()=>{"use strict";Ks();at();Xs();mp();uI=6e4});function wn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function Ve(e){return e===void 0?0:j(e)}async function dc(e){try{let t=`${fI}/${encodeURIComponent(e)}`,n=await Mt(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Ve(n)}}catch{return{rawResponseChars:0}}}function eP(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function tP(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function hI(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function pc(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=wn(e.repository):(e.repository.url&&(r=wn(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:hI(e),...o?{repositoryDirectory:o}:{},...eP(e.exports)?{exports:eP(e.exports)}:{},...tP(e.bin,e.name)?{bin:tP(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function gI(e){return typeof e.links?.repository=="string"?wn(e.links.repository):typeof e.repository=="string"?wn(e.repository):typeof e.repository?.url=="string"?wn(e.repository.url):null}function nP(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:gI(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function fp(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function rP(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}var fI,hp=f(()=>{"use strict";uc();ue();fI="https://api.npmjs.org/downloads/point/last-week"});function gp(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}async function yp(e){try{let t=await ac(),n=fp(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Mt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ve(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Mt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ve(i)}}catch{return{rawResponseChars:0}}}async function fc(e,t,n){let[r,o]=await Promise.all([dc(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):yp(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function mc(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function bI(e,t){try{let n=await Zn("view",[e,"--json"],{timeout:yI});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...mc(c)?{}:{errorDetail:c},rawResponseChars:Ve(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Ve(o),s=cc.safeParse(o);return s.success?{pkg:pc(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...mc(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function RI(e,t){try{let n=await ac(),r=fp(e),o=`${n}/${r}/latest`,i;try{i=await Mt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Ve(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=cc.safeParse(i);return a.success?{pkg:pc(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...mc(r)?{}:{errorDetail:r},rawResponseChars:0}}}function SI(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function bp(e,t){let n=0,r;for(let o of SI(e)){let i;try{i=await Mt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);mc(l)||(r=l);continue}if(n+=Ve(i),!i||typeof i!="object")continue;let s=cc.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:pc(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function hc(e,t=!1){let[n,r]=await Promise.allSettled([bI(e,t),RI(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?fc(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function oP(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await hc(e,t);if(!r){if(o){let s=gp(o);if(s&&n){let a=await bp(e,t);if(a.pkg){let c=await fc(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}var yI,Rp=f(()=>{"use strict";_i();uc();lc();Fi();hp();yI=3e3});async function PI(e,t,n,r=0){let o=Math.max(t+r,t),i=await Zn("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Ve(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Ve(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((h,g)=>{let y=h?.score?.final??0;return(g?.score?.final??0)-y}).slice(r,r+t),d=await Promise.all(u.map(async h=>{if(!h||typeof h!="object")return null;let g=h;if(!g.name)return null;if(n){let y=await hc(g.name,!0);if(y.pkg)return y}return{pkg:nP(g),rawResponseChars:0}})),m=d.map(h=>h?.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function CI(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${qr}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Mt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(h){return{error:`NPM registry search failed: ${h instanceof Error?h.message:String(h)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ve(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=JS.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((h,g)=>{let y=h.score?.final??0;return(g.score?.final??0)-y}).map(h=>h.package).filter(h=>typeof h.name=="string"&&h.name.length>0).slice(0,t),d=await Promise.all(u.map(async h=>{if(n){let g=await hc(h.name,!0);if(g.pkg)return g}return{pkg:{name:h.name,npmUrl:(h.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(h.name)}`,repoUrl:h.links?.repository&&typeof h.links.repository=="string"?wn(h.links.repository):null,version:h.version??"unknown",source:"registry",...h.description?{description:h.description}:{},...h.links?.homepage?{homepage:h.links.homepage}:{}},rawResponseChars:0}})),m=d.map(h=>h.pkg).filter(h=>!!h),p=d.reduce((h,g)=>h+g.rawResponseChars,0);return{packages:m,totalFound:rP(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function Sp(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await Mt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Ve(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ve(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?wn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Ve(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Pp(e,t,n,r=0){try{let o=await PI(e,t,n,r);if(!("error"in o))return o}catch{}return CI(e,t,n,r)}async function Cp(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):dc(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):yp(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}var iP=f(()=>{"use strict";_i();uc();lc();Fi();hp();Rp()});function Di(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function sP(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function xp(e,t,n,r=0){let o=ke("npm-search",{name:e,limit:t,metadata:n,from:r});return Qe(o,async()=>{if(XS(qr)){if(r===0&&t===1&&Di(e)){let u=await bp(e,n);if(u.pkg){let d=await fc(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await Sp(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Di(e)){let l=await oP(e,n,t===1);if("error"in l){if(!gp(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await Pp(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Cp(s);let a=sP(e);if(a!==e){let l=await Pp(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return Cp(l)}let c=await Sp(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}var aP=f(()=>{"use strict";_i();lt();mp();lc();Fi();Rp();iP()});var cP=f(()=>{"use strict";Fi();aP()});async function lP(e){let t=Di(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return xp(e.name,n,!0,r)}var uP=f(()=>{"use strict";cP()});function wI(e){return"error"in e}function gc(e){return"npmUrl"in e}function TI(e){return gc(e)&&e.path?e.path:e.name}function EI(e){return gc(e)?e.repoUrl:e.repository}function kI(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function OI(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function wp(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function dP(e,t){let n=wp(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghHistoryResearch",query:{type:"releases",owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function vI(e){let t=TI(e),n=OI(EI(e)),r={name:t};gc(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=kI(gc(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=dP(n,o);if(i&&(r.next=i),r.version&&wp(n)){let s=`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`;r.warnings=[s],r.diagnostics=[{level:"warning",code:"npmRepoTagDivergence",message:s}]}return r}function AI(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=wp(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:dP(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function LI(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function pP(e){return me(e.queries,async t=>{try{if(!t.packageName)return N("Package name is required for package search",t);let n=await lP({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(wI(n))return N(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(vI),i=o.length>0,s=r.length>1||n.totalFound>1,a=LI(t,n.totalFound,o.length,s),l={...AI(o),pagination:a};return xe(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return N(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var mP=f(()=>{"use strict";uP();Ke();De();pe()});import{redactPath as Ni}from"@octocodeai/octocode-engine/pathUtils";var fP=f(()=>{"use strict"});var mt,yc=f(()=>{"use strict";Oa();Wn();fP();mt={pathValidationFailed:(e,t,n)=>new je($.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Ni(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Ni(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new je($.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new je($.FILE_READ_FAILED,`Failed to read file: ${Ni(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new je($.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new je($.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Ni(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new je($.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new je($.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 je($.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new je($.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});import hP from"path";import{pathValidator as gP}from"@octocodeai/octocode-engine/pathValidator";import{getConfigSync as yP}from"@octocodeai/config";function _I(e=yP().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&gP.addAllowedRoot(t)}function ft(e,t){if(!e.path?.trim()){let s=mt.pathValidationFailed("","path is required");return{isValid:!1,errorResult:N(s,e,{toolName:t})}}_I();let n=process.env.WORKSPACE_ROOT?.trim()||yP().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=hP.isAbsolute(r)?r:hP.resolve(n,r),i=gP.validate(o);if(!i.isValid){let s=mt.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:N(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}var Vt=f(()=>{"use strict";yc();_d()});var Dt,Gi=f(()=>{"use strict";Dt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function bP(e,t){return n=>t}var RP=f(()=>{"use strict"});import{open as FI,readFile as II,stat as MI}from"fs/promises";function Tp(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ep(e,t,n){return{...e,...Tp(t,n)}}function SP(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function PP(e,t){try{return{fileStats:await MI(t)}}catch(n){let r=mt.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function CP(e,t){return t>Dt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function xP(e,t,n){let r=mt.fileTooLarge(e.path,n,Dt.LARGE_FILE_THRESHOLD_KB);return N(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function wP(e,t){let n=mt.binaryFileUnsupported(e.path);return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function TP(e){let n=Buffer.alloc(8192),r;try{r=await FI(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(bP("binary sample handle close",void 0))}}async function EP(e,t){try{return{content:await II(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?mt.fileAccessFailed(e.path,r):mt.fileReadFailed(e.path,r);return{errorResult:N(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function kP(e,t){return{status:"empty",errorCode:$.NO_MATCHES,totalLines:t}}var bc=f(()=>{"use strict";Gi();pe();Vt();yc();Wn();RP()});function DI(e,t,n){let r=oa(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:kP(e,n)};let o=r.lines.join(`
33
+ `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(l=m.start,u=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function NI(e){return e.startLine!==void 0&&e.endLine!==void 0}function GI(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:$.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:$.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
34
+ `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function OP(e,t,n){let r=t.split(`
35
+ `),o=_t(t);return e.matchString?DI(e,r,o):NI(e)?GI(e,r,o):{resultContent:t,isPartial:!1}}var vP=f(()=>{"use strict";Ku();Fr();Wn();bc()});async function AP(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",d=s;if(s!==void 0){let g=await da(e,l,s,r);u=g.chunkMode,d=g.length}let m=ca(e,l,d,s!==void 0?{pageSize:s}:void 0),p;if(m.hasMore&&u==="char-limit"&&la(m.paginatedContent)){let g=m.charOffset+m.charLength;p=await ua(e,g,r)}let h=_s("localGetFileContent",{path:r,charLength:s??m.charLength,minify:t.minify},m);return{windowedContent:m.paginatedContent,pagination:m,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:p,next:h,showPagination:s!==void 0||i>0||a}}async function LP(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=await AP(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,contentView:s,...d&&{isPartial:d},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...Ju(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}async function kp(e,t,n,r,o,i,s){let a=await AP(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...Tp(r,o),...a.showPagination&&{pagination:{...Ju(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function _P(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}var FP=f(()=>{"use strict";Ee();Zu();ed();Be();bc()});import{ContentSanitizer as HI}from"@octocodeai/octocode-engine/contentSanitizer";async function Rc(e){let t=zn();try{let n=ft(e,v.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=SP(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await PP(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await TP(o))return W(wP(e,o),c);if(CP(e,l))return W(xP(e,o,l),c);let{content:u,errorResult:d}=await EP(e,o);if(d||u===void 0)return d;let m=HI.sanitizeContent(u,i),p=m.content,h=p.length,g=Buffer.byteLength(p,"utf-8"),y=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,b=e.minify,S=b==="standard"||b==="symbols",x=S?"standard":"none",k;if(b==="symbols"){let M=D.extractSignatures(p,i);if(M===null){let A=ia(p,i);if(A!==null)return W(await kp(e,A,_t(p),h,g,y,t),h);k=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(M!==null){let A=_t(p),q=D.applyContentViewMinification(M,i);return W(await kp(e,q,A,h,g,y,t),h)}}let E=_t(p),_=OP(e,p,t),w=M=>{let A=[...k?[k]:[],...y?[y]:[]];if(A.length===0)return M;let q=M.warnings??[];return{...M,warnings:[...q,...A]}};if(_.earlyResult){let M=_.earlyResult.content,A=S&&typeof M=="string"?{..._.earlyResult,content:D.applyContentViewMinification(M,i)}:_.earlyResult;return W(Ep(w(Op(_P(A,x),e,E)),h,g),h)}let G=await LP(e,_,s,E,t,S,x);return W(Ep(w(Op(G,e,E)),h,g),h)}catch(n){return N(n,e,{toolName:v.LOCAL_FETCH_CONTENT})}}function Op(e,t,n){return e}var Sc=f(()=>{"use strict";Ee();Fr();aa();pe();Vt();ue();sa();bc();vP();FP()});async function IP(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=ot(Mn,n);return r.ok===!1?r.error:await Rc(r.data)}}),{toolName:v.LOCAL_FETCH_CONTENT,finalize:QI()},e)}function QI(){return({results:e})=>{let t={results:jI(e)},n=Ea(t.results);n&&(t.base=n);let r=ka(t.results);return r&&(t.shared=r),{structuredContent:xt(t),text:BI(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function jI(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function BI(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=qn({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(qn({shared:e.shared},["shared"]).trimEnd()),t.join(`
36
36
  `).trimEnd()+`
37
- `}var FP=f(()=>{"use strict";pe();Ke();Dr();kd();Sc();Al();De();Vn();Sc()});function qr(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function Gi(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var Pc=f(()=>{"use strict"});function IP(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+Gi(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${qr(r)})`}function MP(e,t){let n=e.length,r=t.itemsPerPage||Dt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function Cc(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}var vp=f(()=>{"use strict";Ni();Pc()});function UI(e,t){let n=t??zI,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function er(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=ft(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:UI(i.path,i.excludeDir)},{warnings:a,query:c}=KI(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,m=u.wasCapped,p=u.entries.map(K=>$I(K,r)),h=e.sortBy||"modified";qI(p,h,r);let g=p.slice(0,l),y=WI(g,t,n),b=y.length,S=e.itemsPerPage||20,x=e.page||1,k=Math.max(1,Math.ceil(b/S)),E=(x-1)*S,_=Math.min(E+S,b),G=y.slice(E,_),M=[...u.warnings,...Cc(u)],A=[...a,...M],q=x<k,H={...b===0?{status:"empty"}:{},path:i.path,files:G,pagination:{currentPage:x,totalPages:k,filesPerPage:S,totalFiles:b,hasMore:q,...q?{nextPage:x+1}:{},...m||d>b?{totalFilesFound:d}:{}},...q?{next:{nextPage:Ls(v.LOCAL_FIND_FILES,{...i,page:x+1},"Continue to the next page of matched files.")}}:{},...A.length>0&&{warnings:A}};return W(DP(H,e,{totalFiles:b}),u.entries.reduce((K,I)=>K+I.path.length,0))}catch(o){return N(o,e,{toolName:v.LOCAL_FIND_FILES})}}function $I(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function DP(e,t,n){return e}function qI(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function WI(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(t?o.size=r.size:o.sizeFormatted=qr(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function KI(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!VI.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var zI,VI,Hi=f(()=>{"use strict";Vt();Pc();Ee();pe();ae();ue();Be();vp();zI=[];VI=/^\d+[hdwm]$/});async function NP(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=ot(Dn,n);return r.ok===!1?r.error:await er(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var GP=f(()=>{"use strict";_l();pe();Ke();Hi();De();Vn();Hi()});function Bi(e){return xc.exec(e)?.[1]?.toLowerCase()??""}function r0(e){let t=Bi(e);if(!t)return!1;for(let n of n0)if(Qi[n].extensions.includes(t))return!0;return!1}function Ip(e,t,n){if(n&&n!=="auto")return Qi[n];let r=Bi(e),o=(t??"").toLowerCase();for(let i of Ap){let s=Qi[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Ap){let s=Qi[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Qi.generic}function wc(e){return YI.test(e)?"generated":JI.test(e)?"fixture":XI.test(e)?"test":e0.test(e)?"config":ZI.test(e)?"docs":!ji.test(e)&&(t0.test(e)||r0(e))?"source":"unknown"}function Mp(e){if(!e)return!1;if(ji.test(e))return!0;let t=wc(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Ap,de,Lp,_p,HP,Qi,Fp,ji,YI,XI,JI,ZI,e0,t0,n0,xc,Tc=f(()=>{"use strict";Ap=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],de={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Lp=2e3,_p=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,HP={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Qi={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...HP},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...HP},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},Fp=/^\s*#{1,6}\s/,ji=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,YI=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,XI=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,JI=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,ZI=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,e0=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,t0=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,n0=new Set(["typescript","javascript","rust","python","go","java","scala"]),xc=/\.([a-z0-9]+)$/i});function Dp(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(QP),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Lp,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(QP);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=jp(i,n),l=i.map(d=>{try{return{file:d,s:Bp(d,n,c)}}catch{return{file:d,s:o0()}}});l.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function o0(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function QP(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function zi(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Ec(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Np(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function Gp(e,t,n){if(e.indexOf(`
37
+ `}var MP=f(()=>{"use strict";pe();Ke();Nr();kd();Sc();Al();De();Vn();Sc()});function Wr(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function Hi(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var Pc=f(()=>{"use strict"});function DP(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+Hi(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Wr(r)})`}function NP(e,t){let n=e.length,r=t.itemsPerPage||Dt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function Cc(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}var vp=f(()=>{"use strict";Gi();Pc()});function $I(e,t){let n=t??UI,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function er(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=ft(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:$I(i.path,i.excludeDir)},{warnings:a,query:c}=YI(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,m=u.wasCapped,p=u.entries.map(K=>qI(K,r)),h=e.sortBy||"modified";WI(p,h,r);let g=p.slice(0,l),y=VI(g,t,n),b=y.length,S=e.itemsPerPage||20,x=e.page||1,k=Math.max(1,Math.ceil(b/S)),E=(x-1)*S,_=Math.min(E+S,b),G=y.slice(E,_),M=[...u.warnings,...Cc(u)],A=[...a,...M],q=x<k,H={...b===0?{status:"empty"}:{},path:i.path,files:G,pagination:{currentPage:x,totalPages:k,filesPerPage:S,totalFiles:b,hasMore:q,...q?{nextPage:x+1}:{},...m||d>b?{totalFilesFound:d}:{}},...q?{next:{nextPage:Ls(v.LOCAL_FIND_FILES,{...i,page:x+1},"Continue to the next page of matched files.")}}:{},...A.length>0&&{warnings:A}};return W(GP(H,e,{totalFiles:b}),u.entries.reduce((K,I)=>K+I.path.length,0))}catch(o){return N(o,e,{toolName:v.LOCAL_FIND_FILES})}}function qI(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function GP(e,t,n){return e}function WI(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function VI(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(t?o.size=r.size:o.sizeFormatted=Wr(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function YI(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!KI.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var UI,KI,Qi=f(()=>{"use strict";Vt();Pc();Ee();pe();ae();ue();Be();vp();UI=[];KI=/^\d+[hdwm]$/});async function HP(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=ot(Dn,n);return r.ok===!1?r.error:await er(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var QP=f(()=>{"use strict";_l();pe();Ke();Qi();De();Vn();Qi()});function zi(e){return xc.exec(e)?.[1]?.toLowerCase()??""}function o0(e){let t=zi(e);if(!t)return!1;for(let n of r0)if(ji[n].extensions.includes(t))return!0;return!1}function Ip(e,t,n){if(n&&n!=="auto")return ji[n];let r=zi(e),o=(t??"").toLowerCase();for(let i of Ap){let s=ji[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Ap){let s=ji[i];if(i!=="generic"&&s.extensions.includes(r))return s}return ji.generic}function wc(e){return XI.test(e)?"generated":ZI.test(e)?"fixture":JI.test(e)?"test":t0.test(e)?"config":e0.test(e)?"docs":!Bi.test(e)&&(n0.test(e)||o0(e))?"source":"unknown"}function Mp(e){if(!e)return!1;if(Bi.test(e))return!0;let t=wc(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Ap,de,Lp,_p,jP,ji,Fp,Bi,XI,JI,ZI,e0,t0,n0,r0,xc,Tc=f(()=>{"use strict";Ap=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],de={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Lp=2e3,_p=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,jP={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},ji={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...jP},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...jP},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},Fp=/^\s*#{1,6}\s/,Bi=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,XI=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,JI=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,ZI=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,e0=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,t0=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,n0=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,r0=new Set(["typescript","javascript","rust","python","go","java","scala"]),xc=/\.([a-z0-9]+)$/i});function Dp(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(BP),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Lp,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(BP);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=jp(i,n),l=i.map(d=>{try{return{file:d,s:Bp(d,n,c)}}catch{return{file:d,s:i0()}}});l.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function i0(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function BP(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function Ui(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Ec(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Np(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function Gp(e,t,n){if(e.indexOf(`
38
38
  `)<0)return e;let o=e.split(`
39
- `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function Hp(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(_p.test(e))return"comment";let o=i0(e,t,r);if(o<0)return"code";let i=s0(e);return i>=0&&o>i?"comment":jP(e,o)?"string":"code"}function i0(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function s0(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function jP(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}var Qp=f(()=>{"use strict";Tc();zp()});function a0(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function c0(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function l0(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Np(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=Gp(l,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Ec(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=de.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=de.exactCaseInsensitive,m.push("case-insensitive match")):u.includes(r)&&(d+=de.substring,m.push("substring match")));let p=c.kind;if(p)d+=u0(p,m);else{let h=Hp(u,r,t.id,n.caseSensitive);h!=="code"?(d+=de.commentOrStringPenalty,m.push(h==="comment"?"comment match (weak)":"string literal (weak)")):(zi(t.declaration,u)&&(d+=de.declarationLine,m.push("declaration line")),zi(t.export,u)&&(d+=de.exportLine,m.push("export/public line")),zi(t.import,u)&&(d+=de.importLine,m.push("import line")),t.id==="markdown"&&Fp.test(u)&&(d+=de.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&d0(u,r)&&(d+=de.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function u0(e,t){switch(e){case"declaration":return t.push("AST: declaration"),de.declarationLine;case"export":return t.push("AST: export/public"),de.exportLine;case"configKey":return t.push("AST: config key"),de.configKeyLine;case"heading":return t.push("AST: heading"),de.headingLine;case"import":return t.push("AST: import"),de.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),de.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function d0(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function p0(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(xc,"").includes(l))&&(s+=de.pathSegmentToken,i.push("query token in path"))}let a=Bi(e);return r.extensions.includes(a)&&t.langType&&(s+=de.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=de.sourceDir,i.push("source file")),s}function m0(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),de.lowSignalPathPenalty):0}function f0(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*de.matchCountScale,r=Math.min(n,de.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function jp(e,t){let n=c0(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>h0(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function h0(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Ec(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function g0(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*de.rareQueryTokenScale,de.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function Bp(e,t,n){let r=Ip(e.path,t.langType,t.profileOverride),o=wc(e.path),i=a0(t.keyword),s=[],a=0;return a+=l0(e.matches,r,t,i,s),a+=p0(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=de.pathUnderQuery,s.push("under requested subtree")),a+=m0(o,t,s),ji.test(e.path)&&!t.explicitLowSignal&&(a+=de.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=f0(e.matchCount??0,s),a+=g0(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var zp=f(()=>{"use strict";Tc();Qp()});var BP=f(()=>{"use strict";Tc();zp();Qp()});function zP(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=R0(i);s.fetch={tool:"localGetFileContent",query:Up({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"heuristic":"exact"};let a=S0(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Up({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Up({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function R0(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-8),endLine:n+8}}function S0(e,t,n){if(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)return;if(n==="structural")return P0(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.onlyMatching){let o=$p(e?.value);return o?{symbol:o}:void 0}let r=$p(t.keywords);return r?{symbol:r}:void 0}function P0(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=$p(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function $p(e){if(typeof e!="string")return;let t=e.trim();if(b0.test(t)&&!y0.has(t))return t}function Up(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var y0,b0,qp=f(()=>{"use strict";y0=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),b0=/^[A-Za-z_$][A-Za-z0-9_$]*$/});async function kc(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=Dp(e,s,C0(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),m=!!(t.countLinesPerFile||t.countMatchesPerFile),p=d||m,h=c.reduce((H,K)=>H+(K.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??h:h,y=t,b=Math.min(y.itemsPerPage||Dt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=y.page||1,x=Math.max(1,Math.ceil(u/b)),k=(S-1)*b,E=Math.min(k+b,u),_=c.slice(k,E),w=y.maxMatchesPerFile||Dt.DEFAULT_MATCHES_PER_PAGE,G=_.map(H=>{let K=H.matches?.length??0,I=Math.ceil(K/w),ye=Math.max(1,y.matchPage||1),Te=(ye-1)*w,nn=Math.min(Te+w,K),lo=p?void 0:H.matches?.slice(Te,nn),Os=lo?.length,uo=l?.get(H.path);return{path:H.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:H.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:H.matchCount||1}:{totalMatchRows:K,...Os!==void 0?{returnedMatchRows:Os}:{}},...lo!==void 0&&{matches:lo},...uo?{ranking:{score:uo.score,profile:uo.profile,pathRole:uo.pathRole,reasons:uo.reasons}}:{},pagination:!p&&K>w?{currentPage:ye,totalPages:I,matchesPerPage:w,totalMatches:K,hasMore:ye<I,...ye<I?{nextMatchPage:ye+1}:{}}:void 0}}),M=G.filter(H=>H.pagination?.hasMore),A=zP(G,t,n,{isFileListMode:p,currentPage:S,totalFilePages:x,matchPage:y.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:M.length>0}),q={searchEngine:n,...o?{stats:o}:{},files:G,pagination:{currentPage:S,totalPages:x,filesPerPage:b,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<x,...S<x?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return UP(q,t,{totalMatches:g,totalFiles:u})}function UP(e,t,n){return e}function C0(e){let t=e.rankingProfile,n=!!(e.include?.length||Mp(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var $P=f(()=>{"use strict";Ni();BP();qp()});var Oc=f(()=>{"use strict";$P();qp()});function qP(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&x0(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&w0(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function x0(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function w0(e){return/\(\?[=!<]/.test(e)}var WP=f(()=>{"use strict";Ee()});import{validateRipgrepQuery as T0}from"@octocodeai/octocode-core/schemas/runtime";function E0(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function k0(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:E0(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function O0(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function VP(e){let t=[],n=T0(e);if(!n.isValid)return N(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=jt.safeParse(e);if(!r.success){let g=r.error.issues.map(y=>y.message);return N(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return N(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=ft(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=qP({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return N(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(k0(a))}catch(g){return N(g instanceof Error?g:new Error(String(g)),o,{toolName:v.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(y=>{let b={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(b.count=y.count),y.kind!==void 0&&(b.kind=y.kind),y.scoreHint!==void 0&&(b.scoreHint=y.scoreHint),b})})),m=O0(d),p={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return W({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...l]},m);!a.filesOnly&&m>Dt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let h=await kc(d,o,"rg",[...t,...l],p);return W(h,m)}var KP=f(()=>{"use strict";Vt();Fs();Ni();pe();Oc();WP();ue();Ee()});var YP,XP,JP=f(()=>{"use strict";YP={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},XP={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});function v0(e){return e.trim().replace(/^\./,"").toLowerCase()}function tr(e){if(!e?.trim())return;let t=v0(e),n=YP[t]??XP[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function A0(e){return[...e??[]].map(t=>`**/*.${t}`)}function Wp(e){return[...e??[]].map(t=>`*.${t}`)}function Ui(e){let t=tr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function vc(e){let t=tr(e);return t?t.kind==="extension"&&t.extension?{include:A0([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function Ac(e){let t=tr(e);return t?t.kind==="extension"&&t.extension?Wp([t.extension]):t.kind==="language"?Wp(t.extensions):t.normalized?Wp([t.normalized]):[]:[]}function Vp(e){let t=tr(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Lc(e){return tr(e)?.canonicalLanguage}var ZP=f(()=>{"use strict";JP()});var Kp=f(()=>{"use strict";ZP()});import{readFile as L0,stat as _0}from"node:fs/promises";function D0(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function tC(e){return e.include?.length?e.include:Vp(e.langType)}async function N0(e){try{return(await _0(e)).isFile()}catch{return!1}}async function G0(e,t){let n=await L0(e,"utf8"),r=await D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function nC(e){let t=ft(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await N0(t.sanitizedPath)?await G0(t.sanitizedPath,e):await D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...tC(e)?{include:tC(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:eC.length?{excludeDir:eC}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??F0,maxFileBytes:I0})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return N(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:v.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(M0+D0(e.pattern)),await kc(r,e,"structural",i,o)}var eC,F0,I0,M0,rC=f(()=>{"use strict";Ee();Vt();pe();Kp();Oc();eC=[],F0=2e3,I0=1e6,M0="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function H0(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function ht(e){let t=H0(e);if(t.mode==="structural")return await nC(t);t.contextLines===void 0&&(t.contextLines=2);try{return await VP(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:$.OUTPUT_TOO_LARGE}:N(n,t,{toolName:v.LOCAL_RIPGREP})}}var Wr=f(()=>{"use strict";Vt();Wn();pe();KP();rC()});async function oC(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=ot(jt,n);return r.ok===!1?r.error:await ht(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var iC=f(()=>{"use strict";Fs();pe();Ke();Wr();De();Vn();Oc()});function B0(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function sC(e,t){let n=e[t];return n===void 0?!1:Q0.has(n)||n==="{"&&$0(e,t)}function z0(e,t,n){let r=n.pop()??!1,o=sC(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?cC(e,t+1):t+1})}function U0(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:cC(e,t)})}function aC(e){if(e.length>j0)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=B0(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=z0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(sC(e,r)){let i=U0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function $0(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function cC(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var Q0,j0,lC=f(()=>{"use strict";Q0=new Set(["+","*","?"]),j0=1e3});function uC(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!aC(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function dC(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function pC(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var mC=f(()=>{"use strict";lC()});async function _c(e){try{let t=ft(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return q0(e,t.sanitizedPath,n)}catch(t){let n=mt.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function q0(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=V0(e),s=r&&e.limit&&!W0(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:K0(e),limit:s})}catch(x){return J0(x,e,t)}let c=a.entries.map(x=>Y0(x,n,e.details??!1)),l=uC(c,e),u=e.sortBy??"name";l=l.sort((x,k)=>{let E=0;switch(u){case"size":{let _=x.sizeBytes??(x.size?Gi(x.size):0),w=k.sizeBytes??(k.size?Gi(k.size):0);E=_-w;break}case"time":n&&x.modified&&k.modified?E=x.modified.localeCompare(k.modified):E=x.name.localeCompare(k.name);break;case"extension":E=(x.extension||"").localeCompare(k.extension||"");break;default:E=x.name.localeCompare(k.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:m,pagination:p}=MP(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(x=>({...pC(x),path:x.path??`${t.replace(/\/$/,"")}/${x.name}`}))}:{path:t,...dC(m)},y=[...a.warnings,...Cc({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],b=d===0,S=IP(l);return W(fC({...b?{status:"empty"}:{},...g,summary:S,...p.hasMore||p.totalPages>1?{pagination:p}:{},...p.hasMore?{next:{nextPage:Ls(v.LOCAL_VIEW_STRUCTURE,{...e,page:p.currentPage+1},"Continue to the next page of directory entries.")}}:{},...y.length>0&&{warnings:y}},e),a.entries.reduce((x,k)=>x+k.path.length,0))}function W0(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function V0(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function K0(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function Y0(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:qr(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=X0(e.permissions)),o}function X0(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function J0(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=mt.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return N(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function fC(e,t){return e}var Fc=f(()=>{"use strict";Pc();pe();Vt();yc();mC();vp();ue();Ee();Be()});async function hC(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=ot(Nn,n);return r.ok===!1?r.error:await _c(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var gC=f(()=>{"use strict";Il();pe();Ke();Fc();De();Vn();Fc()});function eM(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function yC(e,t){if(t===void 0||t==="progressIdle")return e;let n=eM(e);if(!n||!Z0.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}var Z0,bC=f(()=>{"use strict";Z0=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as tM,stat as nM}from"node:fs/promises";import{SymbolResolver as rM,SymbolResolutionError as oM}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as Ic}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function Yp(e,t){let n=e.uri,r=ft({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await nM(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:Ic.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:Ic.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await tM(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:Ic.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function RC(e,t){let n=await Yp(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new rM({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:iM(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof oM)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:Ic.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function iM(e){return{start:e,end:{line:e.line,character:e.character}}}var Xp=f(()=>{"use strict";Vt()});function Zp(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function em(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Zp(e.type,t),reason:t}}}function gt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Zp(e,n),reason:n}}}function yt(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}var Tn,Mc,Jp,Dc=f(()=>{"use strict";kt();Tn=40,Mc=40,Jp=10});function $i(e,t,n,r,o){let i=o.length>0,s=o.map(El),{pageItems:a,pagination:c}=yt(s,e.page??1,e.itemsPerPage??Mc);return{type:e.type,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function tm(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?SC(r):void 0,i=o??r.map(El),{pageItems:s,pagination:a}=yt(i,e.page??1,e.itemsPerPage??Mc),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function nm(e,t,n){let r=PC(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function SC(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function PC(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>CC(r)).join(`
40
- `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function CC(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var xC=f(()=>{"use strict";kt();Dc()});import{safeReadFile as sM}from"@octocodeai/octocode-engine/lsp/validation";function qi(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function TC(e,t,n){if(t<=0)return e;let r=await sM(e.uri);if(!r)return e;let o=ci(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
41
- `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function aM(e,t){return Promise.all(e.map(async n=>({...n,from:await TC(n.from,t,n.fromRanges)})))}async function cM(e,t){return Promise.all(e.map(async n=>({...n,to:await TC(n.to,t)})))}async function rm(e,t,n,r,o){if(n<=0||!e)return{calls:[],...wC};try{let i=await e.getIncomingCalls(t),s=o>0?await aM(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=qi(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),rm(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function om(e,t,n,r,o){if(n<=0||!e)return{calls:[],...wC};try{let i=await e.getOutgoingCalls(t),s=o>0?await cM(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=qi(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),om(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var wC,EC=f(()=>{"use strict";_r();wC={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function OC(e){return W(e,j(e))}function vC(e,t){return e.format!=="compact"||!LC(t)?t:uM(t)}function AC(e){if(!LC(e))return e;let n=e.payload.locations?.[0],r=n?.displayRange?.startLine;if(!n?.uri||typeof r!="number")return e;let o=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri;return{...e,next:{readSite:{tool:"localGetFileContent",query:{path:o,startLine:Math.max(1,r-3),endLine:(n.displayRange?.endLine??r)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}function LC(e){return nr(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&nr(e.payload)}function uM(e){return{...e,format:"compact",payload:dM(e.payload)}}function dM(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(kC)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(mM)}:{locations:(e.locations??[]).map(kC)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:_C(e.root)}:{},direction:e.direction,calls:e.calls.map(fM),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(pM)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function pM(e){if(!nr(e))return String(e);let t=Xe(e,"line"),n=Xe(e,"character"),r=Xe(e,"endLine"),o=Kt(e,"kind"),i=Kt(e,"name"),s=Xe(e,"childCount"),a=Kt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function kC(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${IC(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function mM(e){if(!nr(e))return String(e);let t=Kt(e,"uri"),n=Xe(e,"firstLine"),r=Xe(e,"firstCharacter"),o=Xe(e,"count"),i=FC(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function fM(e){if(!nr(e))return String(e);let t=Kt(e,"direction"),n=_C(e.item),r=FC(e,"ranges").map(hM).join(","),o=Xe(e,"rangeCount"),i=Xe(e,"rangeSampleCount"),s=Kt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${IC(s,180)}`:""].filter(Boolean).join(" ")}function _C(e){if(!nr(e))return String(e);let t=Kt(e,"name"),n=Kt(e,"kind"),r=Kt(e,"uri"),o=Xe(e,"line"),i=Xe(e,"endLine"),s=Xe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function hM(e){return nr(e)?`${Xe(e,"line")}:${Xe(e,"character")}`:String(e)}function nr(e){return typeof e=="object"&&e!==null}function Kt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Xe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function FC(e,t){let n=e[t];return Array.isArray(n)?n:[]}function IC(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}function MC(e,t){let n=NC(e.fromRanges);return{direction:"incoming",item:Nc(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...GC(e.from,t)}}function DC(e,t){let n=NC(e.fromRanges);return{direction:"outgoing",item:Nc(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...GC(e.to,t)}}function Nc(e){return{name:e.name,kind:Vr(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function NC(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=lM))break}return n}function GC(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Vr(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}var lM,Wi=f(()=>{"use strict";ue();lM=8});async function im(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return gt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await rm(n,o,i,new Set([qi(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await om(n,o,i,new Set([qi(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),m=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],p=m.map(S=>S.direction==="incoming"?MC(S,e.contextLines??0):DC(S,e.contextLines??0)),{pageItems:h,pagination:g}=yt(p,e.page??1,e.itemsPerPage??Jp),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Nc(o),direction:y,calls:h,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function sm(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return gt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=yt(s,e.page??1,e.itemsPerPage??Tn);return{type:e.type,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}var HC=f(()=>{"use strict";EC();kt();Wi();Dc()});var Vi=f(()=>{"use strict";Dc();xC();HC()});import Ki from"node:path";import{readFile as gM}from"node:fs/promises";import{resolveImportAliasDefinitions as yM}from"@octocodeai/octocode-engine/lsp/resolver";async function BC(e,t,n){if(typeof e.openDocument=="function")try{let r=Ki.extname(t.uri).slice(1),o=QC.includes(r)?QC:[r],i=await ht({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:bM,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=Ki.isAbsolute(a)?a:Ki.join(n,a);if(Ki.resolve(c)!==Ki.resolve(t.uri))try{let l=await gM(c,"utf-8");if(l.length>RM)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function zC(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?$i(e,t,"definition","definitionProvider",await yM({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):gt(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?$i(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):gt(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?$i(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):gt(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?tm(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):gt(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?nm(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):gt(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?im(e,t,n):gt(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?sm(e,t,n):gt(e.type,t,"typeHierarchyProvider unsupported",!0)}}var jC,bM,RM,QC,UC=f(()=>{"use strict";Wr();Vi();jC=new Set(["references","callers","callees","callHierarchy","implementation"]),bM=12,RM=512*1024,QC=["ts","tsx","mts","cts","js","jsx","mjs","cjs"]});import cm from"node:path";import{fileURLToPath as SM}from"node:url";import{unavailableHintFor as PM}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as CM}from"@octocodeai/octocode-engine/lsp/config";function $C(e){return am||(am=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),am.has(cm.extname(e).toLowerCase())}function Tt(e,t){let n=CM(e),r=PM(n,void 0);throw new je($.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function qC(e,t){let n=e.startsWith("file://")?SM(e):e;return cm.isAbsolute(n)?n:cm.resolve(t,n)}function lm(){return[...D.getSupportedJsTsExtensions(),...xM]}function WC(){return lm().map(e=>`**/*.${e}`)}async function VC(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:WC(),excludeDir:[...wM],maxSnippetChars:1})).files[0]?.path}catch{return}}async function um(e,t){if(e.uri)return qC(e.uri,t);let n=await VC(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:lm(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function dm(e){return e instanceof Error?e.message:String(e)}function pm(e,t){if(!$C(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var am,xM,wM,Gc=f(()=>{"use strict";Oa();Wn();Ee();xM=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];wM=[".git","node_modules","dist","out","coverage","target"]});import{acquirePooledClient as TM,isLanguageServerAvailable as EM}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as kM}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function hm(e){let t=await Yp(e,Ie);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await kM(t.value.uri),r=await EM(t.value.uri,n),o=r?await TM(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=pm(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let y=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(y)?y:[],a="lsp"}else{let y=Sy(t.value.content,t.value.uri);y&&(s=y,a="markdown")}let l=a!==void 0;!l&&!r&&Tt(t.value.uri,"documentSymbols");let u=KC(s),d=XC(s),{pageItems:m,pagination:p}=yt(u,e.page??1,e.itemsPerPage??Tn),h=JC(u,y=>y.kind),g=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:m.length,topLevelSymbols:d,kinds:h},payload:{kind:"documentSymbols",symbols:m,...g?{empty:g}:{}},pagination:p}}function KC(e){let t=[];for(let n of e)gm(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function gm(e,t,n){if(!e||typeof e!="object")return;let r=e,o=YC(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Vr(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&OM.has(Vr(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)gm(s,t,i)}}function YC(e){if(mm(e.range))return e.range;let t=e.location;return t&&mm(t.range)?t.range:void 0}function mm(e){if(!e||typeof e!="object")return!1;let t=e;return fm(t.start)&&fm(t.end)}function fm(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function XC(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function JC(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}var OM,ZC=f(()=>{"use strict";sa();kt();Xp();Vi();Wi();Gc();OM=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});import ex from"node:path";import{acquirePooledClient as tx,isLanguageServerAvailable as nx}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as vM}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function ym(e){let t=e.symbolName??"",n=ex.resolve(e.workspaceRoot??process.cwd()),r=await um(e,n);await nx(r,n)||Tt(r,"workspaceSymbol");let i=await tx(n,r);if(i||Tt(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{ex.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${dm(u)}`}}}let a=rx(s),{pageItems:c,pagination:l}=yt(a,e.page??1,e.itemsPerPage??Tn);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function rx(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:Vr(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function bm(e){let t=e.uri??"",n=e.workspaceRoot??(t?await vM(t):process.cwd());await nx(t,n)||Tt(t,"diagnostic");let o=await tx(n,t);if(o||Tt(t,"diagnostic"),!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let i=await o.getDiagnostics(t),s=ox(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=yt(s,e.page??1,e.itemsPerPage??Tn);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function ox(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>ix(r))}return[]}function ix(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}var sx=f(()=>{"use strict";Vi();Wi();Gc()});var ax=f(()=>{"use strict";Gc();ZC();sx()});import{acquirePooledClient as AM,isLanguageServerAvailable as LM}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as _M}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function cx(e){return me(e.queries||[],async t=>ut({toolName:Ie,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await FM(t);return OC(AC(vC(t,n)))}}),{toolName:Ie,minQueryTimeoutMs:3e4},e)}async function FM(e){if(e.type==="documentSymbols")return hm(e);if(e.type==="workspaceSymbol")return ym(e);if(e.type==="diagnostic")return bm(e);let t=await RC(e,Ie);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return em(e,a)}let n=e.workspaceRoot??await _M(t.value.uri);await LM(t.value.uri,n)||Tt(t.value.uri,e.type);let o=await AM(n,t.value.uri);o||Tt(t.value.uri,e.type),jC.has(e.type)&&await BC(o,t.value,n);let i=o.getReadiness?.(),s=await zC(e,t.value,o);return yC(s,i)}var lx=f(()=>{"use strict";Ke();Vn();kt();bC();Xp();UC();Vi();ax();Wi()});function C(e,t,n={}){let r=n.severity??(MM.has(e)?"error":"warning"),o=n.blocksAnswer??(IM.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function ux(e){return e.some(t=>t.blocksAnswer)}var IM,MM,Yt,te=f(()=>{"use strict";IM=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),MM=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);Yt=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});function J(...e){throw new Yt(e)}function rr(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var Kr=f(()=>{"use strict";te()});import{z as T}from"zod";function px(e,t){let n=qM[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var Oe,DM,dx,NM,GM,HM,QM,jM,BM,zM,UM,$M,qM,mx=f(()=>{"use strict";Oe=T.number().int().min(1),DM=T.number().int().min(0),dx=T.enum(["symbols","files","dependencies","relations"]),NM=T.object({match:T.enum(["file","path"]).optional(),concise:T.boolean().optional(),extension:T.string().optional(),filename:T.string().optional(),page:Oe.optional(),limit:Oe.optional()}).passthrough(),GM=T.object({type:T.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:T.string().optional(),symbolName:T.string().optional(),symbolKind:T.string().optional(),lineHint:Oe.optional(),orderHint:T.number().int().optional(),includeDeclaration:T.boolean().optional(),depth:T.number().int().min(0).max(20).optional(),groupByFile:T.boolean().optional(),workspaceRoot:T.string().optional(),format:T.enum(["structured","compact"]).optional(),page:Oe.optional(),itemsPerPage:Oe.optional()}).passthrough(),HM=T.object({keywords:T.array(T.string()).optional(),topicsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:T.string().optional(),owner:T.string().optional(),stars:T.union([T.string(),T.number()]).optional(),forks:T.string().optional(),goodFirstIssues:T.string().optional(),size:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),license:T.string().optional(),match:T.array(T.enum(["name","description","readme"])).optional(),visibility:T.enum(["public","private"]).optional(),archived:T.boolean().optional(),sort:T.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:T.boolean().optional(),page:Oe.optional()}).passthrough(),QM=T.object({packageName:T.string().optional(),keywords:T.array(T.string()).optional(),mode:T.enum(["lean","full"]).optional(),page:Oe.optional()}).passthrough(),jM=T.object({prNumber:Oe.optional(),concise:T.boolean().optional(),state:T.enum(["open","closed","merged"]).optional(),author:T.string().optional(),label:T.union([T.string(),T.array(T.string())]).optional(),keywordsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:T.string().optional(),base:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),closed:T.string().optional(),"merged-at":T.string().optional(),draft:T.boolean().optional(),archived:T.boolean().optional(),sort:T.enum(["created","updated","best-match","comments","reactions"]).optional(),order:T.enum(["asc","desc"]).optional(),reviewMode:T.string().optional(),filePage:Oe.optional(),commentPage:Oe.optional(),commitPage:Oe.optional(),charOffset:DM.optional(),charLength:Oe.optional(),minify:T.enum(["none","standard"]).optional(),limit:Oe.optional(),page:Oe.optional(),matchString:T.string().optional(),matchScope:T.enum(["body","title","comments","reviews","all"]).optional(),content:T.record(T.string(),T.unknown()).optional()}).passthrough(),BM=T.object({path:T.string().optional(),branch:T.string().optional(),since:T.string().optional(),until:T.string().optional(),author:T.string().optional(),includeDiff:T.boolean().optional(),limit:Oe.optional(),page:Oe.optional()}).passthrough(),zM=T.object({prNumber:Oe.optional(),files:T.array(T.string()).optional(),baseRef:T.string().optional(),headRef:T.string().optional(),path:T.string().optional()}).passthrough(),UM=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(dx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:Oe.optional()}).passthrough(),$M=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(dx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:Oe.optional(),subject:T.string().optional(),subjectKind:T.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:T.union([T.string(),T.array(T.string())]).optional(),verdict:T.union([T.string(),T.array(T.string())]).optional(),direction:T.enum(["incoming","outgoing","both"]).optional(),proof:T.enum(["none","lsp"]).optional(),proofLimit:Oe.max(25).optional(),includePackets:T.boolean().optional(),includeFacts:T.boolean().optional(),includeEdges:T.boolean().optional()}).passthrough(),qM={semantics:GM,repositories:HM,packages:QM,pullRequests:jM,commits:BM,diff:zM,research:UM,graph:$M,code:NM}});function fx(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&J(C("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),WM(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Ml.includes(t)||J(C("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function WM(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}var hx=f(()=>{"use strict";te();un();Kr()});function gx(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&J(C("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}var yx=f(()=>{"use strict";te();Kr()});function Yr(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Yr(n),0):e.kind==="not"?1+Yr(e.predicate):1:0}var Rm=f(()=>{"use strict"});function bx(e,t){let n=YM(e);e.where&&n&&J(C("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Sm(r,"where"),Pm(r,"where",new Map);let o=dn.safeParse(r);return o.success||J(C("invalidQuery",rr(o.error),{queryPath:"where"})),o.data}function KM(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:VM}function YM(e){let t=n=>{let r=Yr(n),o=KM(e);return r>o&&J(C("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(Xr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(Xr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(Xr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&J(C("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=Xr(e.xor[0]),r=Xr(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(XM(e.oneOf.map(Xr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&J(C("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&J(C("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function Xr(e){if(e&&typeof e=="object"&&"kind"in e)return e;J(C("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function XM(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Sm(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&J(C("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Sm(n,`${t}.of[${r}]`));break;case"not":e.predicate||J(C("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Sm(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&J(C("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":JM(e,t);break;default:break}}function Pm(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&J(C("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>Pm(r,`${t}.of[${o}]`,n)):e.kind==="not"&&Pm(e.predicate,`${t}.predicate`,n)}function JM(e,t){if(e.op==="exists"){e.value!==void 0&&J(C("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&J(C("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&J(C("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}var VM,Rx=f(()=>{"use strict";Rr();te();Rm();Kr();VM=64});function Sx(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return Sx(e.predicate);default:return!1}}function Px(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:Sx(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}var Cx=f(()=>{"use strict"});function xx(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!eD(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function eD(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return ZM.some(n=>t.includes(n))}var ZM,wx=f(()=>{"use strict";ZM=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"]});function Yi(e){let t=bh.safeParse(e);t.success||J(C("invalidQuery",rr(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??nD(n);r===void 0&&J(C("invalidQuery",`Could not determine \`target\`; specify one of: ${ln.join(", ")}.`,{queryPath:"target"})),Fo.includes(r)&&J(C("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${ln.join(", ")}.`}})),ln.includes(r)||J(C("unknownField",`Unknown target "${r}".`));for(let h of Object.keys(n))tD.has(h)||J(C("unknownField",`Unknown field "${h}" is not part of OQL.`,{queryPath:h}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=fx(n,r),a=gx(n,s),c=bx(n,r),l=Px(n,s,c,r),u=rD(n),d=xx(n,r),m={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(m.target==="code"&&!m.where&&J(C("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.where&&J(C("invalidQuery",`target:"${m.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.from?.kind==="github"&&!(m.from.repo&&m.from.repo.includes("/"))&&J(C("invalidQuery",`target:"${m.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),m.target==="materialize"&&(m.where&&J(C("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),m.from?.kind!=="github"&&m.from?.kind!=="materialized"&&J(C("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),m.params!==void 0){let h=px(m.target,m.params);h&&J(C("invalidQuery",h,{queryPath:"params"}))}let p=Ds.safeParse(m);return p.success||J(C("invalidQuery",rr(p.error))),p.data}function nD(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function rD(e){return e.fetch?{...e.fetch}:void 0}var tD,Hc=f(()=>{"use strict";Rr();te();mx();un();Kr();hx();yx();Rx();Cx();wx();tD=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"])});function Tx(e){let t=Rh.safeParse(e);t.success||J(C("invalidQuery",rr(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||J(C("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&J(C("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return Yi(i)}catch(a){throw a instanceof Yt?new Yt(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}var Ex=f(()=>{"use strict";Rr();te();Kr();Hc()});function kx(e){return Nl(e)?Tx(e):Yi(e)}var Ox=f(()=>{"use strict";un();Ex();Hc();Hc()});function Xi(e){let t=iD(e),n=aD(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function iD(e){return!e.executable||e.diagnostics.some(t=>oD.has(t.code))?"unsupported":e.approximate||sD(e.diagnostics)?"candidate":ux(e.diagnostics)||vx(e)?"partial":"proof"}function sD(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function vx(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function aD(e){return!e.executable||vx(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function Ax(e){return e.some(t=>!t.exact)}function Qc(e,t,n,r,o){return Xi({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var oD,Ji=f(()=>{"use strict";te();oD=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function jc(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(jc):e.kind==="not"?jc(e.predicate):[e]}function Cm(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function Ne(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Jr(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function xm(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var En=f(()=>{"use strict"});import or from"node:path";import{statSync as cD}from"node:fs";function Lx(e){let t=or.resolve(e);try{if(cD(t).isDirectory())return`${t}${or.sep}`}catch{}return`${or.dirname(t)}${or.sep}`}function _x(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function Fx(e,t){let n=_x(e);if(!n)return;let r=Lx(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function Ix(e){let t=_x(e);if(!t)return;let n=Lx(t).slice(0,-or.sep.length);return r=>({kind:"local",path:or.isAbsolute(r)?r:or.join(n,r)})}var wm=f(()=>{"use strict"});function Mx(e,t){for(let n of t)n.proofGrade??=lD(e,n)}function lD(e,t){return t.kind==="code"?Zi(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Zi(e.where,"text")||Zi(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?es(t.data)?"missing":"graph":t.recordType==="research"?es(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"?"text":"candidate"}function Zi(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Zi(n,t)):e.kind==="not"?Zi(e.predicate,t):!1:!1}function es(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!uD(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function uD(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Tm=f(()=>{"use strict"});function dD(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function Dx(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:dD(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"none",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function Nx(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function pD(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function mD(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function Gx(e){let t=mD(e);return t?pD(t,"materialized"):void 0}function Hx(e,t){return jx(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function Qx(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(es(r))return jx(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function jx(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!es(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=hD(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function hD(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&fD.has(o));return r.length>0?r:void 0}var fD,Bx=f(()=>{"use strict";Tm();fD=new Set(["symbols","files","dependencies","relations"])});import ts from"node:path";import{statSync as gD}from"node:fs";function zx(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=RD(e)??SD(t.query),i=yD(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"none",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function yD(e,t){if(e&&ts.isAbsolute(e))return e;if(t&&ts.isAbsolute(t)){let n=bD(t);return e?ts.resolve(n,e):t}return t??e}function bD(e){try{return gD(e).isDirectory()?e:ts.dirname(e)}catch{return ts.dirname(e)}}function RD(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function SD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}var Ux=f(()=>{"use strict"});function PD(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function CD(e){let t=PD(e),n=Ne(e.scope),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${$x(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${$x(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function $x(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function qx(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${CD(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:Ix(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=xD[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function Wx(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||Em(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function Em(e,t){return e.why===t.why&&e.confidence===t.confidence}var xD,km=f(()=>{"use strict";En();wm();Bx();Ux();xD={code:Dx,content:Nx,"record:materialized":Gx,"record:semantics":zx,"record:research":Hx,"record:graph":Qx}});function we(e,t){return Bc(e,{queries:[{...wD,...t}]})}function kn(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function Zr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ns(e){return typeof e=="string"?e:void 0}var wD,Xt=f(()=>{"use strict";Om();wD={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function Jt(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var zc=f(()=>{"use strict"});function vm(e){return Jt(e)}function TD(e){if(e)return Jt({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function eo(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges,c=i;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...c.kind!==void 0?{matchKind:c.kind}:{},...c.scoreHint!==void 0?{scoreHint:c.scoreHint}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:Am(TD(e.pagination),n.length)}}function Am(e,t,n=!1){if(e)return e.totalItemsKind!=="files"&&!n?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function rs(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:vm(e.pagination)}}function Vx(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:vm(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=kD(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:vm(e.pagination)}}function kD(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=ED[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function Kx(e,t,n,r="standard"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var ED,On=f(()=>{"use strict";zc();ED={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});function Yx(e){return JSON.stringify(e)}function Lm(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${Yx(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${Yx(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Lm(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=Lm(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function Xx(e){return["rule:",...Lm(e,1)].join(`
42
- `)}var Jx=f(()=>{"use strict"});function Zx(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function ew(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return Zx(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),Zx(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=Xx(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function Zt(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return ew(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=ew(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var os=f(()=>{"use strict";Jx()});var Uc=f(()=>{"use strict";Kp()});function tw(e,t,n){let r=e.where,o=r?jc(r):[],i=r&&OD.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>C("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function vD(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function is(e,t={}){if(!e.where)return{ok:!1,diagnostics:[C("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=vD(e.where);if(n){let m=nw(e,t);if(m.length>0)return{ok:!1,diagnostics:m};let{owner:p,repo:h}=Cm(e.from),g=e.params??{},y=typeof g.extension=="string"||typeof n.extension=="string"?{}:Ui(Jr(e.scope)),b=xm(e),S=Ne(e.scope);return tw(e,{...p?{owner:p}:{},...h?{repo:h}:{},...y,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...b?{limit:b}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=Zt(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[C("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=nw(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[C("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Cm(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Ui(Jr(e.scope)),u=xm(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return tw(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...Ne(e.scope)?{path:Ne(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function nw(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(C("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(C("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var OD,_m=f(()=>{"use strict";os();te();Uc();En();OD=new Set(["text","regex","structural","field"])});function Fm(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function ir(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function Im(e){return e.structuredContent?.results?.[0]?.status}function rw(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function Mm(...e){return e.map(rw).filter(Boolean).join("/")}function ow(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function Dm(e){return rw(e).split("/").filter(Boolean).length}function AD(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function LD(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function _D(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function FD(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(_D).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function iw(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(AD).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!FD(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(LD(o.path)))}function Nm(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function sw(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function aw(e){return typeof e=="string"?[]:e.matches??[]}function Fe(e){return e.from??{kind:"github"}}function cw(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}var Gm=f(()=>{"use strict"});function ID(e,t){return e>0?[]:[C("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function to(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function MD(e){if(Im(e)==="error"){let r=ir(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:to(o.status),retryAfterSeconds:to(o.retryAfter),rateLimitRemaining:to(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:to(n.status),retryAfterSeconds:to(n.retryAfterSeconds),rateLimitRemaining:to(n.rateLimitRemaining)}}function DD(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return C("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?C("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):C("invalidQuery",e.message,{backend:t})}function ND(e,t){let n=MD(e);return n?[DD(n,t)]:Im(e)==="empty"?[C("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function ss(e,t,n){let r=ND(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...ID(t,n)]}var lw=f(()=>{"use strict";te();Gm()});async function uw(e){let t=is(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await we("ghSearchCode",t.query),r=ir(n),o=new Set,i=[];for(let a of r?.files??[]){let c=Nm(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Fe(e),path:c,entryType:"file"}))}let s=Jt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...ss(n,i.length,"ghSearchCode"),...i.length>0?[C("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Fe(e)}]}}async function dw(e){let t=is(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await we("ghSearchCode",t.query),r=ir(n),o=[];for(let s of r?.files??[]){let a=Nm(s),c=sw(s),l=aw(s);if(l.length===0){o.push({kind:"code",source:Fe(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Fe(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=Am(Jt(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...ss(n,o.length,"ghSearchCode"),...o.length>0?[C("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Fe(e)}]}}async function pw(e){let{owner:t,repo:n}=Fm(Fe(e)),r=e.fetch?.content,o=r?.contentView??"standard",i=cw(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Ne(e.scope)??"",type:"file",minify:o,...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await we("ghGetFileContent",s),c=ir(a),l=o,u=c?.pagination,d=c?.results??c?.files??[],m=d.map(h=>{let g=h.pagination??u,y=typeof g?.charOffset=="number",b={...h.startLine!==void 0?{startLine:h.startLine}:{},...h.endLine!==void 0?{endLine:h.endLine}:{},...y?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Fe(e),path:h.path,content:h.content,contentView:l,...Object.keys(b).length?{range:b}:{}}}),p=u??d.find(h=>h.pagination)?.pagination;return{results:m,...p?.hasMore!==void 0?{pagination:{hasMore:!!p.hasMore,...p.currentPage!==void 0?{currentPage:p.currentPage}:{},...p.totalPages!==void 0?{totalPages:p.totalPages}:{},...p.charLength!==void 0?{itemsPerPage:p.charLength}:{},...p.totalChars!==void 0?{totalItems:p.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...ss(a,m.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Fe(e)}]}}async function mw(e){let{owner:t,repo:n}=Fm(Fe(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Ne(e.scope)??"",...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await we("ghViewRepoStructure",r),i=ir(o),s=[],a=Ne(e.scope);for(let u of ow(i?.structure)){let d=u.dir??".";for(let m of u.folders??[]){let p=Mm(a,d,m);s.push({kind:"tree",source:Fe(e),path:p,entryType:"directory",depth:Dm(p)})}for(let m of u.files??[]){let p=Mm(a,d,m);s.push({kind:"tree",source:Fe(e),path:p,entryType:"file",depth:Dm(p)})}}let c=iw(s,e),l=Jt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...ss(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Fe(e)}]}}var fw=f(()=>{"use strict";Xt();zc();On();te();_m();En();lw();Gm()});async function hw(e){switch(e.target){case"content":return pw(e);case"structure":return mw(e);case"files":return uw(e);default:return dw(e)}}var gw=f(()=>{"use strict";fw()});function no(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Hm=f(()=>{"use strict"});function sr(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function bw(e){return GD.test(e)}function Rw(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function ar(e,t,n){if(n){e.langType=n;return}let r=vc(Jr(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=Rw(e.include,r.include))}function HD(e){return Ac(Jr(e))}function yw(e){let t=no(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function ro(e){return!!(e?.include?.length||e?.exclude?.length)}function as(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(yw).filter(i=>!!i);n.length>0&&!e.names&&(e.names=Rw(e.names,n));let r=(t?.include??[]).filter(i=>!yw(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=HD(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function Sw(e,t){if(ro(t.scope)){qc(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function qc(e){e.limit=$c,e.itemsPerPage=$c}function Pw(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function Wc(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}var $c,GD,cr=f(()=>{"use strict";ae();Uc();En();Hm();$c=1e4;GD=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});function Cw(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?Qm(e.predicate):!1}function QD(e){return e.kind==="text"||e.kind==="regex"}function Vc(e){return e?.kind==="not"&&QD(e.predicate)}function Qm(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}function jm(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?jm(e.predicate):!1}function Kc(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(C("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(cs(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(cs(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(cs(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(C("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(cs(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(cs(i));break}r&&n.push(C("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function cs(e){return C("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function Nt(e,t){let n=[];e.status==="error"?n.push(C("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(C("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(C(jD(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function jD(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function Gt(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var oo=f(()=>{"use strict";te()});import Bm from"node:path";async function ww(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await _c(r);return{...Vx(o,t),diagnostics:Nt(o,"localViewStructure"),provenance:[Gt("localViewStructure",t,void 0)]}}async function Tw(e,t,n){let r=e.fetch?.content,o=r?.contentView??"standard",i=BD(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Rc(s);return{...Kx(a,t,n,o),diagnostics:Nt(a,"localGetFileContent"),provenance:[Gt("localGetFileContent",t,void 0)]}}function BD(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function ls(e,t,n){if(!ro(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>zD(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function zD(e,t,n){let r=no(UD(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>xw(r,i))?!1:!(n?.exclude??[]).some(i=>xw(r,i))}function UD(e,t){let n=Bm.relative(t,e);return!n||n.startsWith("..")||Bm.isAbsolute(n)?e:n}function xw(e,t){let n=no(t),r=no(e),o=$D(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Bm.posix.basename(r))}function $D(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=qD(r)}return new RegExp(`${t}$`)}function qD(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}var Yc=f(()=>{"use strict";Fc();Sc();On();cr();oo();Hm()});function Xc(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}function us(e){let t=new Map;for(let n of e)t.set(n.path,Xc(t.get(n.path),n));return t}function Ew(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,Xc(o,i))}return n}function kw(e,t){return new Set([...e].filter(n=>t.has(n)))}var ds=f(()=>{"use strict"});async function zm(e,t,n,r){let o={path:n,entryType:"f"};as(o,e.scope),ro(e.scope)&&(qc(o),o.page=1);let i=await er(o),s=ls(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),us(rs({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function Ow(e,t,n,r,o,i){let s={path:r,details:!0};as(s,e.scope),Kc(t,s,i),ro(e.scope)&&(qc(s),s.page=1);let a=await er(s),c=ls(a,e,r);return o.push({backend:"localFindFiles",source:e.from}),us(rs(c,n).results)}var vw=f(()=>{"use strict";Hi();On();cr();oo();Yc();ds()});async function Aw(e,t,n,r,o,i){let s=Zt(t);if(s.unsupported)return i.push(C(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:$c,...sr(e.scope)};ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await ht(c);return o.push({backend:"localSearchCode",source:e.from}),us((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}async function Lw(e,t,n,r){let o=await ht(Fw(e,n,r.predicate)),i=Nt(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[Gt("localSearchCode",t,r)]}}async function _w(e,t,n,r){let o=await ht(Fw(e,n,r.predicate));return{...eo(o,t),diagnostics:Nt(o,"localSearchCode"),provenance:[Gt("localSearchCode",t,r)]}}function Fw(e,t,n){let o=Zt(n).match,i={path:t,filesWithoutMatch:!0,...sr(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...Wc(e)};return ar(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}var Jc=f(()=>{"use strict";Wr();os();On();te();cr();oo();ds()});async function Iw(e,t,n,r){let o=[],i=[],a=[...(await Zc(e,r,t,n,o,i)).values()].sort(WD(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(C("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function WD(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function Zc(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Zc(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:Ew(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Zc(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,Xc(a.get(l),u));return a}case"not":{let s=await zm(e,n,r,o),a=await Zc(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return Mw(e,t,n,r,o,i)}}async function Mw(e,t,n,r,o,i){return t.kind==="field"?Ow(e,t,n,r,o,i):Aw(e,t,n,r,o,i)}async function Dw(e,t,n){return new Set((await zm(e,e.from,t,n)).keys())}async function Nw(e,t,n,r,o){return new Set((await Mw(e,t,e.from,n,r,o)).keys())}var Um=f(()=>{"use strict";te();vw();Jc();ds()});async function Gw(e,t,n,r){let o=[],i=[],s=await el(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(C("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function el(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>el(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:kw(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>el(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await Dw(e,r,o),a=await el(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await Nw(e,t,r,o,i),rows:[]};default:{let s=await VD(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function VD(e,t,n,r,o,i){let s=Zt(t);if(s.unsupported)return i.push(C(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...sr(e.scope)};ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await ht(c);return o.push({backend:"localSearchCode",source:n}),eo(l,n).results}var Hw=f(()=>{"use strict";Wr();os();On();te();cr();Um();ds()});async function tl(e,t,n){let r=e.where;if(Cw(r))return Gw(e,t,n,r);if(e.view==="discovery"&&Vc(r))return _w(e,t,n,r);let o=Zt(r);if(o.unsupported)return{results:[],diagnostics:[C(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...sr(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...Wc(e)};ar(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await ht(s),c=eo(a,t),l=Nt(a,"localSearchCode"),u=KD(a);if(u.length>0){let d=u.reduce((p,h)=>p+(h.total??0),0),m=u.reduce((p,h)=>p+h.shown,0);l.push(C("matchTruncated",`${u.length} file(s) have more matches (showed ${m} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(C("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&bw(i.keywords)&&l.push(C("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[Gt("localSearchCode",t,r)]}}function KD(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}var $m=f(()=>{"use strict";Wr();os();On();te();cr();oo();Hw();Jc()});async function Qw(e,t,n){let r=e.where;if(Vc(r))return Lw(e,t,n,r);if(r&&Qm(r))return Iw(e,t,n,r);if(r&&jm(r)){let l=await tl({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};as(o,e.scope),Sw(o,e),Pw(o,e);let i=[];r&&Kc(r,o,i);let s=await er(o),a=ls(s,e,n);return{...rs(a,t),diagnostics:[...i,...Nt(a,"localFindFiles")],provenance:[Gt("localFindFiles",t,r)]}}var jw=f(()=>{"use strict";Hi();On();cr();oo();$m();Um();Jc();Yc()});import YD from"node:fs";import XD from"node:path";function JD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}async function ps(e){let t=e.from,n=JD(e),r=Ne(e.scope),o=r?XD.join(n,r):n;if(!YD.existsSync(o))return{results:[],diagnostics:[C("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return Qw(e,t,o);case"structure":return ww(e,t,o);case"content":return Tw(e,t,o);default:return tl(e,t,o)}}var qm=f(()=>{"use strict";te();$m();jw();Yc();En()});import Bw from"node:path";function zw(e){return[...new Set(e)]}function $w(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function qw(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!Bw.isAbsolute(r.localPath)?Bw.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function Ww(e){if(e.from?.kind!=="github")return ps(e);let t=e.from,{owner:n,repo:r}=$w(t);if(!n||!r)return{results:[],diagnostics:[C("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Ne(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await we("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=qw(s);if(u==="error"||!a)return{results:[],diagnostics:[C("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},m={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:zw([...d.excludeDir??[],".git"]),exclude:zw([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},p=await ps(m);return{...p,diagnostics:[...p.diagnostics,...c?[C("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...p.provenance]}}async function Vw(e){if(e.from?.kind==="materialized"){let p=e.from.localPath;return{results:[Uw(p,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[C("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=$w(t);if(!n||!r)return{results:[],diagnostics:[C("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:Ne(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await we("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=qw(a);if(d==="error"||!c)return{results:[],diagnostics:[C("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let m=!i;return{results:[Uw(c,t,t.ref,m,l)],diagnostics:l?[C("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function Uw(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var Kw=f(()=>{"use strict";Xt();qm();te();En()});import Wm from"node:path";function nl(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{byVerdict:t,facts:n,edges:r}}function ms(e){let t=e.root,n=[...e.symbols.map(a=>ZD(t,a)),...e.files.map(a=>rN(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>oN(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let{byVerdict:o,facts:i,edges:s}=nl(n);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function ZD(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=eN(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:t.retentionSource==="ast"?"imports":"references",source:t.retentionSource==="ast"?"ast":"ripgrep",confidence:t.retentionSource==="ast"?"exact":"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:tN(r),next:nN(e,t)}}function eN(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function tN(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via AST import/call retention (or lexical fallback); likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable retainers found in analyze (AST import/call scan, then lexical fallback). Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only retained from unreachable code (AST or lexical scan). Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function nN(e,t){let n=Wm.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"none"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function rN(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:Wm.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:Wm.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function oN(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var Yw=f(()=>{"use strict"});var rl=f(()=>{"use strict";Yw()});function Xw(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function Vm(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:Xw(e.relation),verdicts:Xw(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function iN(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function lr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function fs(e,t){if(!iN(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>lr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>lr(i.relation,t)),o=e.why.some(i=>lr(i.claim,t));return n||r||o}function ol(e,t){e.set(t.id,t)}function Jw(e,t,n){lr(t.claim,n)&&e.set(t.id,t)}function hs(e,t,n,r){lr(n.relation,r)&&(ol(e,n.from),ol(e,n.to),t.set(n.id,n))}function Zw(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}var il=f(()=>{"use strict"});import eT from"node:path";function gs(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function nT(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=aN(a.relation);if(!lr(c,i))continue;let l=tT(a.from,e,a.line),u=tT(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||hs(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function aN(e){let t=e.trim();return sN.has(t)?t:"references"}function tT(e,t,n){let r=cN(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function cN(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:eT.isAbsolute(o)?eT.relative(t,o):o,name:i}}var sN,Km=f(()=>{"use strict";il();sN=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});function ur(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??lN),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function rT(e,t,n,r,o,i){let s=t.filter(g=>fs(g,r)),a=ur(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,m=new Map,p={},h={};for(let g of s)p[g.verdict]=(p[g.verdict]??0)+1,h[g.proofStatus]=(h[g.proofStatus]??0)+1;for(let g of c){if(ol(l,g.subject),r.includeFacts)for(let y of g.why)Jw(d,y,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let y of g.retainedBy)hs(l,u,y,r);if(r.direction!=="incoming")for(let y of g.retains??[])hs(l,u,y,r)}for(let y of g.missingProof)m.set(Zw(y),y)}return r.includeEdges&&nT(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:m.size,byVerdict:p,proofStatus:h},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...m.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function oT(e){let{byVerdict:t,facts:n,edges:r}=nl(e);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}var lN,ys=f(()=>{"use strict";rl();il();Km();il();Km();lN=25});function sl(e){if(!e)return[];for(let t of iT){let n=e[t];if(Array.isArray(n))return n}return[e]}function sT(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function aT(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))uN.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function Ym(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function io(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function dN(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??io(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:io(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??io(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??io(t);case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:io(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return io(t)}function vn(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=dN(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}var iT,uN,bs=f(()=>{"use strict";iT=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],uN=new Set([...iT,"pagination","contentPagination","next"])});import{statSync as pN}from"node:fs";import al from"node:path";function cl(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function cT(e,t){if(!t||al.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?al.join(n.base,t):t}function Rs(e){try{let t=al.isAbsolute(e)?e:al.resolve(e);return pN(t).isDirectory()}catch{return!1}}function An(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function bt(e){return e.params??{}}function Ss(e,t){let n={...bt(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}var Ln=f(()=>{"use strict"});function ll(e){return e==="plan"||e==="prove"?e:"analyze"}function mN(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;lT.includes(o)&&t.add(o)}return t.size>0?t:void 0}function uT(e,t){let n=mN(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of lT){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:m,pagination:p}=ur(e,u.length);o[l]=u.slice(d,m),o[`${l}Page`]=p,s=p.itemsPerPage,a=Math.max(a,p.totalPages??1),p.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function dT(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function Xm(e,t){let{status:n,data:r}=kn(e);return n==="error"?[C("invalidQuery",cl(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[C("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function dr(e,t,n,r){let{data:o,status:i}=kn(e),s=Xm(e,n),a=i==="error"?[]:sl(o);a.length===0&&!s.some(m=>m.code==="zeroMatches"||m.severity==="error")&&s.push(C("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=Jt(c,l),d=t==="package"?sT(o):void 0;return{results:vn(a,t,r,aT(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function Jm(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function pT(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:Jm(n,t)}}var lT,pr=f(()=>{"use strict";te();Xt();zc();ys();bs();Ln();lT=["manifests","files","dependencies","symbols","graphFacts"]});function fN(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}async function mT(e){let{owner:t}=An(e.from),n=Ss(e,"limit"),r=typeof n.language=="string"?n.language:fN(e),o=Lc(r);o&&(n.language=o);let i=await we("ghSearchRepos",{...t?{owner:t}:{},...n}),s=dr(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&hN(n)&&s.diagnostics.push(C("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function hN(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function fT(e){let t=await we("npmSearch",{...Ss(e)});return dr(t,"package","npmSearch",e.from??{kind:"npm"})}var hT=f(()=>{"use strict";Xt();te();Uc();pr();Ln()});async function Zm(e){let{owner:t,repo:n}=An(e.from),r=e.target==="commits",o=r?void 0:yN(e),i=r?gN(e):void 0,s=Ss(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await we("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=dr(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?yT(c,o):i?gT(c,i):c}function gN(e){let t=bt(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function gT(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),m=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,m)+(m<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(C("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(C("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function yN(e){let t=bt(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function bN(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
43
- `)}function yT(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=bN(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(C("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(C("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}var bT=f(()=>{"use strict";Xt();te();pr();Ln()});function so(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var ul=f(()=>{"use strict"});import dl from"node:path";function RT(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}async function PT(e){let t=bt(e),{owner:n,repo:r}=An(e.from),o=so(t);if(o.kind==="prPatch"){let i=await we("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return dr(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?RN(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):SN(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[C("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function RN(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[C("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=p=>({results:[],diagnostics:[C("invalidQuery",p,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=Rs(r)?r:dl.dirname(r),s=dl.isAbsolute(t.path)?dl.relative(i,t.path):t.path;if(!s||s.startsWith("..")||s.startsWith("-"))return o(`params.path must resolve inside from.path for a local ref diff (got "${t.path}").`);if(!ST.test(t.baseRef)||!ST.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(dl.sep).join("/")}`,c=p=>Kn("git",["-C",i,"show",`${p}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let p=l.success?u:l,h=l.success?t.headRef:t.baseRef;return o(`git show ${h}:${a} failed: ${p.stderr.trim().split(`
44
- `)[0]||p.error?.message||`exit ${p.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=ef(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[C("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function SN(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[C("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=m=>we("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:m,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=RT(i),c=RT(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(m=>m.status==="error"||typeof m.content!="string");if(l){let m=cl(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[C("invalidQuery",m,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=ef(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[C("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function ef(e,t){let n=e===""?[]:e.split(`
39
+ `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function Hp(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(_p.test(e))return"comment";let o=s0(e,t,r);if(o<0)return"code";let i=a0(e);return i>=0&&o>i?"comment":zP(e,o)?"string":"code"}function s0(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function a0(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function zP(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}var Qp=f(()=>{"use strict";Tc();zp()});function c0(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function l0(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function u0(e,t,n,r,o){if(!e||e.length===0)return 0;let i=Np(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=Gp(l,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Ec(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=de.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=de.exactCaseInsensitive,m.push("case-insensitive match")):u.includes(r)&&(d+=de.substring,m.push("substring match")));let p=c.kind;if(p)d+=d0(p,m);else{let h=Hp(u,r,t.id,n.caseSensitive);h!=="code"?(d+=de.commentOrStringPenalty,m.push(h==="comment"?"comment match (weak)":"string literal (weak)")):(Ui(t.declaration,u)&&(d+=de.declarationLine,m.push("declaration line")),Ui(t.export,u)&&(d+=de.exportLine,m.push("export/public line")),Ui(t.import,u)&&(d+=de.importLine,m.push("import line")),t.id==="markdown"&&Fp.test(u)&&(d+=de.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&p0(u,r)&&(d+=de.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function d0(e,t){switch(e){case"declaration":return t.push("AST: declaration"),de.declarationLine;case"export":return t.push("AST: export/public"),de.exportLine;case"configKey":return t.push("AST: config key"),de.configKeyLine;case"heading":return t.push("AST: heading"),de.headingLine;case"import":return t.push("AST: import"),de.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),de.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function p0(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function m0(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(xc,"").includes(l))&&(s+=de.pathSegmentToken,i.push("query token in path"))}let a=zi(e);return r.extensions.includes(a)&&t.langType&&(s+=de.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=de.sourceDir,i.push("source file")),s}function f0(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),de.lowSignalPathPenalty):0}function h0(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*de.matchCountScale,r=Math.min(n,de.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function jp(e,t){let n=l0(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>g0(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function g0(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Ec(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function y0(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*de.rareQueryTokenScale,de.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function Bp(e,t,n){let r=Ip(e.path,t.langType,t.profileOverride),o=wc(e.path),i=c0(t.keyword),s=[],a=0;return a+=u0(e.matches,r,t,i,s),a+=m0(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=de.pathUnderQuery,s.push("under requested subtree")),a+=f0(o,t,s),Bi.test(e.path)&&!t.explicitLowSignal&&(a+=de.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=h0(e.matchCount??0,s),a+=y0(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var zp=f(()=>{"use strict";Tc();Qp()});var UP=f(()=>{"use strict";Tc();zp();Qp()});function $P(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=S0(i);s.fetch={tool:"localGetFileContent",query:Up({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"heuristic":"exact"};let a=P0(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Up({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Up({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function S0(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-8),endLine:n+8}}function P0(e,t,n){if(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)return;if(n==="structural")return C0(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.onlyMatching){let o=$p(e?.value);return o?{symbol:o}:void 0}let r=$p(t.keywords);return r?{symbol:r}:void 0}function C0(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=$p(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function $p(e){if(typeof e!="string")return;let t=e.trim();if(R0.test(t)&&!b0.has(t))return t}function Up(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var b0,R0,qp=f(()=>{"use strict";b0=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),R0=/^[A-Za-z_$][A-Za-z0-9_$]*$/});async function kc(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=Dp(e,s,x0(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),m=!!(t.countLinesPerFile||t.countMatchesPerFile),p=d||m,h=c.reduce((H,K)=>H+(K.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??h:h,y=t,b=Math.min(y.itemsPerPage||Dt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=y.page||1,x=Math.max(1,Math.ceil(u/b)),k=(S-1)*b,E=Math.min(k+b,u),_=c.slice(k,E),w=y.maxMatchesPerFile||Dt.DEFAULT_MATCHES_PER_PAGE,G=_.map(H=>{let K=H.matches?.length??0,I=Math.ceil(K/w),ye=Math.max(1,y.matchPage||1),Te=(ye-1)*w,nn=Math.min(Te+w,K),uo=p?void 0:H.matches?.slice(Te,nn),vs=uo?.length,po=l?.get(H.path);return{path:H.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:H.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:H.matchCount||1}:{totalMatchRows:K,...vs!==void 0?{returnedMatchRows:vs}:{}},...uo!==void 0&&{matches:uo},...po?{ranking:{score:po.score,profile:po.profile,pathRole:po.pathRole,reasons:po.reasons}}:{},pagination:!p&&K>w?{currentPage:ye,totalPages:I,matchesPerPage:w,totalMatches:K,hasMore:ye<I,...ye<I?{nextMatchPage:ye+1}:{}}:void 0}}),M=G.filter(H=>H.pagination?.hasMore),A=$P(G,t,n,{isFileListMode:p,currentPage:S,totalFilePages:x,matchPage:y.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:M.length>0}),q={searchEngine:n,...o?{stats:o}:{},files:G,pagination:{currentPage:S,totalPages:x,filesPerPage:b,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<x,...S<x?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return qP(q,t,{totalMatches:g,totalFiles:u})}function qP(e,t,n){return e}function x0(e){let t=e.rankingProfile,n=!!(e.include?.length||Mp(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var WP=f(()=>{"use strict";Gi();UP();qp()});var Oc=f(()=>{"use strict";WP();qp()});function VP(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&w0(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&T0(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function w0(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function T0(e){return/\(\?[=!<]/.test(e)}var KP=f(()=>{"use strict";Ee()});import{validateRipgrepQuery as E0}from"@octocodeai/octocode-core/schemas/runtime";function k0(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function O0(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:k0(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function v0(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function YP(e){let t=[],n=E0(e);if(!n.isValid)return N(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=jt.safeParse(e);if(!r.success){let g=r.error.issues.map(y=>y.message);return N(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return N(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=ft(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=VP({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return N(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(O0(a))}catch(g){return N(g instanceof Error?g:new Error(String(g)),o,{toolName:v.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(y=>{let b={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(b.count=y.count),y.kind!==void 0&&(b.kind=y.kind),y.scoreHint!==void 0&&(b.scoreHint=y.scoreHint),b})})),m=v0(d),p={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return W({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...l]},m);!a.filesOnly&&m>Dt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let h=await kc(d,o,"rg",[...t,...l],p);return W(h,m)}var XP=f(()=>{"use strict";Vt();Fs();Gi();pe();Oc();KP();ue();Ee()});var JP,ZP,eC=f(()=>{"use strict";JP={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},ZP={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});function A0(e){return e.trim().replace(/^\./,"").toLowerCase()}function tr(e){if(!e?.trim())return;let t=A0(e),n=JP[t]??ZP[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function L0(e){return[...e??[]].map(t=>`**/*.${t}`)}function Wp(e){return[...e??[]].map(t=>`*.${t}`)}function $i(e){let t=tr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function vc(e){let t=tr(e);return t?t.kind==="extension"&&t.extension?{include:L0([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function Ac(e){let t=tr(e);return t?t.kind==="extension"&&t.extension?Wp([t.extension]):t.kind==="language"?Wp(t.extensions):t.normalized?Wp([t.normalized]):[]:[]}function Vp(e){let t=tr(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Lc(e){return tr(e)?.canonicalLanguage}var tC=f(()=>{"use strict";eC()});var Kp=f(()=>{"use strict";tC()});import{readFile as _0,stat as F0}from"node:fs/promises";function N0(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function rC(e){return e.include?.length?e.include:Vp(e.langType)}async function G0(e){try{return(await F0(e)).isFile()}catch{return!1}}async function H0(e,t){let n=await _0(e,"utf8"),r=await D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function oC(e){let t=ft(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await G0(t.sanitizedPath)?await H0(t.sanitizedPath,e):await D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...rC(e)?{include:rC(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:nC.length?{excludeDir:nC}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??I0,maxFileBytes:M0})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return N(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:v.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(D0+N0(e.pattern)),await kc(r,e,"structural",i,o)}var nC,I0,M0,D0,iC=f(()=>{"use strict";Ee();Vt();pe();Kp();Oc();nC=[],I0=2e3,M0=1e6,D0="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function Q0(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function ht(e){let t=Q0(e);if(t.mode==="structural")return await oC(t);t.contextLines===void 0&&(t.contextLines=2);try{return await YP(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:$.OUTPUT_TOO_LARGE}:N(n,t,{toolName:v.LOCAL_RIPGREP})}}var Vr=f(()=>{"use strict";Vt();Wn();pe();XP();iC()});async function sC(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=ot(jt,n);return r.ok===!1?r.error:await ht(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var aC=f(()=>{"use strict";Fs();pe();Ke();Vr();De();Vn();Oc()});function z0(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function cC(e,t){let n=e[t];return n===void 0?!1:j0.has(n)||n==="{"&&q0(e,t)}function U0(e,t,n){let r=n.pop()??!1,o=cC(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?uC(e,t+1):t+1})}function $0(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:uC(e,t)})}function lC(e){if(e.length>B0)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=z0(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=U0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(cC(e,r)){let i=$0(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function q0(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function uC(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var j0,B0,dC=f(()=>{"use strict";j0=new Set(["+","*","?"]),B0=1e3});function pC(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!lC(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function mC(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function fC(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var hC=f(()=>{"use strict";dC()});async function _c(e){try{let t=ft(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return W0(e,t.sanitizedPath,n)}catch(t){let n=mt.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function W0(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=K0(e),s=r&&e.limit&&!V0(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:Y0(e),limit:s})}catch(x){return Z0(x,e,t)}let c=a.entries.map(x=>X0(x,n,e.details??!1)),l=pC(c,e),u=e.sortBy??"name";l=l.sort((x,k)=>{let E=0;switch(u){case"size":{let _=x.sizeBytes??(x.size?Hi(x.size):0),w=k.sizeBytes??(k.size?Hi(k.size):0);E=_-w;break}case"time":n&&x.modified&&k.modified?E=x.modified.localeCompare(k.modified):E=x.name.localeCompare(k.name);break;case"extension":E=(x.extension||"").localeCompare(k.extension||"");break;default:E=x.name.localeCompare(k.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:m,pagination:p}=NP(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(x=>({...fC(x),path:x.path??`${t.replace(/\/$/,"")}/${x.name}`}))}:{path:t,...mC(m)},y=[...a.warnings,...Cc({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],b=d===0,S=DP(l);return W(gC({...b?{status:"empty"}:{},...g,summary:S,...p.hasMore||p.totalPages>1?{pagination:p}:{},...p.hasMore?{next:{nextPage:Ls(v.LOCAL_VIEW_STRUCTURE,{...e,page:p.currentPage+1},"Continue to the next page of directory entries.")}}:{},...y.length>0&&{warnings:y}},e),a.entries.reduce((x,k)=>x+k.path.length,0))}function V0(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function K0(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function Y0(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function X0(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:Wr(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=J0(e.permissions)),o}function J0(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function Z0(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=mt.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return N(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function gC(e,t){return e}var Fc=f(()=>{"use strict";Pc();pe();Vt();yc();hC();vp();ue();Ee();Be()});async function yC(e){let{queries:t}=e;return me(t||[],async n=>ut({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=ot(Nn,n);return r.ok===!1?r.error:await _c(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var bC=f(()=>{"use strict";Il();pe();Ke();Fc();De();Vn();Fc()});function tM(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function RC(e,t){if(t===void 0||t==="progressIdle")return e;let n=tM(e);if(!n||!eM.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}var eM,SC=f(()=>{"use strict";eM=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as nM,stat as rM}from"node:fs/promises";import{SymbolResolver as oM,SymbolResolutionError as iM}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as Ic}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function Yp(e,t){let n=e.uri,r=ft({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await rM(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:Ic.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:Ic.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await nM(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:Ic.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function PC(e,t){let n=await Yp(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new oM({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:sM(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof iM)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:Ic.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function sM(e){return{start:e,end:{line:e.line,character:e.character}}}var Xp=f(()=>{"use strict";Vt()});function Zp(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function em(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Zp(e.type,t),reason:t}}}function gt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Zp(e,n),reason:n}}}function yt(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}var Tn,Mc,Jp,Dc=f(()=>{"use strict";kt();Tn=40,Mc=40,Jp=10});function qi(e,t,n,r,o){let i=o.length>0,s=o.map(El),{pageItems:a,pagination:c}=yt(s,e.page??1,e.itemsPerPage??Mc);return{type:e.type,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function tm(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?CC(r):void 0,i=o??r.map(El),{pageItems:s,pagination:a}=yt(i,e.page??1,e.itemsPerPage??Mc),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function nm(e,t,n){let r=xC(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function CC(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function xC(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>wC(r)).join(`
40
+ `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function wC(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var TC=f(()=>{"use strict";kt();Dc()});import{safeReadFile as aM}from"@octocodeai/octocode-engine/lsp/validation";function Wi(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function kC(e,t,n){if(t<=0)return e;let r=await aM(e.uri);if(!r)return e;let o=li(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
41
+ `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function cM(e,t){return Promise.all(e.map(async n=>({...n,from:await kC(n.from,t,n.fromRanges)})))}async function lM(e,t){return Promise.all(e.map(async n=>({...n,to:await kC(n.to,t)})))}async function rm(e,t,n,r,o){if(n<=0||!e)return{calls:[],...EC};try{let i=await e.getIncomingCalls(t),s=o>0?await cM(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Wi(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),rm(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function om(e,t,n,r,o){if(n<=0||!e)return{calls:[],...EC};try{let i=await e.getOutgoingCalls(t),s=o>0?await lM(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Wi(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),om(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var EC,OC=f(()=>{"use strict";Fr();EC={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function AC(e){return W(e,j(e))}function LC(e,t){return e.format!=="compact"||!FC(t)?t:dM(t)}function _C(e){if(!FC(e))return e;let n=e.payload.locations?.[0],r=n?.displayRange?.startLine;if(!n?.uri||typeof r!="number")return e;let o=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri;return{...e,next:{readSite:{tool:"localGetFileContent",query:{path:o,startLine:Math.max(1,r-3),endLine:(n.displayRange?.endLine??r)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}function FC(e){return nr(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&nr(e.payload)}function dM(e){return{...e,format:"compact",payload:pM(e.payload)}}function pM(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(vC)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(fM)}:{locations:(e.locations??[]).map(vC)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:IC(e.root)}:{},direction:e.direction,calls:e.calls.map(hM),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(mM)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function mM(e){if(!nr(e))return String(e);let t=Xe(e,"line"),n=Xe(e,"character"),r=Xe(e,"endLine"),o=Kt(e,"kind"),i=Kt(e,"name"),s=Xe(e,"childCount"),a=Kt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function vC(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${DC(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function fM(e){if(!nr(e))return String(e);let t=Kt(e,"uri"),n=Xe(e,"firstLine"),r=Xe(e,"firstCharacter"),o=Xe(e,"count"),i=MC(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function hM(e){if(!nr(e))return String(e);let t=Kt(e,"direction"),n=IC(e.item),r=MC(e,"ranges").map(gM).join(","),o=Xe(e,"rangeCount"),i=Xe(e,"rangeSampleCount"),s=Kt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${DC(s,180)}`:""].filter(Boolean).join(" ")}function IC(e){if(!nr(e))return String(e);let t=Kt(e,"name"),n=Kt(e,"kind"),r=Kt(e,"uri"),o=Xe(e,"line"),i=Xe(e,"endLine"),s=Xe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function gM(e){return nr(e)?`${Xe(e,"line")}:${Xe(e,"character")}`:String(e)}function nr(e){return typeof e=="object"&&e!==null}function Kt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Xe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function MC(e,t){let n=e[t];return Array.isArray(n)?n:[]}function DC(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}function NC(e,t){let n=HC(e.fromRanges);return{direction:"incoming",item:Nc(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...QC(e.from,t)}}function GC(e,t){let n=HC(e.fromRanges);return{direction:"outgoing",item:Nc(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...QC(e.to,t)}}function Nc(e){return{name:e.name,kind:Kr(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function HC(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=uM))break}return n}function QC(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Kr(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}var uM,Vi=f(()=>{"use strict";ue();uM=8});async function im(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return gt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await rm(n,o,i,new Set([Wi(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await om(n,o,i,new Set([Wi(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),m=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],p=m.map(S=>S.direction==="incoming"?NC(S,e.contextLines??0):GC(S,e.contextLines??0)),{pageItems:h,pagination:g}=yt(p,e.page??1,e.itemsPerPage??Jp),y=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",b=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Nc(o),direction:y,calls:h,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:b,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function sm(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return gt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=yt(s,e.page??1,e.itemsPerPage??Tn);return{type:e.type,uri:t.uri,resolvedSymbol:Qt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}var jC=f(()=>{"use strict";OC();kt();Vi();Dc()});var Ki=f(()=>{"use strict";Dc();TC();jC()});import Yi from"node:path";import{readFile as yM}from"node:fs/promises";import{resolveImportAliasDefinitions as bM}from"@octocodeai/octocode-engine/lsp/resolver";async function UC(e,t,n){if(typeof e.openDocument=="function")try{let r=Yi.extname(t.uri).slice(1),o=BC.includes(r)?BC:[r],i=await ht({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:RM,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=Yi.isAbsolute(a)?a:Yi.join(n,a);if(Yi.resolve(c)!==Yi.resolve(t.uri))try{let l=await yM(c,"utf-8");if(l.length>SM)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function $C(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?qi(e,t,"definition","definitionProvider",await bM({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):gt(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?qi(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):gt(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?qi(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):gt(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?tm(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):gt(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?nm(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):gt(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?im(e,t,n):gt(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?sm(e,t,n):gt(e.type,t,"typeHierarchyProvider unsupported",!0)}}var zC,RM,SM,BC,qC=f(()=>{"use strict";Vr();Ki();zC=new Set(["references","callers","callees","callHierarchy","implementation"]),RM=12,SM=512*1024,BC=["ts","tsx","mts","cts","js","jsx","mjs","cjs"]});import cm from"node:path";import{fileURLToPath as PM}from"node:url";import{unavailableHintFor as CM}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as xM}from"@octocodeai/octocode-engine/lsp/config";function WC(e){return am||(am=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),am.has(cm.extname(e).toLowerCase())}function Tt(e,t){let n=xM(e),r=CM(n,void 0);throw new je($.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function VC(e,t){let n=e.startsWith("file://")?PM(e):e;return cm.isAbsolute(n)?n:cm.resolve(t,n)}function lm(){return[...D.getSupportedJsTsExtensions(),...wM]}function KC(){return lm().map(e=>`**/*.${e}`)}async function YC(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:KC(),excludeDir:[...TM],maxSnippetChars:1})).files[0]?.path}catch{return}}async function um(e,t){if(e.uri)return VC(e.uri,t);let n=await YC(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:lm(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function dm(e){return e instanceof Error?e.message:String(e)}function pm(e,t){if(!WC(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var am,wM,TM,Gc=f(()=>{"use strict";Oa();Wn();Ee();wM=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];TM=[".git","node_modules","dist","out","coverage","target"]});import{acquirePooledClient as EM,isLanguageServerAvailable as kM}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as OM}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function hm(e){let t=await Yp(e,Ie);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await OM(t.value.uri),r=await kM(t.value.uri,n),o=r?await EM(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=pm(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let y=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(y)?y:[],a="lsp"}else{let y=Sy(t.value.content,t.value.uri);y&&(s=y,a="markdown")}let l=a!==void 0;!l&&!r&&Tt(t.value.uri,"documentSymbols");let u=XC(s),d=ZC(s),{pageItems:m,pagination:p}=yt(u,e.page??1,e.itemsPerPage??Tn),h=ex(u,y=>y.kind),g=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:m.length,topLevelSymbols:d,kinds:h},payload:{kind:"documentSymbols",symbols:m,...g?{empty:g}:{}},pagination:p}}function XC(e){let t=[];for(let n of e)gm(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function gm(e,t,n){if(!e||typeof e!="object")return;let r=e,o=JC(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Kr(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&vM.has(Kr(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)gm(s,t,i)}}function JC(e){if(mm(e.range))return e.range;let t=e.location;return t&&mm(t.range)?t.range:void 0}function mm(e){if(!e||typeof e!="object")return!1;let t=e;return fm(t.start)&&fm(t.end)}function fm(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function ZC(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function ex(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}var vM,tx=f(()=>{"use strict";sa();kt();Xp();Ki();Vi();Gc();vM=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});import nx from"node:path";import{acquirePooledClient as rx,isLanguageServerAvailable as ox}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as AM}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function ym(e){let t=e.symbolName??"",n=nx.resolve(e.workspaceRoot??process.cwd()),r=await um(e,n);await ox(r,n)||Tt(r,"workspaceSymbol");let i=await rx(n,r);if(i||Tt(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{nx.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${dm(u)}`}}}let a=ix(s),{pageItems:c,pagination:l}=yt(a,e.page??1,e.itemsPerPage??Tn);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function ix(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:Kr(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function bm(e){let t=e.uri??"",n=e.workspaceRoot??(t?await AM(t):process.cwd());await ox(t,n)||Tt(t,"diagnostic");let o=await rx(n,t);if(o||Tt(t,"diagnostic"),!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let i=await o.getDiagnostics(t),s=sx(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=yt(s,e.page??1,e.itemsPerPage??Tn);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function sx(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>ax(r))}return[]}function ax(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}var cx=f(()=>{"use strict";Ki();Vi();Gc()});var lx=f(()=>{"use strict";Gc();tx();cx()});import{acquirePooledClient as LM,isLanguageServerAvailable as _M}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as FM}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function ux(e){return me(e.queries||[],async t=>ut({toolName:Ie,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await IM(t);return AC(_C(LC(t,n)))}}),{toolName:Ie,minQueryTimeoutMs:3e4},e)}async function IM(e){if(e.type==="documentSymbols")return hm(e);if(e.type==="workspaceSymbol")return ym(e);if(e.type==="diagnostic")return bm(e);let t=await PC(e,Ie);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return em(e,a)}let n=e.workspaceRoot??await FM(t.value.uri);await _M(t.value.uri,n)||Tt(t.value.uri,e.type);let o=await LM(n,t.value.uri);o||Tt(t.value.uri,e.type),zC.has(e.type)&&await UC(o,t.value,n);let i=o.getReadiness?.(),s=await $C(e,t.value,o);return RC(s,i)}var dx=f(()=>{"use strict";Ke();Vn();kt();SC();Xp();qC();Ki();lx();Vi()});function C(e,t,n={}){let r=n.severity??(DM.has(e)?"error":"warning"),o=n.blocksAnswer??(MM.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function px(e){return e.some(t=>t.blocksAnswer)}var MM,DM,Yt,te=f(()=>{"use strict";MM=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),DM=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);Yt=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});function J(...e){throw new Yt(e)}function rr(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var Yr=f(()=>{"use strict";te()});import{z as T}from"zod";function fx(e,t){let n=WM[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var Oe,NM,mx,GM,HM,QM,jM,BM,zM,UM,$M,qM,WM,hx=f(()=>{"use strict";Oe=T.number().int().min(1),NM=T.number().int().min(0),mx=T.enum(["symbols","files","dependencies","relations"]),GM=T.object({match:T.enum(["file","path"]).optional(),concise:T.boolean().optional(),extension:T.string().optional(),filename:T.string().optional(),page:Oe.optional(),limit:Oe.optional()}).passthrough(),HM=T.object({type:T.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:T.string().optional(),symbolName:T.string().optional(),symbolKind:T.string().optional(),lineHint:Oe.optional(),orderHint:T.number().int().optional(),includeDeclaration:T.boolean().optional(),depth:T.number().int().min(0).max(20).optional(),groupByFile:T.boolean().optional(),workspaceRoot:T.string().optional(),format:T.enum(["structured","compact"]).optional(),page:Oe.optional(),itemsPerPage:Oe.optional()}).passthrough(),QM=T.object({keywords:T.array(T.string()).optional(),topicsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:T.string().optional(),owner:T.string().optional(),stars:T.union([T.string(),T.number()]).optional(),forks:T.string().optional(),goodFirstIssues:T.string().optional(),size:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),license:T.string().optional(),match:T.array(T.enum(["name","description","readme"])).optional(),visibility:T.enum(["public","private"]).optional(),archived:T.boolean().optional(),sort:T.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:T.boolean().optional(),page:Oe.optional()}).passthrough(),jM=T.object({packageName:T.string().optional(),keywords:T.array(T.string()).optional(),mode:T.enum(["lean","full"]).optional(),page:Oe.optional()}).passthrough(),BM=T.object({prNumber:Oe.optional(),concise:T.boolean().optional(),state:T.enum(["open","closed","merged"]).optional(),author:T.string().optional(),label:T.union([T.string(),T.array(T.string())]).optional(),keywordsToSearch:T.union([T.string(),T.array(T.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:T.string().optional(),base:T.string().optional(),created:T.string().optional(),updated:T.string().optional(),closed:T.string().optional(),"merged-at":T.string().optional(),draft:T.boolean().optional(),archived:T.boolean().optional(),sort:T.enum(["created","updated","best-match","comments","reactions"]).optional(),order:T.enum(["asc","desc"]).optional(),reviewMode:T.string().optional(),filePage:Oe.optional(),commentPage:Oe.optional(),commitPage:Oe.optional(),charOffset:NM.optional(),charLength:Oe.optional(),minify:T.enum(["none","standard"]).optional(),limit:Oe.optional(),page:Oe.optional(),matchString:T.string().optional(),matchScope:T.enum(["body","title","comments","reviews","all"]).optional(),content:T.record(T.string(),T.unknown()).optional()}).passthrough(),zM=T.object({path:T.string().optional(),branch:T.string().optional(),since:T.string().optional(),until:T.string().optional(),author:T.string().optional(),includeDiff:T.boolean().optional(),limit:Oe.optional(),page:Oe.optional()}).passthrough(),UM=T.object({prNumber:Oe.optional(),files:T.array(T.string()).optional(),baseRef:T.string().optional(),headRef:T.string().optional(),path:T.string().optional()}).passthrough(),$M=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(mx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:Oe.optional()}).passthrough(),qM=T.object({goal:T.string().optional(),intent:T.enum(["general","reachability","dependencies","symbols"]).optional(),facets:T.array(mx).optional(),mode:T.enum(["plan","analyze","prove"]).optional(),maxFiles:Oe.optional(),subject:T.string().optional(),subjectKind:T.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:T.union([T.string(),T.array(T.string())]).optional(),verdict:T.union([T.string(),T.array(T.string())]).optional(),direction:T.enum(["incoming","outgoing","both"]).optional(),proof:T.enum(["none","lsp"]).optional(),proofLimit:Oe.max(25).optional(),includePackets:T.boolean().optional(),includeFacts:T.boolean().optional(),includeEdges:T.boolean().optional()}).passthrough(),WM={semantics:HM,repositories:QM,packages:jM,pullRequests:BM,commits:zM,diff:UM,research:$M,graph:qM,code:GM}});function gx(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&J(C("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),VM(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Ml.includes(t)||J(C("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function VM(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}var yx=f(()=>{"use strict";te();un();Yr()});function bx(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&J(C("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}var Rx=f(()=>{"use strict";te();Yr()});function Xr(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Xr(n),0):e.kind==="not"?1+Xr(e.predicate):1:0}var Rm=f(()=>{"use strict"});function Sx(e,t){let n=XM(e);e.where&&n&&J(C("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Sm(r,"where"),Pm(r,"where",new Map);let o=dn.safeParse(r);return o.success||J(C("invalidQuery",rr(o.error),{queryPath:"where"})),o.data}function YM(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:KM}function XM(e){let t=n=>{let r=Xr(n),o=YM(e);return r>o&&J(C("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(Jr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(Jr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(Jr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&J(C("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=Jr(e.xor[0]),r=Jr(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(JM(e.oneOf.map(Jr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&J(C("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&J(C("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function Jr(e){if(e&&typeof e=="object"&&"kind"in e)return e;J(C("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function JM(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Sm(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&J(C("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Sm(n,`${t}.of[${r}]`));break;case"not":e.predicate||J(C("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Sm(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&J(C("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":ZM(e,t);break;default:break}}function Pm(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&J(C("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>Pm(r,`${t}.of[${o}]`,n)):e.kind==="not"&&Pm(e.predicate,`${t}.predicate`,n)}function ZM(e,t){if(e.op==="exists"){e.value!==void 0&&J(C("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&J(C("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&J(C("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}var KM,Px=f(()=>{"use strict";Sr();te();Rm();Yr();KM=64});function Cx(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return Cx(e.predicate);default:return!1}}function xx(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:Cx(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}var wx=f(()=>{"use strict"});function Tx(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!tD(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function tD(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return eD.some(n=>t.includes(n))}var eD,Ex=f(()=>{"use strict";eD=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"]});function Xi(e){let t=bh.safeParse(e);t.success||J(C("invalidQuery",rr(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??rD(n);r===void 0&&J(C("invalidQuery",`Could not determine \`target\`; specify one of: ${ln.join(", ")}.`,{queryPath:"target"})),Io.includes(r)&&J(C("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${ln.join(", ")}.`}})),ln.includes(r)||J(C("unknownField",`Unknown target "${r}".`));for(let h of Object.keys(n))nD.has(h)||J(C("unknownField",`Unknown field "${h}" is not part of OQL.`,{queryPath:h}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=gx(n,r),a=bx(n,s),c=Sx(n,r),l=xx(n,s,c,r),u=oD(n),d=Tx(n,r),m={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(m.target==="code"&&!m.where&&J(C("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.where&&J(C("invalidQuery",`target:"${m.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(m.target==="content"||m.target==="structure")&&m.from?.kind==="github"&&!(m.from.repo&&m.from.repo.includes("/"))&&J(C("invalidQuery",`target:"${m.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),m.target==="materialize"&&(m.where&&J(C("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),m.from?.kind!=="github"&&m.from?.kind!=="materialized"&&J(C("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),m.params!==void 0){let h=fx(m.target,m.params);h&&J(C("invalidQuery",h,{queryPath:"params"}))}let p=Ds.safeParse(m);return p.success||J(C("invalidQuery",rr(p.error))),p.data}function rD(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function oD(e){return e.fetch?{...e.fetch}:void 0}var nD,Hc=f(()=>{"use strict";Sr();te();hx();un();Yr();yx();Rx();Px();wx();Ex();nD=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"])});function kx(e){let t=Rh.safeParse(e);t.success||J(C("invalidQuery",rr(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||J(C("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&J(C("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return Xi(i)}catch(a){throw a instanceof Yt?new Yt(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}var Ox=f(()=>{"use strict";Sr();te();Yr();Hc()});function vx(e){return Nl(e)?kx(e):Xi(e)}var Ax=f(()=>{"use strict";un();Ox();Hc();Hc()});function Ji(e){let t=sD(e),n=cD(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function sD(e){return!e.executable||e.diagnostics.some(t=>iD.has(t.code))?"unsupported":e.approximate||aD(e.diagnostics)?"candidate":px(e.diagnostics)||Lx(e)?"partial":"proof"}function aD(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function Lx(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function cD(e){return!e.executable||Lx(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function _x(e){return e.some(t=>!t.exact)}function Qc(e,t,n,r,o){return Ji({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var iD,Zi=f(()=>{"use strict";te();iD=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function jc(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(jc):e.kind==="not"?jc(e.predicate):[e]}function Cm(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function Ne(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Zr(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function xm(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var En=f(()=>{"use strict"});import or from"node:path";import{statSync as lD}from"node:fs";function Fx(e){let t=or.resolve(e);try{if(lD(t).isDirectory())return`${t}${or.sep}`}catch{}return`${or.dirname(t)}${or.sep}`}function Ix(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function Mx(e,t){let n=Ix(e);if(!n)return;let r=Fx(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function Dx(e){let t=Ix(e);if(!t)return;let n=Fx(t).slice(0,-or.sep.length);return r=>({kind:"local",path:or.isAbsolute(r)?r:or.join(n,r)})}var wm=f(()=>{"use strict"});function Nx(e,t){for(let n of t)n.proofGrade??=uD(e,n)}function uD(e,t){return t.kind==="code"?es(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":es(e.where,"text")||es(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?ts(t.data)?"missing":"graph":t.recordType==="research"?ts(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"?"text":"candidate"}function es(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>es(n,t)):e.kind==="not"?es(e.predicate,t):!1:!1}function ts(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!dD(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function dD(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Tm=f(()=>{"use strict"});function pD(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function Gx(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:pD(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"none",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function Hx(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function mD(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function fD(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function Qx(e){let t=fD(e);return t?mD(t,"materialized"):void 0}function jx(e,t){return zx(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function Bx(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(ts(r))return zx(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function zx(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!ts(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=gD(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function gD(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&hD.has(o));return r.length>0?r:void 0}var hD,Ux=f(()=>{"use strict";Tm();hD=new Set(["symbols","files","dependencies","relations"])});import ns from"node:path";import{statSync as yD}from"node:fs";function $x(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=SD(e)??PD(t.query),i=bD(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"none",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function bD(e,t){if(e&&ns.isAbsolute(e))return e;if(t&&ns.isAbsolute(t)){let n=RD(t);return e?ns.resolve(n,e):t}return t??e}function RD(e){try{return yD(e).isDirectory()?e:ns.dirname(e)}catch{return ns.dirname(e)}}function SD(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function PD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}var qx=f(()=>{"use strict"});function CD(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function xD(e){let t=CD(e),n=Ne(e.scope),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${Wx(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${Wx(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function Wx(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function Vx(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${xD(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:Dx(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=wD[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function Kx(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||Em(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function Em(e,t){return e.why===t.why&&e.confidence===t.confidence}var wD,km=f(()=>{"use strict";En();wm();Ux();qx();wD={code:Gx,content:Hx,"record:materialized":Qx,"record:semantics":$x,"record:research":jx,"record:graph":Bx}});function we(e,t){return Bc(e,{queries:[{...TD,...t}]})}function kn(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function eo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function rs(e){return typeof e=="string"?e:void 0}var TD,Xt=f(()=>{"use strict";Om();TD={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function Jt(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var zc=f(()=>{"use strict"});function vm(e){return Jt(e)}function ED(e){if(e)return Jt({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function to(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges,c=i;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...c.kind!==void 0?{matchKind:c.kind}:{},...c.scoreHint!==void 0?{scoreHint:c.scoreHint}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:Am(ED(e.pagination),n.length)}}function Am(e,t,n=!1){if(e)return e.totalItemsKind!=="files"&&!n?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function os(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:vm(e.pagination)}}function Yx(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:vm(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=OD(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:vm(e.pagination)}}function OD(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=kD[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function Xx(e,t,n,r="standard"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var kD,On=f(()=>{"use strict";zc();kD={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});function Jx(e){return JSON.stringify(e)}function Lm(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${Jx(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${Jx(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Lm(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=Lm(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function Zx(e){return["rule:",...Lm(e,1)].join(`
42
+ `)}var ew=f(()=>{"use strict"});function tw(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function nw(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return tw(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),tw(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=Zx(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function Zt(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return nw(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=nw(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var is=f(()=>{"use strict";ew()});var Uc=f(()=>{"use strict";Kp()});function rw(e,t,n){let r=e.where,o=r?jc(r):[],i=r&&vD.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>C("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function AD(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function ss(e,t={}){if(!e.where)return{ok:!1,diagnostics:[C("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=AD(e.where);if(n){let m=ow(e,t);if(m.length>0)return{ok:!1,diagnostics:m};let{owner:p,repo:h}=Cm(e.from),g=e.params??{},y=typeof g.extension=="string"||typeof n.extension=="string"?{}:$i(Zr(e.scope)),b=xm(e),S=Ne(e.scope);return rw(e,{...p?{owner:p}:{},...h?{repo:h}:{},...y,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...b?{limit:b}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=Zt(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[C("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=ow(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[C("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Cm(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:$i(Zr(e.scope)),u=xm(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return rw(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...Ne(e.scope)?{path:Ne(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function ow(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(C("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(C("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var vD,_m=f(()=>{"use strict";is();te();Uc();En();vD=new Set(["text","regex","structural","field"])});function Fm(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function ir(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function Im(e){return e.structuredContent?.results?.[0]?.status}function iw(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function Mm(...e){return e.map(iw).filter(Boolean).join("/")}function sw(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function Dm(e){return iw(e).split("/").filter(Boolean).length}function LD(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function _D(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function FD(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ID(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(FD).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function aw(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(LD).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!ID(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(_D(o.path)))}function Nm(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function cw(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function lw(e){return typeof e=="string"?[]:e.matches??[]}function Fe(e){return e.from??{kind:"github"}}function uw(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}var Gm=f(()=>{"use strict"});function MD(e,t){return e>0?[]:[C("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function no(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function DD(e){if(Im(e)==="error"){let r=ir(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:no(o.status),retryAfterSeconds:no(o.retryAfter),rateLimitRemaining:no(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:no(n.status),retryAfterSeconds:no(n.retryAfterSeconds),rateLimitRemaining:no(n.rateLimitRemaining)}}function ND(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return C("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?C("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):C("invalidQuery",e.message,{backend:t})}function GD(e,t){let n=DD(e);return n?[ND(n,t)]:Im(e)==="empty"?[C("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function as(e,t,n){let r=GD(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...MD(t,n)]}var dw=f(()=>{"use strict";te();Gm()});async function pw(e){let t=ss(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await we("ghSearchCode",t.query),r=ir(n),o=new Set,i=[];for(let a of r?.files??[]){let c=Nm(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Fe(e),path:c,entryType:"file"}))}let s=Jt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...as(n,i.length,"ghSearchCode"),...i.length>0?[C("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Fe(e)}]}}async function mw(e){let t=ss(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await we("ghSearchCode",t.query),r=ir(n),o=[];for(let s of r?.files??[]){let a=Nm(s),c=cw(s),l=lw(s);if(l.length===0){o.push({kind:"code",source:Fe(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Fe(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=Am(Jt(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...as(n,o.length,"ghSearchCode"),...o.length>0?[C("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Fe(e)}]}}async function fw(e){let{owner:t,repo:n}=Fm(Fe(e)),r=e.fetch?.content,o=r?.contentView??"standard",i=uw(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Ne(e.scope)??"",type:"file",minify:o,...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await we("ghGetFileContent",s),c=ir(a),l=o,u=c?.pagination,d=c?.results??c?.files??[],m=d.map(h=>{let g=h.pagination??u,y=typeof g?.charOffset=="number",b={...h.startLine!==void 0?{startLine:h.startLine}:{},...h.endLine!==void 0?{endLine:h.endLine}:{},...y?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Fe(e),path:h.path,content:h.content,contentView:l,...Object.keys(b).length?{range:b}:{}}}),p=u??d.find(h=>h.pagination)?.pagination;return{results:m,...p?.hasMore!==void 0?{pagination:{hasMore:!!p.hasMore,...p.currentPage!==void 0?{currentPage:p.currentPage}:{},...p.totalPages!==void 0?{totalPages:p.totalPages}:{},...p.charLength!==void 0?{itemsPerPage:p.charLength}:{},...p.totalChars!==void 0?{totalItems:p.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...as(a,m.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Fe(e)}]}}async function hw(e){let{owner:t,repo:n}=Fm(Fe(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Ne(e.scope)??"",...Fe(e).kind==="github"&&Fe(e).ref?{branch:Fe(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await we("ghViewRepoStructure",r),i=ir(o),s=[],a=Ne(e.scope);for(let u of sw(i?.structure)){let d=u.dir??".";for(let m of u.folders??[]){let p=Mm(a,d,m);s.push({kind:"tree",source:Fe(e),path:p,entryType:"directory",depth:Dm(p)})}for(let m of u.files??[]){let p=Mm(a,d,m);s.push({kind:"tree",source:Fe(e),path:p,entryType:"file",depth:Dm(p)})}}let c=aw(s,e),l=Jt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...as(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Fe(e)}]}}var gw=f(()=>{"use strict";Xt();zc();On();te();_m();En();dw();Gm()});async function yw(e){switch(e.target){case"content":return fw(e);case"structure":return hw(e);case"files":return pw(e);default:return mw(e)}}var bw=f(()=>{"use strict";gw()});function ro(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Hm=f(()=>{"use strict"});function sr(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function Sw(e){return HD.test(e)}function Pw(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function ar(e,t,n){if(n){e.langType=n;return}let r=vc(Zr(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=Pw(e.include,r.include))}function QD(e){return Ac(Zr(e))}function Rw(e){let t=ro(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function oo(e){return!!(e?.include?.length||e?.exclude?.length)}function cs(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(Rw).filter(i=>!!i);n.length>0&&!e.names&&(e.names=Pw(e.names,n));let r=(t?.include??[]).filter(i=>!Rw(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=QD(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function Cw(e,t){if(oo(t.scope)){qc(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function qc(e){e.limit=$c,e.itemsPerPage=$c}function xw(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function Wc(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}var $c,HD,cr=f(()=>{"use strict";ae();Uc();En();Hm();$c=1e4;HD=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});function ww(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?Qm(e.predicate):!1}function jD(e){return e.kind==="text"||e.kind==="regex"}function Vc(e){return e?.kind==="not"&&jD(e.predicate)}function Qm(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}function jm(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?jm(e.predicate):!1}function Kc(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(C("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(ls(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(ls(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(ls(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(C("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(ls(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(ls(i));break}r&&n.push(C("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function ls(e){return C("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function Nt(e,t){let n=[];e.status==="error"?n.push(C("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(C("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(C(BD(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function BD(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function Gt(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var io=f(()=>{"use strict";te()});import Bm from"node:path";async function Ew(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await _c(r);return{...Yx(o,t),diagnostics:Nt(o,"localViewStructure"),provenance:[Gt("localViewStructure",t,void 0)]}}async function kw(e,t,n){let r=e.fetch?.content,o=r?.contentView??"standard",i=zD(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Rc(s);return{...Xx(a,t,n,o),diagnostics:Nt(a,"localGetFileContent"),provenance:[Gt("localGetFileContent",t,void 0)]}}function zD(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function us(e,t,n){if(!oo(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>UD(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function UD(e,t,n){let r=ro($D(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>Tw(r,i))?!1:!(n?.exclude??[]).some(i=>Tw(r,i))}function $D(e,t){let n=Bm.relative(t,e);return!n||n.startsWith("..")||Bm.isAbsolute(n)?e:n}function Tw(e,t){let n=ro(t),r=ro(e),o=qD(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Bm.posix.basename(r))}function qD(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=WD(r)}return new RegExp(`${t}$`)}function WD(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}var Yc=f(()=>{"use strict";Fc();Sc();On();cr();io();Hm()});function Xc(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}function ds(e){let t=new Map;for(let n of e)t.set(n.path,Xc(t.get(n.path),n));return t}function Ow(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,Xc(o,i))}return n}function vw(e,t){return new Set([...e].filter(n=>t.has(n)))}var ps=f(()=>{"use strict"});async function zm(e,t,n,r){let o={path:n,entryType:"f"};cs(o,e.scope),oo(e.scope)&&(qc(o),o.page=1);let i=await er(o),s=us(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),ds(os({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function Aw(e,t,n,r,o,i){let s={path:r,details:!0};cs(s,e.scope),Kc(t,s,i),oo(e.scope)&&(qc(s),s.page=1);let a=await er(s),c=us(a,e,r);return o.push({backend:"localFindFiles",source:e.from}),ds(os(c,n).results)}var Lw=f(()=>{"use strict";Qi();On();cr();io();Yc();ps()});async function _w(e,t,n,r,o,i){let s=Zt(t);if(s.unsupported)return i.push(C(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:$c,...sr(e.scope)};ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await ht(c);return o.push({backend:"localSearchCode",source:e.from}),ds((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}async function Fw(e,t,n,r){let o=await ht(Mw(e,n,r.predicate)),i=Nt(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[Gt("localSearchCode",t,r)]}}async function Iw(e,t,n,r){let o=await ht(Mw(e,n,r.predicate));return{...to(o,t),diagnostics:Nt(o,"localSearchCode"),provenance:[Gt("localSearchCode",t,r)]}}function Mw(e,t,n){let o=Zt(n).match,i={path:t,filesWithoutMatch:!0,...sr(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...Wc(e)};return ar(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}var Jc=f(()=>{"use strict";Vr();is();On();te();cr();io();ps()});async function Dw(e,t,n,r){let o=[],i=[],a=[...(await Zc(e,r,t,n,o,i)).values()].sort(VD(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(C("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function VD(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function Zc(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Zc(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:Ow(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Zc(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,Xc(a.get(l),u));return a}case"not":{let s=await zm(e,n,r,o),a=await Zc(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return Nw(e,t,n,r,o,i)}}async function Nw(e,t,n,r,o,i){return t.kind==="field"?Aw(e,t,n,r,o,i):_w(e,t,n,r,o,i)}async function Gw(e,t,n){return new Set((await zm(e,e.from,t,n)).keys())}async function Hw(e,t,n,r,o){return new Set((await Nw(e,t,e.from,n,r,o)).keys())}var Um=f(()=>{"use strict";te();Lw();Jc();ps()});async function Qw(e,t,n,r){let o=[],i=[],s=await el(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(C("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function el(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>el(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:vw(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>el(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await Gw(e,r,o),a=await el(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await Hw(e,t,r,o,i),rows:[]};default:{let s=await KD(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function KD(e,t,n,r,o,i){let s=Zt(t);if(s.unsupported)return i.push(C(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...sr(e.scope)};ar(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await ht(c);return o.push({backend:"localSearchCode",source:n}),to(l,n).results}var jw=f(()=>{"use strict";Vr();is();On();te();cr();Um();ps()});async function tl(e,t,n){let r=e.where;if(ww(r))return Qw(e,t,n,r);if(e.view==="discovery"&&Vc(r))return Iw(e,t,n,r);let o=Zt(r);if(o.unsupported)return{results:[],diagnostics:[C(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...sr(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...Wc(e)};ar(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await ht(s),c=to(a,t),l=Nt(a,"localSearchCode"),u=YD(a);if(u.length>0){let d=u.reduce((p,h)=>p+(h.total??0),0),m=u.reduce((p,h)=>p+h.shown,0);l.push(C("matchTruncated",`${u.length} file(s) have more matches (showed ${m} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(C("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&Sw(i.keywords)&&l.push(C("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[Gt("localSearchCode",t,r)]}}function YD(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}var $m=f(()=>{"use strict";Vr();is();On();te();cr();io();jw();Jc()});async function Bw(e,t,n){let r=e.where;if(Vc(r))return Fw(e,t,n,r);if(r&&Qm(r))return Dw(e,t,n,r);if(r&&jm(r)){let l=await tl({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};cs(o,e.scope),Cw(o,e),xw(o,e);let i=[];r&&Kc(r,o,i);let s=await er(o),a=us(s,e,n);return{...os(a,t),diagnostics:[...i,...Nt(a,"localFindFiles")],provenance:[Gt("localFindFiles",t,r)]}}var zw=f(()=>{"use strict";Qi();On();cr();io();$m();Um();Jc();Yc()});import XD from"node:fs";import JD from"node:path";function ZD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}async function ms(e){let t=e.from,n=ZD(e),r=Ne(e.scope),o=r?JD.join(n,r):n;if(!XD.existsSync(o))return{results:[],diagnostics:[C("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return Bw(e,t,o);case"structure":return Ew(e,t,o);case"content":return kw(e,t,o);default:return tl(e,t,o)}}var qm=f(()=>{"use strict";te();$m();zw();Yc();En()});import Uw from"node:path";function $w(e){return[...new Set(e)]}function Ww(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function Vw(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!Uw.isAbsolute(r.localPath)?Uw.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function Kw(e){if(e.from?.kind!=="github")return ms(e);let t=e.from,{owner:n,repo:r}=Ww(t);if(!n||!r)return{results:[],diagnostics:[C("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Ne(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await we("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=Vw(s);if(u==="error"||!a)return{results:[],diagnostics:[C("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},m={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:$w([...d.excludeDir??[],".git"]),exclude:$w([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},p=await ms(m);return{...p,diagnostics:[...p.diagnostics,...c?[C("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...p.provenance]}}async function Yw(e){if(e.from?.kind==="materialized"){let p=e.from.localPath;return{results:[qw(p,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[C("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=Ww(t);if(!n||!r)return{results:[],diagnostics:[C("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:Ne(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await we("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=Vw(a);if(d==="error"||!c)return{results:[],diagnostics:[C("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let m=!i;return{results:[qw(c,t,t.ref,m,l)],diagnostics:l?[C("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function qw(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var Xw=f(()=>{"use strict";Xt();qm();te();En()});import Wm from"node:path";function nl(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{byVerdict:t,facts:n,edges:r}}function fs(e){let t=e.root,n=[...e.symbols.map(a=>eN(t,a)),...e.files.map(a=>oN(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>iN(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let{byVerdict:o,facts:i,edges:s}=nl(n);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function eN(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=tN(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:t.retentionSource==="ast"?"imports":"references",source:t.retentionSource==="ast"?"ast":"ripgrep",confidence:t.retentionSource==="ast"?"exact":"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:nN(r),next:rN(e,t)}}function tN(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function nN(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via AST import/call retention (or lexical fallback); likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable retainers found in analyze (AST import/call scan, then lexical fallback). Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only retained from unreachable code (AST or lexical scan). Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function rN(e,t){let n=Wm.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"none"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function oN(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:Wm.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:Wm.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function iN(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var Jw=f(()=>{"use strict"});var rl=f(()=>{"use strict";Jw()});function Zw(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function Vm(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:Zw(e.relation),verdicts:Zw(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function sN(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function lr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function hs(e,t){if(!sN(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>lr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>lr(i.relation,t)),o=e.why.some(i=>lr(i.claim,t));return n||r||o}function ol(e,t){e.set(t.id,t)}function eT(e,t,n){lr(t.claim,n)&&e.set(t.id,t)}function gs(e,t,n,r){lr(n.relation,r)&&(ol(e,n.from),ol(e,n.to),t.set(n.id,n))}function tT(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}var il=f(()=>{"use strict"});import nT from"node:path";function ys(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function oT(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=cN(a.relation);if(!lr(c,i))continue;let l=rT(a.from,e,a.line),u=rT(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||gs(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function cN(e){let t=e.trim();return aN.has(t)?t:"references"}function rT(e,t,n){let r=lN(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function lN(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:nT.isAbsolute(o)?nT.relative(t,o):o,name:i}}var aN,Km=f(()=>{"use strict";il();aN=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});function ur(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??uN),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function iT(e,t,n,r,o,i){let s=t.filter(g=>hs(g,r)),a=ur(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,m=new Map,p={},h={};for(let g of s)p[g.verdict]=(p[g.verdict]??0)+1,h[g.proofStatus]=(h[g.proofStatus]??0)+1;for(let g of c){if(ol(l,g.subject),r.includeFacts)for(let y of g.why)eT(d,y,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let y of g.retainedBy)gs(l,u,y,r);if(r.direction!=="incoming")for(let y of g.retains??[])gs(l,u,y,r)}for(let y of g.missingProof)m.set(tT(y),y)}return r.includeEdges&&oT(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:m.size,byVerdict:p,proofStatus:h},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...m.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function sT(e){let{byVerdict:t,facts:n,edges:r}=nl(e);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}var uN,bs=f(()=>{"use strict";rl();il();Km();il();Km();uN=25});function sl(e){if(!e)return[];for(let t of aT){let n=e[t];if(Array.isArray(n))return n}return[e]}function cT(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function lT(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))dN.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function Ym(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function so(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function pN(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??so(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:so(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??so(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??so(t);case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:so(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return so(t)}function vn(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=pN(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}var aT,dN,Rs=f(()=>{"use strict";aT=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],dN=new Set([...aT,"pagination","contentPagination","next"])});import{statSync as mN}from"node:fs";import al from"node:path";function cl(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function uT(e,t){if(!t||al.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?al.join(n.base,t):t}function Ss(e){try{let t=al.isAbsolute(e)?e:al.resolve(e);return mN(t).isDirectory()}catch{return!1}}function An(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function bt(e){return e.params??{}}function Ps(e,t){let n={...bt(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}var Ln=f(()=>{"use strict"});function ll(e){return e==="plan"||e==="prove"?e:"analyze"}function fN(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;dT.includes(o)&&t.add(o)}return t.size>0?t:void 0}function pT(e,t){let n=fN(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of dT){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:m,pagination:p}=ur(e,u.length);o[l]=u.slice(d,m),o[`${l}Page`]=p,s=p.itemsPerPage,a=Math.max(a,p.totalPages??1),p.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function mT(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function Xm(e,t){let{status:n,data:r}=kn(e);return n==="error"?[C("invalidQuery",cl(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[C("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function dr(e,t,n,r){let{data:o,status:i}=kn(e),s=Xm(e,n),a=i==="error"?[]:sl(o);a.length===0&&!s.some(m=>m.code==="zeroMatches"||m.severity==="error")&&s.push(C("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=Jt(c,l),d=t==="package"?cT(o):void 0;return{results:vn(a,t,r,lT(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function Jm(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function fT(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:Jm(n,t)}}var dT,pr=f(()=>{"use strict";te();Xt();zc();bs();Rs();Ln();dT=["manifests","files","dependencies","symbols","graphFacts"]});function hN(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}async function hT(e){let{owner:t}=An(e.from),n=Ps(e,"limit"),r=typeof n.language=="string"?n.language:hN(e),o=Lc(r);o&&(n.language=o);let i=await we("ghSearchRepos",{...t?{owner:t}:{},...n}),s=dr(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&gN(n)&&s.diagnostics.push(C("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function gN(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function gT(e){let t=await we("npmSearch",{...Ps(e)});return dr(t,"package","npmSearch",e.from??{kind:"npm"})}var yT=f(()=>{"use strict";Xt();te();Uc();pr();Ln()});async function Zm(e){let{owner:t,repo:n}=An(e.from),r=e.target==="commits",o=r?void 0:bN(e),i=r?yN(e):void 0,s=Ps(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await we("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=dr(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?RT(c,o):i?bT(c,i):c}function yN(e){let t=bt(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function bT(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),m=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,m)+(m<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(C("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(C("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function bN(e){let t=bt(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function RN(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
43
+ `)}function RT(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=RN(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(C("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(C("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}var ST=f(()=>{"use strict";Xt();te();pr();Ln()});function ao(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var ul=f(()=>{"use strict"});import dl from"node:path";function PT(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}async function xT(e){let t=bt(e),{owner:n,repo:r}=An(e.from),o=ao(t);if(o.kind==="prPatch"){let i=await we("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return dr(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?SN(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):PN(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[C("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function SN(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[C("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=p=>({results:[],diagnostics:[C("invalidQuery",p,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=Ss(r)?r:dl.dirname(r),s=dl.isAbsolute(t.path)?dl.relative(i,t.path):t.path;if(!s||s.startsWith("..")||s.startsWith("-"))return o(`params.path must resolve inside from.path for a local ref diff (got "${t.path}").`);if(!CT.test(t.baseRef)||!CT.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(dl.sep).join("/")}`,c=p=>Kn("git",["-C",i,"show",`${p}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let p=l.success?u:l,h=l.success?t.headRef:t.baseRef;return o(`git show ${h}:${a} failed: ${p.stderr.trim().split(`
44
+ `)[0]||p.error?.message||`exit ${p.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=ef(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[C("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function PN(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[C("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=m=>we("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:m,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=PT(i),c=PT(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(m=>m.status==="error"||typeof m.content!="string");if(l){let m=cl(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[C("invalidQuery",m,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=ef(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[C("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function ef(e,t){let n=e===""?[]:e.split(`
45
45
  `),r=t===""?[]:t.split(`
46
46
  `),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let p=o-1;p>=0;p--)for(let h=i-1;h>=0;h--)s[p][h]=n[p]===r[h]?s[p+1][h+1]+1:Math.max(s[p+1][h],s[p][h+1]);let a=[],c=0,l=0,u=0,d=0,m=0;for(;d<o&&m<i;)n[d]===r[m]?(a.push(` ${n[d]}`),u++,d++,m++):s[d+1][m]>=s[d][m+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[m]}`),c++,m++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;m<i;)a.push(`+ ${r[m++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
47
- `)}}var ST,CT=f(()=>{"use strict";Xt();te();ul();_a();pr();Ln();ST=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/});import Ge from"node:path";function PN(e,t,n){let r=t??n??".";if(!e)return r;if(Ge.isAbsolute(e))return e;if(n&&Ge.isAbsolute(n))return Ge.resolve(n,e);if(t&&Ge.isAbsolute(t)){let o=Rs(t)?t:Ge.dirname(t);return Ge.resolve(o,e)}return e}function xT(){return C("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function CN(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(C("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(C("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push(xT()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push(xT());let i=e?.pagination;return i?.hasMore&&n.push(C("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:Jm(i,t)})),n}async function wT(e){let t,n,r=[],o=[],i=bt(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let E=e.from.path,_=Rs(E);n=c??(_?Ge.resolve(E):void 0),t=a??(_?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=Ne(e.scope),_=E?Ge.isAbsolute(E)?E:Ge.join(e.from.localPath,E):void 0;s?(n=c??e.from.localPath,t=a??_):t=a??_??e.from.localPath}else if(e.from?.kind==="github"){let{owner:E,repo:_}=An(e.from);if(!E||!_)return o.push(C("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,G=Ne(e.scope),M=w&&!Ge.isAbsolute(w)?w:G,A=await we("ghCloneRepo",{owner:E,repo:_,...e.from.ref?{branch:e.from.ref}:{},...M?{sparsePath:M}:{}}),q=kn(A).data,H=cT(A,q?.localPath);if(!H)return o.push(C("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:H}),s?(n=c??H,w?t=Ge.isAbsolute(w)?w:Ge.join(H,w):G&&(t=Ge.isAbsolute(G)?G:Ge.join(H,G))):w?t=Ge.isAbsolute(w)?w:Ge.join(H,w):G?t=Ge.isAbsolute(G)?G:Ge.join(H,G):t=H}if(!t&&!n)return o.push(C("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...m}=i,p=await we("lspGetSemantics",{...m,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:h,status:g}=kn(p),y=h,b=pT(y,e),S=PN(ns(y?.uri),t,n),x=TN(e,S),k=wN(xN(y),u);return{results:g==="error"?[]:vn(k,"semantics",x),...b?{pagination:b}:{},diagnostics:[...o,...Xm(p,"lspGetSemantics"),...CN(y,e)],provenance:[...r,{backend:"lspGetSemantics",source:x}]}}function xN(e){if(!e)return[];let n=(Ym(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=ns(e.uri);return n.map(o=>Ym(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return sl(e)}function wN(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function TN(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}var TT=f(()=>{"use strict";Xt();te();En();bs();pr();Ln()});import{builtinModules as EN}from"node:module";var tf,ET,kT,OT,Ps=f(()=>{"use strict";tf=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],ET="package.json",kT=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),OT=new Set(EN.flatMap(e=>[e,`node:${e}`]))});import pl from"node:path";function ml(){if(Cs)return Cs;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Cs=new Set(e.length>0?e:tf)}catch{Cs=new Set(tf)}return Cs}function vT(){if(xs)return xs;try{let e=JSON.parse(D.getGraphFactCapabilities());xs=Array.isArray(e)?e.filter(kN):[]}catch{xs=[]}return xs}function kN(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function nf(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function fl(e,t,n){return hl(pl.resolve(e,t),n)}function hl(e,t){let n=ml(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(pl.join(e,`index${o}`));return r.find(o=>t.has(o))}function ws(e){return e.startsWith("./")||e.startsWith("../")}function AT(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function LT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function rf(e){return typeof e=="string"&&e.trim()?e:void 0}function gl(e){return typeof e=="string"&&e.length>0}function _T(e){return typeof e=="string"}function FT(e){return[...new Set(e)]}function Ht(e,t){return pl.relative(e,t)||pl.basename(t)}function IT(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function MT(e,t){return!!(e===t||e.endsWith(`.${t}`)||e.endsWith(`::${t}`))}var Cs,xs,Ts=f(()=>{"use strict";Ee();Ps()});import en from"node:path";import{readFile as ON,readdir as vN}from"node:fs/promises";async function DT(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await vN(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(kT.has(s.name))continue;await r(en.join(o,s.name));continue}s.isFile()&&n.push(en.join(o,s.name))}}return await r(e),n}async function NT(e){return(await Promise.all(e.map(async n=>AN(n)))).filter(n=>n!==null)}async function AN(e){let t=await LN(e);if(!t)return null;let n=en.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=LT(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:rf(t.name),deps:r,entrypoints:_N(n,t)}}async function LN(e){try{let t=JSON.parse(await ON(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function _N(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=rf(t[o]);i&&n.add(en.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(en.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(en.resolve(e,o));GT(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(en.resolve(e,o));return[...n]}function GT(e,t,n){if(typeof t=="string"){n.add(en.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))GT(e,r,n)}function HT(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=FN(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:Ht(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:Ht(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:Ht(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function FN(e,t){return t.filter(r=>e.startsWith(`${r.dir}${en.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}var QT=f(()=>{"use strict";Ps();Ts()});import ao from"node:path";import{readFile as IN}from"node:fs/promises";async function jT(e,t){let n=ml(),r=t.filter(i=>n.has(ao.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await IN(i,"utf8").catch(()=>""),a=ao.extname(i).toLowerCase(),c=MN(s,i,Ht(e,i)),l=FT(c?c.imports.map(u=>u.specifier):DN(s));return{path:i,rel:Ht(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!ws(u)).map(AT).filter(gl).filter(u=>!OT.has(u)),...c?{graphFacts:c}:{}}}))}function MN(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??ao.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(_T):[]}}catch{return}}function of(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...ml()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=nf(e,l=>l.language),s=nf(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function DN(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function BT(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,ao.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??ao.dirname(o.path);for(let a of o.imports){if(!ws(a))continue;let c=fl(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function zT(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=hl(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","lib.rs","main.rs","mod.rs"]){let s=hl(ao.resolve(e,i),r);s&&o.add(s)}return[...o]}function UT(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}var $T=f(()=>{"use strict";Ee();Ps();Ts()});import NN from"node:path";import{readFile as qT}from"node:fs/promises";async function WT(e){return(await Promise.all(e.map(async n=>{let r=GN(n);if(r.length>0)return r;let o=await qT(n.path,"utf8").catch(()=>"");return HN(n.rel,o)}))).flat()}function GN(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function HN(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:IT(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function VT(e,t,n){let r=new Map(t.map(a=>[a.rel,a])),o=new Map(t.map(a=>[a.path,a])),i=new Set(t.map(a=>a.path)),s=QN(t);return e.map(a=>{let c=r.get(a.file),l=jN(a,t,c,s,i,o),u=l.length>0?"ast":"ripgrep",d=l.length>0?l:t.filter(g=>g.rel!==a.file&&BN(g.path,a.symbol)).map(g=>g.rel),m=d.filter(g=>{let y=r.get(g);return y?n.has(y.path):!1}),p=c?n.has(c.path):!1,h=m.length>0?"reachable":d.length>0?"transitive-dead":p?"candidate-unused-export":"unused-export";return{symbol:a.symbol,kind:a.kind,file:a.file,line:a.line,evidenceSource:a.evidenceSource,retentionSource:u,directRefs:d.length,externalRefs:m.length,retainedBy:d,verdict:h}})}function QN(e){let t=new Map;for(let n of e){let r=n.graphFacts;if(r){for(let o of r.declarations){if(!o.exported)continue;let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}for(let o of r.exports){let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}}}return t}function jN(e,t,n,r,o,i){let s=r.get(e.symbol)??(n?new Set([n.path]):new Set),a=new Set;for(let c of t){if(c.rel===e.file)continue;let l=c.graphFacts;if(l){for(let u of l.imports){let d=u.importedName&&u.importedName!=="default"?u.importedName:void 0,m=u.localName;if(!(d===e.symbol||m===e.symbol)||!ws(u.specifier))continue;let h=fl(NN.dirname(c.path),u.specifier,o);if(h&&s.has(h)){a.add(c.rel);break}}if(!a.has(c.rel)){for(let u of l.calls)if(MT(u.callee,e.symbol)){a.add(c.rel);break}}}}return[...a].sort()}function BN(e,t){return sf.get(e)?.has(t)??!1}async function KT(e){sf.clear(),await Promise.all(e.map(async t=>{let n=await qT(t.path,"utf8").catch(()=>"");sf.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}var sf,YT=f(()=>{"use strict";Ts();sf=new Map});import zN from"node:path";async function yl(e){let t=zN.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=UN(r,e.intent,e.facets),i=$N(o,e.facets),s=qN(o,i),a=vT();if(n==="plan")return WN({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:of([],[],a)});let c=await DT(t,e.maxFiles??5e3),l=await NT(c.filter(w=>w.endsWith(ET))),u=await jT(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),m=of(u,d,a);await KT(u);let p=new Set(l.map(w=>w.name).filter(gl)),h=BT(u),g=zT(t,l,u),y=UT(g,h),b=u.filter(w=>!y.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=HT(t,l,u,p),x=await WT(u),k=VT(x,u,y),E=k.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,_=k.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:y.size,unusedFiles:b.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:k.length,candidateUnusedExports:E,transitiveDeadExports:_,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,G)=>w+G.declarations.length,0),nativeGraphCalls:d.reduce((w,G)=>w+G.calls.length,0)},manifests:l.map(w=>({manifest:Ht(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(G=>Ht(t,G)),dependencyCount:[...w.deps.keys()].length})),files:b,dependencies:S,symbols:k,graphFacts:d,graphCapabilities:m,caveats:["Analyze uses native AST graph facts for inventory and preferred cross-file retention (named imports / call callees). Lexical token scan is fallback only when AST finds no retainers.",'Graph facts are syntax inventory, not semantic identity. Upgrade candidates with target:graph proof:"lsp" (or lspGetSemantics references/callers) before destructive cleanup.',"Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function UN(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function $N(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function qN(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["extractGraphFacts","export regex fallback"],produces:["symbols","lineHints"],evidence:"heuristic"},{id:"reference-scan",purpose:"Candidate cross-file retention from native AST imports/calls (preferred) with lexical token fallback. Upgrade via target:graph proof:lsp \u2014 analyze does not run LSP.",tools:["extractGraphFacts","token scan fallback"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"heuristic"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function WN(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}var af=f(()=>{"use strict";QT();$T();YT();Ps();Ts()});async function XT(e){let t=bt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[C("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=ll(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[C("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await yl({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[C("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:ms(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?ur(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?uT(e,i):{fields:{}},m={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:gs(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},p=dT(l?.pagination,d.pagination);return{results:vn([m],"research",e.from),...p?{pagination:p}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}var JT=f(()=>{"use strict";te();af();rl();ys();pr();bs();Ln()});import bl from"node:path";function lf(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function eE(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function tE(e,t,n,r,o){let i=n.filter(l=>fs(l,r)),s=ur(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await KN(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(C(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(C("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),VN(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(C("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function VN(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function KN(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=bl.isAbsolute(t.subject.uri)?t.subject.uri:bl.resolve(e,t.subject.uri);try{let i=await we("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=YN(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=kn(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:ns(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,m=Zr(a?.totalReferences)??Zr(u?.totalReferences)??Zr(a?.referenceCount)??Zr(u?.referenceCount)??Zr(d?.totalItems)??ZT(u)??ZT(a);return{status:"ok",...typeof m=="number"?{totalReferences:m}:{},files:XN(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function YN(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function ZT(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function XN(e,t){let n=new Set;return cf(e,n,t),[...n].slice(0,25)}function cf(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)cf(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&JN(i)&&t.add(bl.isAbsolute(i)?bl.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])cf(r[o],t,n)}function JN(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var nE=f(()=>{"use strict";Xt();te();ys()});async function rE(e){let t=bt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[C("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=ll(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[C("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await yl({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[C("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:ms(i),a=Vm(t),c=s?.packets??[],l=lf(i.mode,t)?await tE(n,e,c,a,eE(e,t)):[],u=oT(c),d=rT(e,c,u,a,i.graphFacts,n),m=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[lf(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],p={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:gs(i.graphFacts),caveats:m};return{results:vn([p],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var oE=f(()=>{"use strict";te();af();rl();ys();nE();pr();bs();Ln()});var iE,sE=f(()=>{"use strict";hT();bT();CT();TT();JT();oE();iE={repositories:mT,packages:fT,pullRequests:Zm,commits:Zm,diff:PT,semantics:wT,research:XT,graph:rE}});function aE(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&ZN.has(e.target)&&t.push(C("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "none" or "standard".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "none" or "standard".'}})),t}var ZN,cE=f(()=>{"use strict";te();ZN=new Set(["pullRequests","commits","diff"])});function lE(e){let t={schema:Rt.schema,view:e.view??Rt.view,page:e.page??Rt.page,itemsPerPage:e.itemsPerPage??Rt.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??Rt.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??Rt.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??Rt.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?Rt.detailedCodeContext:Rt.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??Rt.localSearchSort),t}var Rt,uE=f(()=>{"use strict";Rt={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"standard",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function eG(e){return e?.mode==="auto"||e?.mode==="required"}function tG(e,t){let n=e.target==="files"?mr:_n;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:_n,exact:!0,reason:`${t.kind} evaluated locally by ${_n}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function nG(e,t,n){let r=eG(e.materialize);if(n)return rG(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:mr,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:mr,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:tn,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:mr,exact:!0,reason:`${Rl(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:mr,exact:!1,reason:`GitHub cannot enumerate files by ${Rl(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Rl(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:_n,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:_n,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:tn,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?uf(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:_n,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return uf(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:mr,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:tn,exact:!0,reason:"path/name predicate pushed to provider"}:uf(e,`field "${t.field}"`,r)}}function Rl(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function rG(e,t,n){let r=Rl(t);return n?{route:"ROUTE",backend:e.target==="files"?mr:_n,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:tn,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function uf(e,t,n){if(n)return{route:"ROUTE",backend:_n,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:tn,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function dE(e,t,n=!1){return e.sourceKind==="github"?nG(e,t,n):tG(e,t)}var _n,mr,tn,pE=f(()=>{"use strict";_n="localSearchCode",mr="localFindFiles",tn="ghSearchCode"});function co(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return df.find(n=>n.id===`${t}.diff.${e.variant}`)}return df.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function pf(e){return df.find(t=>t.id===e)}function mf(e){let t=oG(e.source,e.target);if(e.target==="diff"){let n=so(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return co({sourceKind:t,target:"diff",variant:r})}return co({sourceKind:t,target:e.target})}function mE(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function fE(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function oG(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var df,hE=f(()=>{"use strict";ul();df=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function iG(e,t){return e.id??t}function Sl(e,t,n,r,o,i=!1){let s=iG(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,m)=>Sl(e,d,`${n}.of[${m}]`,r,o,i)),l=sG(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(C("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=Sl(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=dE(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(C(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&gE(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:aG(e.target),exact:a.exact}),a.route}function sG(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function aG(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function gE(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Pl(e,t){if(!t)return;let n=fE(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Es(e,t,n){if(!t)return!1;for(let r of mE(t,n))gE(e.backendCalls,r);return!0}function yE(e,t){return ff(e,t,"files")}function ff(e,t,n,r=co({sourceKind:"materialized",target:n})){let o=co({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Pl(e,o),Pl(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),Es(e,o,t),Es(e,r,void 0),!0}function Cl(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Cl):e.kind==="not"?Cl(e.predicate):!1:!1}function bE(e){return e.target==="code"?pf(Cl(e.where)?"local.code.structural":"local.code.textRegex"):co({sourceKind:"materialized",target:e.target})}function RE(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?pf(Cl(e.where)?"local.code.structural":"local.code.textRegex")??mf({source:t,target:e.target,params:e.params}):mf({source:t,target:e.target,params:e.params})}var SE=f(()=>{"use strict";pE();te();hE()});function PE(e){return e.kind==="not"&&e.predicate.kind==="not"?PE(e.predicate.predicate):e}function CE(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Dl[e.target]:void 0;if(n)return n.includes(t)?[]:[C("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[C("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function xE(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=PE(e.where),r=is({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function wE(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(C("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(C("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var TE=f(()=>{"use strict";te();_m();un()});function EE(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=RE(e,o);if(Pl(n,s),e.where)Sl(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(h=>h.route==="ROUTE")&&ff(n,o,e.target,bE(e));else if(e.target==="diff"){let h=so(e.params);h.kind==="prPatch"||h.kind==="directFile"?Es(n,s,o)||n.diagnostics.push(C("unsupportedTarget",`No transformer registered for target:"diff" lane "${h.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(C("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let h=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(h?g&&yE(n,o):Es(n,s,o))&&(!h||g)&&n.diagnostics.push(C("unsupportedTarget",h?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(C("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...xE(e,n.nodes)),n.diagnostics.push(...CE(e)),n.diagnostics.push(...aE(e));let a=wE(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??Rt.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(C("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=Yr(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(C("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let m={input:t,normalized:e,defaults:lE(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},p=!n.nodes.some(h=>h.route==="UNSUPPORTED")&&!n.diagnostics.some(h=>h.severity==="error"&&h.code!=="planTruncated");return{plan:m,executable:p}}var kE=f(()=>{"use strict";ul();cE();te();uE();Rm();SE();TE()});function cG(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function OE(e,t,n,r,o,i){let s=o&&i?lG(i):[],a=o&&i?uG(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:Qc(e.plan.diagnostics,t,n,r,cG(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function lG(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[C("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function uG(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}var vE=f(()=>{"use strict";te();Ji()});function AE(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):pG.has(c)?o.add(c):mG.has(c)?o.add("data"):fG.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!dG.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[C("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}var dG,pG,mG,fG,LE=f(()=>{"use strict";te();dG=new Set(["kind","source","recordType","id","proofGrade"]),pG=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","matchKind","scoreHint","proofGrade","size","modified","entryType","depth","children","data"]),mG=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),fG=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});function ks(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function xl(e,t,n,r){let o=EE(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return OE(o,s,e.id,r,n.dryRun,e);let a=await yG(e,o);Fx(e,a.results),hG(e,a),gG(a);let c=qx(e,a);Mx(e,a.results);let l=AE(e,a.results),u=Wx(a.results);return Xi({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:Ax(o.plan.backendCalls),plan:s})}function hG(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function gG(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}async function yG(e,t){if(e.target==="materialize")return Vw(e);let n=iE[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?ps(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?Ww(e):hw(e)}var hf=f(()=>{"use strict";gw();qm();Kw();sE();Ji();kE();km();vE();wm();Tm();LE()});async function _E(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await xl(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=bG(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&ks(o.merged.results)}else for(let i of r)ks(i.envelope.results);return o}function bG(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let m=CG(d);n.has(m)||(n.add(m),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),RG(s,u.envelope.nextHints),SG(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),PG(u.envelope)&&(l=!0)}return l&&o.push(C("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Xi({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function RG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||Em(o,r))&&(e[n]=r)}}function SG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function PG(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function CG(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var FE=f(()=>{"use strict";te();Ji();km();hf()});var IE={};KE(IE,{runOqlSearch:()=>xG});async function xG(e,t={}){let n;try{n=kx(e)}catch(o){if(o instanceof Yt)return Qc(o.diagnostics);throw o}if(Gl(n))return _E(n,e,t);let r=await xl(n,e,t);return ks(r.results),r}var ME=f(()=>{"use strict";Ox();te();Ji();un();FE();hf()});async function NE(e){let t=wG(e),n=Hn.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(ME(),IE)),o=await r(n.data,{authInfo:e.authInfo});return TG(o)}function wG(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function TG(e){let t=EG(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function EG(e){return Hl(e)?{results:e.children.map(t=>DE(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:GE(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[DE(e,e.queryId??"oqlSearch-1")]}}function DE(e,t){let n=GE(e);return{id:e.queryId??t,...OG(e),data:n}}function GE(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||kG(d,u)){let{why:m,confidence:p,...h}=l;s[c]=h,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function kG(e,t){return e.why===t.why&&e.confidence===t.confidence}function OG(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var HE=f(()=>{"use strict";Rr();un()});var gf,QE=f(()=>{"use strict";pe();gf={hasTool(e){return zu(e)},getDescription(e){return Bu[e]??""},getToolName(e){return v[e]??String(e)}}});function vG(e,t){return t.getToolName(e)}function Et(e,t,n){let r=vG(t,e);return{...n,name:r,description:yf(r,e)}}function AG(e=gf){let t=Et(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:yo,inputSchema:bo,executionFn:WR,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=Et(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Fn,inputSchema:go,executionFn:DR,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=Et(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:xo,inputSchema:wo,executionFn:US,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=Et(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:So,inputSchema:Po,executionFn:BS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=Et(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:In,inputSchema:Ro,executionFn:kS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=Et(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:To,inputSchema:Eo,executionFn:pP,security:"remote",requiresServerRuntime:!0}}),a=Et(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:yr,inputSchema:fo,executionFn:Zb,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=Et(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:jt,inputSchema:vo,executionFn:oC,security:"basic"}}),l=Et(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Nn,inputSchema:Ao,executionFn:hC,security:"basic"}}),u=Et(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Dn,inputSchema:Oo,executionFn:NP,security:"basic"}}),d=Et(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Mn,inputSchema:ko,executionFn:_P,security:"basic"}}),m={name:Ie,description:yf(Ie,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Lo,inputSchema:_o,executionFn:cx,security:"basic",requiresServerRuntime:!0}},p={name:rn,description:yf(rn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:Io,inputSchema:Hn,executionFn:NE,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},h=[t,n,r,o,i,s,a,c,l,u,d,m,...po()?[p]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,OQL_SEARCH:p,ALL_TOOLS:h}}var yf,Je,Jne,Zne,ere,tre,nre,rre,ore,ire,sre,are,cre,lre,ure,jE,BE=f(()=>{"use strict";zl();eR();NR();VR();OS();zS();$S();mP();FP();GP();iC();gC();lx();HE();kt();mo();QE();yf=(e,t=gf)=>t.getDescription(e);Je=AG(),Jne=Je.GITHUB_SEARCH_CODE,Zne=Je.GITHUB_FETCH_CONTENT,ere=Je.GITHUB_VIEW_REPO_STRUCTURE,tre=Je.GITHUB_SEARCH_REPOSITORIES,nre=Je.GITHUB_SEARCH_PULL_REQUESTS,rre=Je.PACKAGE_SEARCH,ore=Je.GITHUB_CLONE_REPO,ire=Je.LOCAL_RIPGREP,sre=Je.LOCAL_VIEW_STRUCTURE,are=Je.LOCAL_FIND_FILES,cre=Je.LOCAL_FETCH_CONTENT,lre=Je.LSP_GET_SEMANTIC_CONTENT,ure=Je.OQL_SEARCH,jE=Je.ALL_TOOLS});import{ContentSanitizer as LG}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as _G}from"@octocodeai/config";function Rf(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:xt(t.structuredContent)}}catch{}return IG(t)?MG(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=LG.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function IG(e){return _G()==="mcp"&&process.env[FG]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function MG(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:DG(e.structuredContent)},...t]}}function DG(e){let t=["structuredContent available"];if(bf(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=NG(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;bf(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function NG(e){let t=0,n=0;for(let r of e)bf(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function bf(e){return typeof e=="object"&&e!==null}function Sf(e,t){let n=HG(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
48
- message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:GG,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Rf(r)}catch{return r}}function HG(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:QG(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function QG(e){try{return JSON.stringify(e)}catch{return}}var FG,GG,zE=f(()=>{"use strict";Dr();FG="OCTOCODE_MCP_FULL_TEXT";GG="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as jG,withBasicSecurityValidation as BG}from"@octocodeai/octocode-engine/security";function UE(e,t){let n=jG(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function $E(e,t){let n=BG(r=>e(r),t);return(r,o)=>n(r,o)}var qE=f(()=>{"use strict"});import{getConfigSync as zG}from"@octocodeai/config";function $G(e){let t=e;return n=>t(n)}function qG(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:$G(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function VG(e){return WG.find(t=>t.name===e)}async function Bc(e,t){let n=VG(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=KG(n,t);return await YG(n),XG(n),await JG(n,r)}catch(r){return Sf(n.name,r)}}function KG(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function YG(e){e.requiresServerRuntime&&(wl||(wl=UG().catch(t=>{throw wl=null,t})),await wl),e.requiresProviders&&(Tl||(Tl=yb().then(()=>{}).catch(t=>{throw Tl=null,t})),await Tl)}function XG(e){if(!e.isLocal&&!e.isClone)return;let t=zG();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function JG(e,t){try{let n=e.security==="remote"?await ZG(e,t):await eH(e,t);return Rf(n)}catch(n){return Sf(e.name,n)}}async function ZG(e,t){return UE(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function eH(e,t){return $E(e.execute,e.name)(t)}var wl,Tl,UG,WG,WE=f(()=>{"use strict";Yo();xd();BE();zE();qE();Kl();wl=null,Tl=null,UG=vg;WG=jE.map(qG)});var Om=f(()=>{"use strict";Kl();WE()});Om();ju();import{completeMetadata as tH}from"@octocodeai/octocode-core";var Pf=null;function nH(){return Pf||(Pf=ra(tH)),Pf}async function rH(){return nH()}Dr();export{Ul as DIRECT_TOOL_CATEGORIES,xh as DIRECT_TOOL_DEFINITIONS,st as DirectToolInputError,xO as buildDirectToolExampleQuery,Bc as executeDirectTool,pn as findDirectToolDefinition,HL as formatCallToolResultForOutput,hO as formatDirectToolMetadataSchemaText,bO as formatDirectToolOutputSchemaText,fO as formatDirectToolSchemaText,gO as getDirectToolAutoFilledFields,Sr as getDirectToolCategory,RO as getDirectToolDescription,No as getDirectToolDisplayFields,yO as getDirectToolOutputFields,rH as loadToolContent,_h as prepareDirectToolInput,vO as prepareDirectToolInputFromJsonText,mO as sortDirectToolNames};
47
+ `)}}var CT,wT=f(()=>{"use strict";Xt();te();ul();_a();pr();Ln();CT=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/});import Ge from"node:path";function CN(e,t,n){let r=t??n??".";if(!e)return r;if(Ge.isAbsolute(e))return e;if(n&&Ge.isAbsolute(n))return Ge.resolve(n,e);if(t&&Ge.isAbsolute(t)){let o=Ss(t)?t:Ge.dirname(t);return Ge.resolve(o,e)}return e}function TT(){return C("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function xN(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(C("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(C("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push(TT()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push(TT());let i=e?.pagination;return i?.hasMore&&n.push(C("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:Jm(i,t)})),n}async function ET(e){let t,n,r=[],o=[],i=bt(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let E=e.from.path,_=Ss(E);n=c??(_?Ge.resolve(E):void 0),t=a??(_?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=Ne(e.scope),_=E?Ge.isAbsolute(E)?E:Ge.join(e.from.localPath,E):void 0;s?(n=c??e.from.localPath,t=a??_):t=a??_??e.from.localPath}else if(e.from?.kind==="github"){let{owner:E,repo:_}=An(e.from);if(!E||!_)return o.push(C("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,G=Ne(e.scope),M=w&&!Ge.isAbsolute(w)?w:G,A=await we("ghCloneRepo",{owner:E,repo:_,...e.from.ref?{branch:e.from.ref}:{},...M?{sparsePath:M}:{}}),q=kn(A).data,H=uT(A,q?.localPath);if(!H)return o.push(C("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:H}),s?(n=c??H,w?t=Ge.isAbsolute(w)?w:Ge.join(H,w):G&&(t=Ge.isAbsolute(G)?G:Ge.join(H,G))):w?t=Ge.isAbsolute(w)?w:Ge.join(H,w):G?t=Ge.isAbsolute(G)?G:Ge.join(H,G):t=H}if(!t&&!n)return o.push(C("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...m}=i,p=await we("lspGetSemantics",{...m,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:h,status:g}=kn(p),y=h,b=fT(y,e),S=CN(rs(y?.uri),t,n),x=EN(e,S),k=TN(wN(y),u);return{results:g==="error"?[]:vn(k,"semantics",x),...b?{pagination:b}:{},diagnostics:[...o,...Xm(p,"lspGetSemantics"),...xN(y,e)],provenance:[...r,{backend:"lspGetSemantics",source:x}]}}function wN(e){if(!e)return[];let n=(Ym(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=rs(e.uri);return n.map(o=>Ym(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return sl(e)}function TN(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function EN(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}var kT=f(()=>{"use strict";Xt();te();En();Rs();pr();Ln()});import{builtinModules as kN}from"node:module";var tf,OT,vT,AT,Cs=f(()=>{"use strict";tf=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],OT="package.json",vT=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),AT=new Set(kN.flatMap(e=>[e,`node:${e}`]))});import pl from"node:path";function ml(){if(xs)return xs;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());xs=new Set(e.length>0?e:tf)}catch{xs=new Set(tf)}return xs}function LT(){if(ws)return ws;try{let e=JSON.parse(D.getGraphFactCapabilities());ws=Array.isArray(e)?e.filter(ON):[]}catch{ws=[]}return ws}function ON(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function nf(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function fl(e,t,n){return hl(pl.resolve(e,t),n)}function hl(e,t){let n=ml(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(pl.join(e,`index${o}`));return r.find(o=>t.has(o))}function Ts(e){return e.startsWith("./")||e.startsWith("../")}function _T(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function FT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function rf(e){return typeof e=="string"&&e.trim()?e:void 0}function gl(e){return typeof e=="string"&&e.length>0}function IT(e){return typeof e=="string"}function MT(e){return[...new Set(e)]}function Ht(e,t){return pl.relative(e,t)||pl.basename(t)}function DT(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function NT(e,t){return!!(e===t||e.endsWith(`.${t}`)||e.endsWith(`::${t}`))}var xs,ws,Es=f(()=>{"use strict";Ee();Cs()});import en from"node:path";import{readFile as vN,readdir as AN}from"node:fs/promises";async function GT(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await AN(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(vT.has(s.name))continue;await r(en.join(o,s.name));continue}s.isFile()&&n.push(en.join(o,s.name))}}return await r(e),n}async function HT(e){return(await Promise.all(e.map(async n=>LN(n)))).filter(n=>n!==null)}async function LN(e){let t=await _N(e);if(!t)return null;let n=en.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=FT(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:rf(t.name),deps:r,entrypoints:FN(n,t)}}async function _N(e){try{let t=JSON.parse(await vN(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function FN(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=rf(t[o]);i&&n.add(en.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(en.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(en.resolve(e,o));QT(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(en.resolve(e,o));return[...n]}function QT(e,t,n){if(typeof t=="string"){n.add(en.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))QT(e,r,n)}function jT(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=IN(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:Ht(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:Ht(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:Ht(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function IN(e,t){return t.filter(r=>e.startsWith(`${r.dir}${en.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}var BT=f(()=>{"use strict";Cs();Es()});import co from"node:path";import{readFile as MN}from"node:fs/promises";async function zT(e,t){let n=ml(),r=t.filter(i=>n.has(co.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await MN(i,"utf8").catch(()=>""),a=co.extname(i).toLowerCase(),c=DN(s,i,Ht(e,i)),l=MT(c?c.imports.map(u=>u.specifier):NN(s));return{path:i,rel:Ht(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!Ts(u)).map(_T).filter(gl).filter(u=>!AT.has(u)),...c?{graphFacts:c}:{}}}))}function DN(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??co.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(IT):[]}}catch{return}}function of(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...ml()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=nf(e,l=>l.language),s=nf(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function NN(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function UT(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,co.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??co.dirname(o.path);for(let a of o.imports){if(!Ts(a))continue;let c=fl(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function $T(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=hl(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","lib.rs","main.rs","mod.rs"]){let s=hl(co.resolve(e,i),r);s&&o.add(s)}return[...o]}function qT(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}var WT=f(()=>{"use strict";Ee();Cs();Es()});import GN from"node:path";import{readFile as VT}from"node:fs/promises";async function KT(e){return(await Promise.all(e.map(async n=>{let r=HN(n);if(r.length>0)return r;let o=await VT(n.path,"utf8").catch(()=>"");return QN(n.rel,o)}))).flat()}function HN(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function QN(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:DT(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function YT(e,t,n){let r=new Map(t.map(a=>[a.rel,a])),o=new Map(t.map(a=>[a.path,a])),i=new Set(t.map(a=>a.path)),s=jN(t);return e.map(a=>{let c=r.get(a.file),l=BN(a,t,c,s,i,o),u=l.length>0?"ast":"ripgrep",d=l.length>0?l:t.filter(g=>g.rel!==a.file&&zN(g.path,a.symbol)).map(g=>g.rel),m=d.filter(g=>{let y=r.get(g);return y?n.has(y.path):!1}),p=c?n.has(c.path):!1,h=m.length>0?"reachable":d.length>0?"transitive-dead":p?"candidate-unused-export":"unused-export";return{symbol:a.symbol,kind:a.kind,file:a.file,line:a.line,evidenceSource:a.evidenceSource,retentionSource:u,directRefs:d.length,externalRefs:m.length,retainedBy:d,verdict:h}})}function jN(e){let t=new Map;for(let n of e){let r=n.graphFacts;if(r){for(let o of r.declarations){if(!o.exported)continue;let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}for(let o of r.exports){let i=t.get(o.name)??new Set;i.add(n.path),t.set(o.name,i)}}}return t}function BN(e,t,n,r,o,i){let s=r.get(e.symbol)??(n?new Set([n.path]):new Set),a=new Set;for(let c of t){if(c.rel===e.file)continue;let l=c.graphFacts;if(l){for(let u of l.imports){let d=u.importedName&&u.importedName!=="default"?u.importedName:void 0,m=u.localName;if(!(d===e.symbol||m===e.symbol)||!Ts(u.specifier))continue;let h=fl(GN.dirname(c.path),u.specifier,o);if(h&&s.has(h)){a.add(c.rel);break}}if(!a.has(c.rel)){for(let u of l.calls)if(NT(u.callee,e.symbol)){a.add(c.rel);break}}}}return[...a].sort()}function zN(e,t){return sf.get(e)?.has(t)??!1}async function XT(e){sf.clear(),await Promise.all(e.map(async t=>{let n=await VT(t.path,"utf8").catch(()=>"");sf.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}var sf,JT=f(()=>{"use strict";Es();sf=new Map});import UN from"node:path";async function yl(e){let t=UN.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=$N(r,e.intent,e.facets),i=qN(o,e.facets),s=WN(o,i),a=LT();if(n==="plan")return VN({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:of([],[],a)});let c=await GT(t,e.maxFiles??5e3),l=await HT(c.filter(w=>w.endsWith(OT))),u=await zT(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),m=of(u,d,a);await XT(u);let p=new Set(l.map(w=>w.name).filter(gl)),h=UT(u),g=$T(t,l,u),y=qT(g,h),b=u.filter(w=>!y.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=jT(t,l,u,p),x=await KT(u),k=YT(x,u,y),E=k.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,_=k.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:y.size,unusedFiles:b.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:k.length,candidateUnusedExports:E,transitiveDeadExports:_,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,G)=>w+G.declarations.length,0),nativeGraphCalls:d.reduce((w,G)=>w+G.calls.length,0)},manifests:l.map(w=>({manifest:Ht(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(G=>Ht(t,G)),dependencyCount:[...w.deps.keys()].length})),files:b,dependencies:S,symbols:k,graphFacts:d,graphCapabilities:m,caveats:["Analyze uses native AST graph facts for inventory and preferred cross-file retention (named imports / call callees). Lexical token scan is fallback only when AST finds no retainers.",'Graph facts are syntax inventory, not semantic identity. Upgrade candidates with target:graph proof:"lsp" (or lspGetSemantics references/callers) before destructive cleanup.',"Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function $N(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function qN(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function WN(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["extractGraphFacts","export regex fallback"],produces:["symbols","lineHints"],evidence:"heuristic"},{id:"reference-scan",purpose:"Candidate cross-file retention from native AST imports/calls (preferred) with lexical token fallback. Upgrade via target:graph proof:lsp \u2014 analyze does not run LSP.",tools:["extractGraphFacts","token scan fallback"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"heuristic"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function VN(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}var af=f(()=>{"use strict";BT();WT();JT();Cs();Es()});async function ZT(e){let t=bt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[C("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=ll(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[C("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await yl({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[C("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:fs(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?ur(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?pT(e,i):{fields:{}},m={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:ys(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},p=mT(l?.pagination,d.pagination);return{results:vn([m],"research",e.from),...p?{pagination:p}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}var eE=f(()=>{"use strict";te();af();rl();bs();pr();Rs();Ln()});import bl from"node:path";function lf(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function nE(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function rE(e,t,n,r,o){let i=n.filter(l=>hs(l,r)),s=ur(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await YN(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(C(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(C("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),KN(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(C("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function KN(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function YN(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=bl.isAbsolute(t.subject.uri)?t.subject.uri:bl.resolve(e,t.subject.uri);try{let i=await we("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=XN(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=kn(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:rs(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,m=eo(a?.totalReferences)??eo(u?.totalReferences)??eo(a?.referenceCount)??eo(u?.referenceCount)??eo(d?.totalItems)??tE(u)??tE(a);return{status:"ok",...typeof m=="number"?{totalReferences:m}:{},files:JN(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function XN(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function tE(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function JN(e,t){let n=new Set;return cf(e,n,t),[...n].slice(0,25)}function cf(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)cf(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&ZN(i)&&t.add(bl.isAbsolute(i)?bl.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])cf(r[o],t,n)}function ZN(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var oE=f(()=>{"use strict";Xt();te();bs()});async function iE(e){let t=bt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[C("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(h=>typeof h=="string"):void 0,o=ll(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[C("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await yl({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(h){return{results:[],diagnostics:[C("invalidQuery",h instanceof Error?h.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:fs(i),a=Vm(t),c=s?.packets??[],l=lf(i.mode,t)?await rE(n,e,c,a,nE(e,t)):[],u=sT(c),d=iT(e,c,u,a,i.graphFacts,n),m=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[lf(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],p={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:ys(i.graphFacts),caveats:m};return{results:vn([p],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var sE=f(()=>{"use strict";te();af();rl();bs();oE();pr();Rs();Ln()});var aE,cE=f(()=>{"use strict";yT();ST();wT();kT();eE();sE();aE={repositories:hT,packages:gT,pullRequests:Zm,commits:Zm,diff:xT,semantics:ET,research:ZT,graph:iE}});function lE(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&eG.has(e.target)&&t.push(C("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "none" or "standard".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "none" or "standard".'}})),t}var eG,uE=f(()=>{"use strict";te();eG=new Set(["pullRequests","commits","diff"])});function dE(e){let t={schema:Rt.schema,view:e.view??Rt.view,page:e.page??Rt.page,itemsPerPage:e.itemsPerPage??Rt.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??Rt.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??Rt.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??Rt.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?Rt.detailedCodeContext:Rt.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??Rt.localSearchSort),t}var Rt,pE=f(()=>{"use strict";Rt={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"standard",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function tG(e){return e?.mode==="auto"||e?.mode==="required"}function nG(e,t){let n=e.target==="files"?mr:_n;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:_n,exact:!0,reason:`${t.kind} evaluated locally by ${_n}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function rG(e,t,n){let r=tG(e.materialize);if(n)return oG(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:mr,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:mr,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:tn,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:mr,exact:!0,reason:`${Rl(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:mr,exact:!1,reason:`GitHub cannot enumerate files by ${Rl(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Rl(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:_n,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:_n,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:tn,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?uf(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:_n,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return uf(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:mr,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:tn,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:tn,exact:!0,reason:"path/name predicate pushed to provider"}:uf(e,`field "${t.field}"`,r)}}function Rl(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function oG(e,t,n){let r=Rl(t);return n?{route:"ROUTE",backend:e.target==="files"?mr:_n,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:tn,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function uf(e,t,n){if(n)return{route:"ROUTE",backend:_n,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:tn,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function mE(e,t,n=!1){return e.sourceKind==="github"?rG(e,t,n):nG(e,t)}var _n,mr,tn,fE=f(()=>{"use strict";_n="localSearchCode",mr="localFindFiles",tn="ghSearchCode"});function lo(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return df.find(n=>n.id===`${t}.diff.${e.variant}`)}return df.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function pf(e){return df.find(t=>t.id===e)}function mf(e){let t=iG(e.source,e.target);if(e.target==="diff"){let n=ao(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return lo({sourceKind:t,target:"diff",variant:r})}return lo({sourceKind:t,target:e.target})}function hE(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function gE(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function iG(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var df,yE=f(()=>{"use strict";ul();df=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function sG(e,t){return e.id??t}function Sl(e,t,n,r,o,i=!1){let s=sG(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,m)=>Sl(e,d,`${n}.of[${m}]`,r,o,i)),l=aG(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(C("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=Sl(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=mE(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(C(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&bE(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:cG(e.target),exact:a.exact}),a.route}function aG(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function cG(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function bE(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Pl(e,t){if(!t)return;let n=gE(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function ks(e,t,n){if(!t)return!1;for(let r of hE(t,n))bE(e.backendCalls,r);return!0}function RE(e,t){return ff(e,t,"files")}function ff(e,t,n,r=lo({sourceKind:"materialized",target:n})){let o=lo({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Pl(e,o),Pl(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),ks(e,o,t),ks(e,r,void 0),!0}function Cl(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Cl):e.kind==="not"?Cl(e.predicate):!1:!1}function SE(e){return e.target==="code"?pf(Cl(e.where)?"local.code.structural":"local.code.textRegex"):lo({sourceKind:"materialized",target:e.target})}function PE(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?pf(Cl(e.where)?"local.code.structural":"local.code.textRegex")??mf({source:t,target:e.target,params:e.params}):mf({source:t,target:e.target,params:e.params})}var CE=f(()=>{"use strict";fE();te();yE()});function xE(e){return e.kind==="not"&&e.predicate.kind==="not"?xE(e.predicate.predicate):e}function wE(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Dl[e.target]:void 0;if(n)return n.includes(t)?[]:[C("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[C("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function TE(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=xE(e.where),r=ss({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function EE(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(C("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(C("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var kE=f(()=>{"use strict";te();_m();un()});function OE(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=PE(e,o);if(Pl(n,s),e.where)Sl(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(h=>h.route==="ROUTE")&&ff(n,o,e.target,SE(e));else if(e.target==="diff"){let h=ao(e.params);h.kind==="prPatch"||h.kind==="directFile"?ks(n,s,o)||n.diagnostics.push(C("unsupportedTarget",`No transformer registered for target:"diff" lane "${h.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(C("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let h=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(h?g&&RE(n,o):ks(n,s,o))&&(!h||g)&&n.diagnostics.push(C("unsupportedTarget",h?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(C("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...TE(e,n.nodes)),n.diagnostics.push(...wE(e)),n.diagnostics.push(...lE(e));let a=EE(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??Rt.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(C("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=Xr(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(C("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let m={input:t,normalized:e,defaults:dE(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},p=!n.nodes.some(h=>h.route==="UNSUPPORTED")&&!n.diagnostics.some(h=>h.severity==="error"&&h.code!=="planTruncated");return{plan:m,executable:p}}var vE=f(()=>{"use strict";ul();uE();te();pE();Rm();CE();kE()});function lG(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function AE(e,t,n,r,o,i){let s=o&&i?uG(i):[],a=o&&i?dG(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:Qc(e.plan.diagnostics,t,n,r,lG(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function uG(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[C("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function dG(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}var LE=f(()=>{"use strict";te();Zi()});function _E(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):mG.has(c)?o.add(c):fG.has(c)?o.add("data"):hG.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!pG.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[C("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}var pG,mG,fG,hG,FE=f(()=>{"use strict";te();pG=new Set(["kind","source","recordType","id","proofGrade"]),mG=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","matchKind","scoreHint","proofGrade","size","modified","entryType","depth","children","data"]),fG=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),hG=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});function Os(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function xl(e,t,n,r){let o=OE(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return AE(o,s,e.id,r,n.dryRun,e);let a=await bG(e,o);Mx(e,a.results),gG(e,a),yG(a);let c=Vx(e,a);Nx(e,a.results);let l=_E(e,a.results),u=Kx(a.results);return Ji({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:_x(o.plan.backendCalls),plan:s})}function gG(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function yG(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}async function bG(e,t){if(e.target==="materialize")return Yw(e);let n=aE[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?ms(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?Kw(e):yw(e)}var hf=f(()=>{"use strict";bw();qm();Xw();cE();Zi();vE();km();LE();wm();Tm();FE()});async function IE(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await xl(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=RG(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&Os(o.merged.results)}else for(let i of r)Os(i.envelope.results);return o}function RG(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let m=xG(d);n.has(m)||(n.add(m),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),SG(s,u.envelope.nextHints),PG(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),CG(u.envelope)&&(l=!0)}return l&&o.push(C("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Ji({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function SG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||Em(o,r))&&(e[n]=r)}}function PG(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function CG(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function xG(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var ME=f(()=>{"use strict";te();Zi();km();hf()});var DE={};XE(DE,{runOqlSearch:()=>wG});async function wG(e,t={}){let n;try{n=vx(e)}catch(o){if(o instanceof Yt)return Qc(o.diagnostics);throw o}if(Gl(n))return IE(n,e,t);let r=await xl(n,e,t);return Os(r.results),r}var NE=f(()=>{"use strict";Ax();te();Zi();un();ME();hf()});async function HE(e){let t=TG(e),n=Hn.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(NE(),DE)),o=await r(n.data,{authInfo:e.authInfo});return EG(o)}function TG(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function EG(e){let t=kG(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function kG(e){return Hl(e)?{results:e.children.map(t=>GE(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:QE(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[GE(e,e.queryId??"oqlSearch-1")]}}function GE(e,t){let n=QE(e);return{id:e.queryId??t,...vG(e),data:n}}function QE(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||OG(d,u)){let{why:m,confidence:p,...h}=l;s[c]=h,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function OG(e,t){return e.why===t.why&&e.confidence===t.confidence}function vG(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var jE=f(()=>{"use strict";Sr();un()});var gf,BE=f(()=>{"use strict";pe();gf={hasTool(e){return zu(e)},getDescription(e){return Bu[e]??""},getToolName(e){return v[e]??String(e)}}});function AG(e,t){return t.getToolName(e)}function Et(e,t,n){let r=AG(t,e);return{...n,name:r,description:yf(r,e)}}function LG(e=gf){let t=Et(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:bo,inputSchema:Ro,executionFn:WR,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=Et(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Fn,inputSchema:yo,executionFn:DR,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=Et(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:wo,inputSchema:To,executionFn:US,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=Et(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Po,inputSchema:Co,executionFn:BS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=Et(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:In,inputSchema:So,executionFn:kS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=Et(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Eo,inputSchema:ko,executionFn:pP,security:"remote",requiresServerRuntime:!0}}),a=Et(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:br,inputSchema:ho,executionFn:Zb,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=Et(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:jt,inputSchema:Ao,executionFn:sC,security:"basic"}}),l=Et(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Nn,inputSchema:Lo,executionFn:yC,security:"basic"}}),u=Et(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Dn,inputSchema:vo,executionFn:HP,security:"basic"}}),d=Et(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Mn,inputSchema:Oo,executionFn:IP,security:"basic"}}),m={name:Ie,description:yf(Ie,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:_o,inputSchema:Fo,executionFn:ux,security:"basic",requiresServerRuntime:!0}},p={name:rn,description:yf(rn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:Mo,inputSchema:Hn,executionFn:HE,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},h=[t,n,r,o,i,s,a,c,l,u,d,m,...mo()?[p]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,OQL_SEARCH:p,ALL_TOOLS:h}}var yf,Je,Zne,ere,tre,nre,rre,ore,ire,sre,are,cre,lre,ure,dre,zE,UE=f(()=>{"use strict";zl();eR();NR();VR();OS();zS();$S();mP();MP();QP();aC();bC();dx();jE();kt();fo();BE();yf=(e,t=gf)=>t.getDescription(e);Je=LG(),Zne=Je.GITHUB_SEARCH_CODE,ere=Je.GITHUB_FETCH_CONTENT,tre=Je.GITHUB_VIEW_REPO_STRUCTURE,nre=Je.GITHUB_SEARCH_REPOSITORIES,rre=Je.GITHUB_SEARCH_PULL_REQUESTS,ore=Je.PACKAGE_SEARCH,ire=Je.GITHUB_CLONE_REPO,sre=Je.LOCAL_RIPGREP,are=Je.LOCAL_VIEW_STRUCTURE,cre=Je.LOCAL_FIND_FILES,lre=Je.LOCAL_FETCH_CONTENT,ure=Je.LSP_GET_SEMANTIC_CONTENT,dre=Je.OQL_SEARCH,zE=Je.ALL_TOOLS});import{ContentSanitizer as _G}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as FG}from"@octocodeai/config";function Rf(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:xt(t.structuredContent)}}catch{}return MG(t)?DG(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=_G.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function MG(e){return FG()==="mcp"&&process.env[IG]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function DG(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:NG(e.structuredContent)},...t]}}function NG(e){let t=["structuredContent available"];if(bf(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=GG(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;bf(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function GG(e){let t=0,n=0;for(let r of e)bf(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function bf(e){return typeof e=="object"&&e!==null}function Sf(e,t){let n=QG(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
48
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:HG,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Rf(r)}catch{return r}}function QG(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:jG(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function jG(e){try{return JSON.stringify(e)}catch{return}}var IG,HG,$E=f(()=>{"use strict";Nr();IG="OCTOCODE_MCP_FULL_TEXT";HG="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as BG,withBasicSecurityValidation as zG}from"@octocodeai/octocode-engine/security";function qE(e,t){let n=BG(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function WE(e,t){let n=zG(r=>e(r),t);return(r,o)=>n(r,o)}var VE=f(()=>{"use strict"});import{getConfigSync as UG}from"@octocodeai/config";function qG(e){let t=e;return n=>t(n)}function WG(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:qG(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function KG(e){return VG.find(t=>t.name===e)}async function Bc(e,t){let n=KG(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=YG(n,t);return await XG(n),JG(n),await ZG(n,r)}catch(r){return Sf(n.name,r)}}function YG(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function XG(e){e.requiresServerRuntime&&(wl||(wl=$G().catch(t=>{throw wl=null,t})),await wl),e.requiresProviders&&(Tl||(Tl=yb().then(()=>{}).catch(t=>{throw Tl=null,t})),await Tl)}function JG(e){if(!e.isLocal&&!e.isClone)return;let t=UG();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function ZG(e,t){try{let n=e.security==="remote"?await eH(e,t):await tH(e,t);return Rf(n)}catch(n){return Sf(e.name,n)}}async function eH(e,t){return qE(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function tH(e,t){return WE(e.execute,e.name)(t)}var wl,Tl,$G,VG,KE=f(()=>{"use strict";Xo();xd();UE();$E();VE();Kl();wl=null,Tl=null,$G=vg;VG=zE.map(WG)});var Om=f(()=>{"use strict";Kl();KE()});Om();ju();import{completeMetadata as nH}from"@octocodeai/octocode-core";var Pf=null;function rH(){return Pf||(Pf=ra(nH)),Pf}async function oH(){return rH()}Nr();export{Ul as DIRECT_TOOL_CATEGORIES,xh as DIRECT_TOOL_DEFINITIONS,st as DirectToolInputError,TO as buildDirectToolExampleQuery,Bc as executeDirectTool,pn as findDirectToolDefinition,jL as formatCallToolResultForOutput,yO as formatDirectToolMetadataSchemaText,SO as formatDirectToolOutputSchemaText,gO as formatDirectToolSchemaText,bO as getDirectToolAutoFilledFields,Pr as getDirectToolCategory,PO as getDirectToolDescription,Go as getDirectToolDisplayFields,RO as getDirectToolOutputFields,oH as loadToolContent,_h as prepareDirectToolInput,LO as prepareDirectToolInputFromJsonText,hO as sortDirectToolNames};