@octocodeai/octocode-tools-core 18.0.1 → 18.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -98
- package/dist/direct.d.ts +1 -1
- package/dist/direct.js +28 -30
- package/dist/github/compare.d.ts +18 -9
- package/dist/index.js +30 -32
- package/dist/schema.js +1 -1
- package/dist/tools/directToolCatalog/toolCatalogFormatters.d.ts +0 -7
- package/dist/tools/github_clone_repo/scheme.d.ts +38 -20
- package/dist/tools/github_fetch_content/finalizer/types.d.ts +2 -0
- package/dist/tools/github_search_pull_requests/contentResponse/fileSurfaces.d.ts +1 -2
- package/dist/tools/github_search_pull_requests/splitSchemes.d.ts +3 -0
- package/dist/utils/file/configFiles.d.ts +70 -0
- package/package.json +3 -3
package/dist/direct.js
CHANGED
|
@@ -5,32 +5,30 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
import{completeMetadata as Xh}from"@octocodeai/octocode-core";var D=Xh.toolNames,le=D.LSP_GET_SEMANTIC_CONTENT;function Ln(e=process.env){let t=e.ENABLE_RELEASES;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function Vt(e=process.env){let t=e.ENABLE_DISCUSSIONS;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var bE=new Set([D.LOCAL_RIPGREP,D.LOCAL_FETCH_CONTENT,D.LOCAL_FIND_FILES,D.LOCAL_VIEW_STRUCTURE,le]);var Yc=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];function Ze(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0},...e.lineDeviation!==void 0&&{lineDeviation:e.lineDeviation}}}function Fi(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}}}import{CloneRepoQuerySchema as tg}from"@octocodeai/octocode-core/schemas";import{z as to}from"zod";function I(e,t){return to.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,to.number().int().min(e).max(t))}var X=I(1,1e3).optional().default(1),Kt=I(0,100).optional(),Yt=I(1,1e9).optional(),Jh={responseCharOffset:I(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:I(1,5e4).optional().describe("Full-response char window.")};function V(e,t={}){let{maxQueries:n=5}=t;return to.object({queries:to.array(e).min(1).max(n).describe("Parallel queries."),...Jh}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}import{z as Xc}from"zod";function Zh(e,t){return e?.description&&!t.description?t.describe(e.description):t}function qc(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=Zh(e.shape[r],o);return n}function eg(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Jc(e,t){if(!t?.length)return e;let n=new Set(t);return Xc.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function K(e,t={},n={}){let r=Jc(e,n.omit),o=eg(r,qc(r,t));return n.strict?o.strict():o}function q(e,t={},n={}){let r=Jc(e,n.omit),o=Xc.object({...r.shape,...qc(r,t)});return n.strict?o.strict():o}var Xt=K(tg),An=V(Xt);import{z as ng}from"zod";import{FileContentQuerySchema as Zc}from"@octocodeai/octocode-core/schemas";var rg=ng.enum(["none","standard","symbols"]).optional(),eu={startLine:Yt,endLine:Yt,contextLines:Kt,charOffset:I(0,1e8).optional(),charLength:I(1,5e4).optional(),minify:rg},og=q(Zc,eu),Lt=K(Zc,eu),kn=V(og);import{z as ig}from"zod";import{GitHubCodeSearchQuerySchema as tu}from"@octocodeai/octocode-core/schemas";var nu={limit:I(1,100).optional(),page:X.default(1),match:ig.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghSearchPullRequests, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},In=K(tu,nu),On=V(q(tu,nu));import{z as Di}from"zod";import{GitHubPullRequestSearchQuerySchema as ru}from"@octocodeai/octocode-core/schemas";var ou={type:Di.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),prNumber:I(1,1e9).optional(),issueNumber:I(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:I(1,100).optional().default(30),match:Di.array(Di.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:X.default(1),filePage:X.optional(),commentPage:X.optional(),commitPage:X.optional(),itemsPerPage:I(1,100).optional().default(20),charOffset:I(0,1e8).optional(),commentBodyOffset:I(0,1e8).optional(),charLength:I(1,5e4).optional()},sg=q(ru,ou),Mi=K(ru,ou),ag=V(sg);import{SearchPullRequestsQuerySchema as iu,SearchIssuesQuerySchema as su,SearchCommitsQuerySchema as au,ListReleasesQuerySchema as cu}from"@octocodeai/octocode-core/schemas";var uu={limit:I(1,100).optional().default(30),page:X.default(1),itemsPerPage:I(1,100).optional().default(20)},lu={...uu,filePage:X.optional(),commentPage:X.optional(),commitPage:X.optional(),charOffset:I(0,1e8).optional(),commentBodyOffset:I(0,1e8).optional(),charLength:I(1,1e5).optional()},Fn=K(iu,lu),vn=V(q(iu,lu)),du={...uu,commentPage:X.optional(),charOffset:I(0,1e8).optional(),commentBodyOffset:I(0,1e8).optional(),charLength:I(1,1e5).optional()},Dn=K(su,du),Mn=V(q(su,du)),pu={page:X.default(1),limit:I(1,100).optional().describe("Commits per page \u2014 alias of itemsPerPage (preferred when both are set).")},Nn=K(au,pu),Gn=V(q(au,pu)),mu={page:X.default(1),limit:I(1,100).optional().describe("Releases per page \u2014 alias of itemsPerPage (preferred when both are set).")},qt=K(cu,mu),Jt=V(q(cu,mu));import{SearchDiscussionsQuerySchema as fu}from"@octocodeai/octocode-core/schemas";var hu={itemsPerPage:I(1,100).optional().default(20),limit:I(1,100).optional()},Zt=K(fu,hu),en=V(q(fu,hu));import{z as gu}from"zod";import{GitHubReposSearchSingleQuerySchema as yu}from"@octocodeai/octocode-core/schemas";var Ru={limit:I(1,100).optional(),page:X.default(1),match:gu.array(gu.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.)")},Hn=K(yu,Ru),Bn=V(q(yu,Ru));import{GitHubViewRepoStructureQuerySchema as Su}from"@octocodeai/octocode-core/schemas";var bu={maxDepth:I(0,20).optional(),page:X.default(1),itemsPerPage:I(1,200).optional()},Un=K(Su,bu),Qn=V(q(Su,bu));import{z as no}from"zod";import{NpmPackageQuerySchema as Cu}from"@octocodeai/octocode-core/schemas";var Pu={page:X,keywords:no.union([no.string(),no.array(no.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},$n=K(Cu,Pu),jn=V(q(Cu,Pu,{strict:!0}),{maxQueries:5});import{z as ug}from"zod";import{FetchContentQuerySchema as xu}from"@octocodeai/octocode-core/schemas";var lg=ug.enum(["none","standard","symbols"]).optional(),wu={startLine:Yt,endLine:Yt,contextLines:Kt.default(5),charOffset:I(0,1e8).optional(),charLength:I(1,5e4).optional(),minify:lg},dg=q(xu,wu),_t=K(xu,wu),zn=V(dg,{maxQueries:5});import{z as Ni}from"zod";import{FindFilesQuerySchema as pg}from"@octocodeai/octocode-core/schemas";var Tu={maxDepth:I(0,100).optional(),minDepth:I(0,100).optional(),limit:I(1,1e4).optional().describe("Discovery cap applied after sort, before pagination \u2014 total results are capped here; itemsPerPage/page page within that cap."),page:X.default(1),itemsPerPage:I(1,50).optional(),excludeDir:Ni.array(Ni.string()).optional().describe("Directory names to prune from the walk. Common generated/vendor dirs are pruned by default (node_modules, .git, dist, build, out, coverage, target, .next, .cache); pass [] to prune nothing, or pass an explicit list to choose pruned dirs.")},Eu=Ni.object(Object.fromEntries(Object.entries(pg.shape).filter(([e])=>e!=="regexType")));function mg(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 fg=q(Eu,Tu),kt=K(Eu,Tu).superRefine(mg),Vn=V(fg,{maxQueries:5});import{FindDeadCodeQuerySchema as Lu}from"@octocodeai/octocode-core/schemas";var Au={maxFiles:I(1,5e4).optional(),limit:I(1,5e3).optional(),page:X.default(1),itemsPerPage:I(1,50).optional()},hg=q(Lu,Au),It=K(Lu,Au),Kn=V(hg,{maxQueries:5});import{z as pt}from"zod";import{RipgrepQuerySchema as _u}from"@octocodeai/octocode-core/schemas";var gg=["paginated","discovery","detailed","structural"],yg=["semanticRanking"],ku={mode:pt.enum(gg).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghSearchPullRequests\'s `content.patches.mode` \u2014 different concepts sharing this name.)'),searchText:pt.string().optional().describe('The search pattern. regex:"fixed" for a literal match, "perl" for advanced features (lookaheads, backreferences), else "smart". (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)'),output:pt.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content").describe('"content" (default) matches with line text; "files"/"filesWithout" return matching/non-matching paths; "countLines"/"countMatches" return per-file counts; "matchOnly" returns just the matched substring (required for unique/matchWindow). ("files" is unlike localViewStructure\'s `filesOnly`, which filters a directory listing to file entries.)'),pattern:pt.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Modifiers are part of the node \u2014 `function $NAME` does not match `async function` or `export function`; include the modifiers or use a YAML `kind` rule for modifier-agnostic matches. Use this to find syntax shape, then use lspGetSemantics for semantic proof."),maxDepth:I(0,20).optional().describe("Keep files at most this many directory levels below the search root (0 = files directly in the root). Structural mode pushes this into the native walker; text/regex mode applies it after the native search and emits a warning when it filters deeper matches."),rule:pt.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),captureText:pt.boolean().optional().describe("Structural only: return full verbatim capture text for `$$$` list metavars (bodies, arg lists). Default false \u2014 list-capture text is omitted from `metavars`, and `metavarRanges` entries are comment-pruned and truncated to keep results lean; ranges always remain as line anchors."),contextLines:Kt,matchContentLength:I(1,1e5).optional().default(500),maxMatchesPerFile:I(1,1e5).optional(),maxFiles:I(1,1e5).optional(),matchPage:X.optional(),itemsPerPage:I(1,1e3).optional(),page:X.default(1),unique:pt.enum(["off","list","count"]).optional().default("off").describe('Needs output:"matchOnly". "list" returns each matched value once per file; "count" adds its frequency.')},Rg={...ku,semanticRanking:pt.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},Sg=q(_u,Rg),bg=K(_u,ku,{strict:!0,omit:yg}),tt=bg.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let n=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(n){let r=n[0].slice(2);t.addIssue({code:"custom",message:`\`${n[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),Yn=V(Sg,{maxQueries:5});import{z as Iu}from"zod";import{ViewStructureQuerySchema as Ou}from"@octocodeai/octocode-core/schemas";var Fu={excludeDir:Iu.array(Iu.string()).optional().describe("Directory names to prune from recursive walks (default: common generated/vendor dirs such as node_modules, dist, build, out, coverage, target). Pass [] to inspect everything."),maxDepth:I(0,20).optional(),limit:I(1,1e4).optional(),page:X.default(1),itemsPerPage:I(1,50).optional()},Cg=q(Ou,Fu),Ot=K(Ou,Fu),Xn=V(Cg,{maxQueries:5});import{z as ro}from"zod";import{LspGetSemanticsQuerySchema as vu}from"@octocodeai/octocode-core/schemas";var Pg=I(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),xg=I(0,1e5).optional(),wg=["structured","compact"],Du={type:ro.enum(Yc).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:ro.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:Pg.optional(),orderHint:xg,depth:I(0,20).optional().describe("Traversal depth for call-hierarchy / type-hierarchy queries (0 = direct only)."),includeDeclaration:ro.boolean().optional().default(!0),page:X.describe("Result page for paginated reference/symbol lists (advance while pagination.hasMore)."),itemsPerPage:I(1,100).optional().describe("References/symbols returned per page (with page)."),contextLines:I(0,100).optional().describe("Lines of surrounding source shown around each result location."),format:ro.enum(wg).optional().default("structured")},Tg=q(vu,Du),qn=K(vu,Du);var Jn=V(Tg,{maxQueries:5});var Hi=["GitHub","Local Code","Package","Other"],Mu=new Map([D.GITHUB_SEARCH_CODE,D.GITHUB_SEARCH_REPOSITORIES,D.GITHUB_PULL_REQUESTS,D.GITHUB_ISSUES,D.GITHUB_COMMITS,D.GITHUB_FETCH_CONTENT,D.GITHUB_VIEW_REPO_STRUCTURE,D.GITHUB_CLONE_REPO,D.LOCAL_RIPGREP,D.LOCAL_FIND_FILES,D.LOCAL_FIND_DEAD_CODE,D.LOCAL_FETCH_CONTENT,D.LOCAL_VIEW_STRUCTURE,le,D.PACKAGE_SEARCH,...Vt()?[D.GITHUB_DISCUSSIONS]:[]].map((e,t)=>[e,t])),Fe=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},Eg=["id","mainResearchGoal","researchGoal","reasoning"],Zn=new Set([...Eg]),Nu=[{name:D.GITHUB_SEARCH_CODE,schema:In,inputSchema:On},{name:D.GITHUB_FETCH_CONTENT,schema:Lt,inputSchema:kn},{name:D.GITHUB_VIEW_REPO_STRUCTURE,schema:Un,inputSchema:Qn},{name:D.GITHUB_SEARCH_REPOSITORIES,schema:Hn,inputSchema:Bn},{name:D.GITHUB_PULL_REQUESTS,schema:Fn,inputSchema:vn},{name:D.GITHUB_ISSUES,schema:Dn,inputSchema:Mn},{name:D.GITHUB_COMMITS,schema:Nn,inputSchema:Gn},...Ln()?[{name:D.GITHUB_RELEASES,schema:qt,inputSchema:Jt}]:[],...Vt()?[{name:D.GITHUB_DISCUSSIONS,schema:Zt,inputSchema:en}]:[],{name:D.PACKAGE_SEARCH,schema:$n,inputSchema:jn},{name:D.GITHUB_CLONE_REPO,schema:Xt,inputSchema:An},{name:D.LOCAL_RIPGREP,schema:tt,inputSchema:Yn},{name:D.LOCAL_VIEW_STRUCTURE,schema:Ot,inputSchema:Xn},{name:D.LOCAL_FIND_FILES,schema:kt,inputSchema:Vn},{name:D.LOCAL_FIND_DEAD_CODE,schema:It,inputSchema:Kn},{name:D.LOCAL_FETCH_CONTENT,schema:_t,inputSchema:zn},{name:le,schema:qn,inputSchema:Jn}],Lg=[...Ln()?[]:[{name:D.GITHUB_RELEASES,schema:qt,inputSchema:Jt,disabled:{envVar:"ENABLE_RELEASES"}}],...Vt()?[]:[{name:D.GITHUB_DISCUSSIONS,schema:Zt,inputSchema:en,disabled:{envVar:"ENABLE_DISCUSSIONS"}}]];function nt(e){return Nu.find(t=>t.name===e)??Lg.find(t=>t.name===e)}function Ft(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===D.PACKAGE_SEARCH?"Package":"Other"}function Ag(e){return[...e].sort((t,n)=>{let r=Hi.indexOf(Ft(t)),o=Hi.indexOf(Ft(n));if(r!==o)return r-o;let i=Mu.get(t)??Number.MAX_SAFE_INTEGER,s=Mu.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}import{z as Gu}from"zod";var _g=["id","researchGoal","reasoning"],Hu=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function kg(e){let t=nt(e);if(!t)return"{}";try{return JSON.stringify(Gu.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Gu.toJSONSchema(t.schema,{io:"input"}),null,2)}}function Ig(e){return JSON.stringify(e??{},null,2)}function Og(e){let t=Ft(e),n=[..._g];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function Fg(){return Hu.map(e=>({...e}))}function vg(){return JSON.stringify(Object.fromEntries(Hu.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function Dg(e,t){return t?.tools?.[e]?.description??e}import{z as Mg}from"zod";function er(e){let t=nt(e);if(!t)return[];let n=Mg.toJSONSchema(t.schema,{io:"input"});if(!tn(n))return[];let r=rt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Zn.has(i)&&!Qi(r[i])):[]);return Ui(r,o)}function Ng(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 Bi(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=tn(e.items)?e.items:void 0;return`array<${n?Bi(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(tn).map(Bi).filter(r=>r!=="value");if(n.length>0)return[...new Set(n)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Ui(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Zn.has(o))continue;let s=tn(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Bi(s),constraints:Ng(s),description:typeof s.description=="string"?s.description:void 0}),rt(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!Qi(s.properties?.[l]):!1):[]);r.push(...Ui(s.properties,u,a))}let c=s.type==="array"&&tn(s.items)?s.items:void 0;if(c&&rt(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!Qi(c.properties?.[l]):!1):[]);r.push(...Ui(c.properties,u,a))}}return r}function Uu(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[Bu(e,n)]}return Bu(e,t)}function Bu(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 rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tn(e){return rt(e)}function Qi(e){return tn(e)&&"default"in e}function Qu(e){return e===D.GITHUB_PULL_REQUESTS?[{label:"PR search (list)",query:{owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"PR detail (diffs + reviews)",query:{owner:"sindresorhus",repo:"slugify",prNumber:1,content:{comments:{discussion:!0},reviews:!0,patches:{mode:"all"}}}}]:e===D.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===D.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===D.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===D.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===D.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===D.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===D.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===D.LOCAL_FIND_DEAD_CODE?[{label:"default entrypoints (package.json + tests)",query:{path:"packages/octocode-tools-core",itemsPerPage:20}},{label:"explicit entrypoints",query:{path:"packages/octocode-tools-core",entrypoints:["src/index.ts","src/direct.ts"],includeTests:!1}}]:e===D.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,entryType:"f",itemsPerPage:100}}]:e===D.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===D.GITHUB_COMMITS?[{label:"file history (bounded window)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",since:"6m",itemsPerPage:10}},{label:"compare two refs (base...head)",query:{owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===D.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{packageName:"schema validation",page:1}}]:e===le?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function $u(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function Gg(e){let t=Qu(e);if(t.length>0)return t.map(r=>({...r,command:$u(e,r.query)}));let n=Bg(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:$u(e,n)}]}function Hg(e){return Gg(e)[0]?.query??{}}function Bg(e){if(!nt(e))return{};let t=er(e),n=t.filter(i=>!i.name.includes(".")),r=Ug(n),o={};for(let i of r)o[i.name]=Uu(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===le&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}var ju=4,$i=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]]),zu=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function Ug(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&&Qg(i)).sort($g),o=Math.max(ju,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=>!zu.has(i.name)).filter(i=>i.type!=="boolean").slice(0,ju)}function Qg(e){return zu.has(e.name)||e.type==="boolean"?!1:jg(e)?$i.has(e.name):!0}function $g(e,t){let n=$i.get(e.name)??Number.MAX_SAFE_INTEGER,r=$i.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function jg(e){return e.constraints?.includes("default ")===!0}function zg(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Fe("Tool input must be valid JSON.")}return Wu(e,r,n)}function Wu(e,t,n={}){let r=Vg(e,t,n),o=nt(e);if(!o)throw new Fe(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Fe("Tool input does not match the expected schema.",Wg(i.error));return i.data}function Wg(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function Vg(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(rt(t)&&Array.isArray(t.queries))r=t.queries;else if(rt(t))r=[t];else throw new Fe('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Fe("At least one query is required.");let o=rt(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>Kg(e,a,ty(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function Kg(e,t,n,r){let o={...n},i=Ft(e),s=r.sourceLabel??"direct tool execution",a=Yg(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 Yg(e,t){return`Execute ${e} via ${t}`}function Xg(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 qg(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),u=Xg(n,c);if(c.includes(n)||n.includes(c)){u<o&&(r=a,o=u);continue}if(n.length<3)continue;let l=Math.max(2,Math.floor(a.length/3));u<=l&&u<s&&(i=a,s=u)}return r??i}var Jg=new Set(["none","standard","symbols"]),Zg={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"searchText",keywords:"searchText",language:"langType"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:{field:"minify",map:e=>{if(e===!0)return"standard";if(e===!1)return"none";if(typeof e=="string"&&Jg.has(e))return e}}},ghSearchPullRequests:{merged:{field:"state",map:e=>e===!0?"merged":void 0}},ghSearchCommits:{filePath:"path"},localFindFiles:{maxResults:"limit"}};function ey(e,t){let n=Zg[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n)){if(!(o in t))continue;let s=typeof i=="string"?i:i.field;if(s in t){r??={...t},delete r[o];continue}let a=typeof i=="string"?t[o]:i.map(t[o]);a!==void 0&&(r??={...t},r[s]=a,delete r[o])}return r??t}function ty(e,t,n,r={}){if(!rt(t))throw new Fe("Tool input must be a JSON object or an array of objects.");let o=ey(e,t),i=new Set([...er(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Zn]),s={},a=[];for(let[c,u]of Object.entries(o)){if(i.has(c)){s[c]=u;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(u=>{let l=qg(u,i);return l?`'${u}' \u2192 did you mean '${l}'?`:""}).filter(Boolean);throw new Fe(`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}function mt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function nn(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 oo(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var tr=new Map,ny=300*1e3;function ry(e){let t=mt(e),n=tr.get(t);return!n||Date.now()-n.cachedAt>=ny?!1:n.credentials?!nn(n.credentials):!0}function ji(e){e?tr.delete(mt(e)):tr.clear()}function Vu(e){let t=mt(e);if(ry(t))return tr.get(t).credentials}function Ku(e,t){let n=mt(e);tr.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as qu,readFileSync as Ju,writeFileSync as Zu,unlinkSync as i_,statSync as dy,chmodSync as py}from"node:fs";import{createCipheriv as my,createDecipheriv as fy,randomBytes as el}from"node:crypto";import{existsSync as oy,mkdirSync as iy}from"node:fs";import{join as He}from"node:path";import{getOctocodeHome as sy}from"@octocodeai/config";var ay=448;function cy(){return sy(process.env)}function rn(){return ke}var ke=cy(),ot={home:ke,config:He(ke,".octocoderc"),credentials:He(ke,"credentials.json"),key:He(ke,".key"),session:He(ke,"session.json"),stats:He(ke,"stats.json"),tmp:He(ke,"tmp"),clone:He(ke,"tmp","clone"),tree:He(ke,"tmp","tree"),repos:He(ke,"tmp","clone"),cliConfig:He(ke,"config.json"),lspConfig:He(ke,"lsp-servers.json")};function Yu(){oy(ot.home)||iy(ot.home,{recursive:!0,mode:ay})}import{z as ge}from"zod";var uy=ge.object({token:ge.string(),tokenType:ge.literal("oauth"),scopes:ge.array(ge.string()).optional(),refreshToken:ge.string().optional(),expiresAt:ge.string().optional(),refreshTokenExpiresAt:ge.string().optional()}),ly=ge.object({hostname:ge.string(),username:ge.string(),token:uy,gitProtocol:ge.enum(["ssh","https"]),createdAt:ge.string(),updatedAt:ge.string()}),Xu=ge.object({version:ge.number(),credentials:ge.record(ge.string(),ly)});var tl=ot.home,nr=ot.credentials,vt=ot.key,nl="aes-256-gcm",hy=16;function Dt(){Yu()}function rl(){if(Dt(),qu(vt))return dy(vt).mode&511&63&&py(vt,384),Buffer.from(Ju(vt,"utf8"),"hex");let e=el(32);return Zu(vt,e.toString("hex"),{mode:384}),e}function zi(e){let t=rl(),n=el(hy),r=my(nl,t,n),o=r.update(e,"utf8","hex");o+=r.final("hex");let i=r.getAuthTag();return`${n.toString("hex")}:${i.toString("hex")}:${o}`}function Wi(e){let t=rl(),[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=fy(nl,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function io(){if(Dt(),!qu(nr))return{version:1,credentials:{}};try{let e=Ju(nr,"utf8"),t=Wi(e),n=JSON.parse(t),r=Xu.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function ol(e){Dt();let t=zi(JSON.stringify(e,null,2));Zu(nr,t,{mode:384})}import{refreshToken as gy}from"@octokit/oauth-methods";import{request as yy}from"@octokit/request";var rr="178c6fc778ccc68e1d6a",on="github.com";function Ry(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 Sy(e){return e==="github.com"||e===on?"https://api.github.com":`https://${e}/api/v3`}async function il(e,t=on,n=rr){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(oo(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await gy({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:yy.defaults({baseUrl:Sy(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?Ry(o.message):"Token refresh failed"}}}async function sl(e,t=on,n=rr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!nn(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await il(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as Py}from"@octocodeai/config";import{execFile as by}from"child_process";var Cy=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Vi(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=Cy.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;by("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Ki=null;function al(e){Ki=e}function xy(){if(!Ki)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Ki}async function so(e){let t=e?.hostname??on,n=e?.clientId??rr,r=e?.getGhCliToken??Vi,o=Py();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await xy().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}async function cl(e){let t=mt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=io();return r.credentials[t]=n,ol(r),ji(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Yi(e="github.com",t){let n=mt(e);if(!t?.bypassCache){let i=Vu(n);if(i!==void 0)return i}let o=io().credentials[n]||null;return Ku(n,o),o}async function ul(e,t){let n=await Yi(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await cl(n),!0):!1}async function ll(e,t){return sl({getCredentials:Yi,updateToken:ul},e,t)}al({getTokenWithRefresh:ll});import ao from"node:os";import W_ from"node:path";var Ly=ao.platform()==="win32",Ay=ao.platform()==="darwin",_y=ao.platform()==="linux",ky=ao.homedir();import{randomUUID as bk}from"node:crypto";import{existsSync as hl,readFileSync as gl,writeFileSync as Dy,unlinkSync as ok,renameSync as My}from"node:fs";import{isStatsEnabled as yl}from"@octocodeai/config";import{z}from"zod";var Iy=z.object({rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),calls:z.number()}),Oy=z.object({hits:z.record(z.string(),z.number()).default({}),rateLimits:z.number().default(0)}),co=z.record(z.string(),z.number()).default({}),Fy=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:co,rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),charSavingsCalls:z.number(),githubCacheHits:z.number(),githubCacheRateLimits:z.number(),packageRegistryFailures:z.number().default(0),packageRegistryFailuresByRegistry:co}),uo=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:co,charsSavedByTool:z.record(z.string(),Iy).default({}),githubCacheHits:Oy.default({hits:{},rateLimits:0}),packageRegistryFailures:co,totalUsage:Fy.optional()}),dl=z.object({version:z.literal(1),sessionId:z.string(),createdAt:z.string(),lastActiveAt:z.string(),stats:uo.optional()}),pl=z.object({version:z.literal(1),stats:uo});function ml(e){return Object.values(e).reduce((t,n)=>t+n,0)}function vy(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:ml(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:ml(o),packageRegistryFailuresByRegistry:o}}function ft(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:vy(t)}}function sn(){return ft({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var or=ot.session,ir=ot.stats;function fl(e,t){let n=`${e}.tmp`;Dy(n,JSON.stringify(t,null,2),{mode:384}),My(n,e)}function Ny(e){let t=JSON.parse(e),n=pl.safeParse(t);if(n.success)return ft(n.data.stats);let r=uo.safeParse(t);return r.success?ft(r.data):null}function Gy(){if(!hl(ir))return sn();try{let e=gl(ir,"utf8");return Ny(e)??sn()}catch{return sn()}}function Xi(e){Dt(),yl()&&fl(ir,{version:e.version,stats:ft(e.stats)});let{stats:t,...n}=e;fl(or,n)}function Rl(){if(!hl(or))return null;try{let e=gl(or,"utf8"),t=JSON.parse(e),n=dl.safeParse(t);return n.success?{...n.data,stats:yl()?Gy():sn()}:null}catch{return null}}var Hy=6e4,ht=null,sr=!1,qi=null,Sl=!1,bl=null,Cl=null,Pl=null,Ji=!1;function By(){Sl||(Sl=!0,bl=()=>{lo()},Cl=()=>{lo()},Pl=()=>{lo()},process.on("exit",bl),process.on("SIGINT",Cl),process.on("SIGTERM",Pl))}function Uy(){qi||(qi=setInterval(()=>{sr&&ht&&(Xi(ht),sr=!1)},Hy),qi.unref())}function xl(){if(ht)return ht;let e=Rl();return e&&(ht=e),e}function wl(e){ht=e,sr=!0,By(),Uy()}function lo(){if(!Ji&&sr&&ht){Ji=!0;try{Xi(ht),sr=!1}catch{}finally{Ji=!1}}}function Qy(e){return ft(e)}function $y(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 Tl(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function jy(e,t){if(!t)return e;let n={...e.hits};for(let[r,o]of Object.entries(t.hits??{}))n[r]=(n[r]??0)+o;return{hits:n,rateLimits:e.rateLimits+(t.rateLimits??0)}}function gt(e){let t=xl();if(!t)return{success:!1,session:null};let n=Qy(t.stats),r=ft({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Tl(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:$y(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:jy(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Tl(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return wl(o),{success:!0,session:o}}function Zi(e=1){return gt({rateLimits:e})}function es(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return gt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function ts(e,t=1){return gt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ns(e=1){return gt({githubCacheHits:{hits:{},rateLimits:e}})}import{z as ue}from"zod";var zy=ue.looseObject({$schema:ue.string().optional(),version:ue.number().int().optional(),github:ue.record(ue.string(),ue.unknown()).optional(),local:ue.record(ue.string(),ue.unknown()).optional(),tools:ue.record(ue.string(),ue.unknown()).optional(),network:ue.record(ue.string(),ue.unknown()).optional(),lsp:ue.record(ue.string(),ue.unknown()).optional(),output:ue.record(ue.string(),ue.unknown()).optional()});import{existsSync as Wy,readdirSync as Vy,lstatSync as Ky}from"node:fs";import{join as Yy}from"node:path";function po(e){if(!Wy(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Vy(r)}catch{continue}for(let i of o){let s=Yy(r,i);try{let a=Ky(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}import{getConfigSync as El,invalidateConfigCache as uI}from"@octocodeai/config";var Mt="18.0.1";var rs={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},ar={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"}},cr={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})`}},qy={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"}},yt={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}`}},Rt={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"}},Ce={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}`}},Jy={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}`}},ur={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Zy={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}`}},iI={...rs,...ar,...cr,...qy,...yt,...Rt,...Ce,...Jy,...ur,...Zy};import{maskSensitiveData as eR}from"@octocodeai/octocode-engine/mask";var dr=null,lr=null,tR=so;var nR=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function Ll(){try{let e=await tR({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:nR.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Al(){if(dr!==null)return;if(lr!==null)return lr;let e=(async()=>{let t=El(),n=await Ll();dr={version:Mt,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}})();lr=e;try{await e}catch(t){throw lr===e&&(dr=null,lr=null),t}}function mo(){if(!dr){let e=eR(rs.NOT_INITIALIZED.message);throw new Error(e)}return dr}async function os(){return(await Ll()).token}function _l(){let e=mo();return e.enableLocal&&e.enableClone}function is(){return"github"}function ss(){let e=El().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as BR}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as rR}from"node:module";var oR=rR(import.meta.url),kl="@octocodeai/octocode-engine",iR=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??oR(kl),fo,sR=iR,as=class extends Error{constructor(n){super(`Failed to load native dependency ${kl}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function J(){if(fo)return fo;try{return fo=sR(),fo}catch(e){throw new as(e)}}var F={applyContentViewMinification(e,t){return J().applyContentViewMinification(e,t)},applyMinification(e,t){return J().applyMinification(e,t)},minifyContent(e,t){return J().minifyContent(e,t)},minifyContentSync(e,t){return J().minifyContentSync(e,t)},minifyContentResult(e,t){return J().minifyContentResult(e,t)},minifyMarkdownCore(e){return J().minifyMarkdownCore(e)},extractSignatures(e,t){return J().extractSignatures(e,t)},extractJsSymbols(e,t){return J().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return J().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return J().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return J().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return J().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return J().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return J().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return J().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return J().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return J().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return J().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return J().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return J().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return J().parseRipgrepJson(e,t)},searchRipgrep(e){return J().searchRipgrep(e)},queryFileSystem(e){return J().queryFileSystem(e)},extractMatchingLines(e,t,n){return J().extractMatchingLines(e,t,n)},filterPatch(e,t){return J().filterPatch(e,t)},computeLineDiff(e,t){return J().computeLineDiff(e,t)},charToByteOffset(e,t){return J().charToByteOffset(e,t)},byteToCharOffset(e,t){return J().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return J().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return J().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return J().SIGNATURES_ONLY_HINT}};import{Octokit as aR}from"octokit";import{throttling as cR}from"@octokit/plugin-throttling";import{createHash as uR}from"crypto";function St(e){(e.provider?gt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Zi(1)).session&&e.provider==="github"&&ns(1)}function Il(e){gt({packageRegistryFailures:{[e]:1}})}function Ml(e){return uR("sha256").update(e).digest("hex").substring(0,16)}async function pe(e){let t=e?.token??await os(),n=t?Ml(t):"anon",r=mo().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var lR=aR.plugin(cR),dR=300*1e3,cs=50,pR=60*1e3;function Nl(e){return Date.now()-e.createdAt>dR}var it=new Map,pr=null;function Gl(){for(let[e,t]of it.entries())Nl(t)&&it.delete(e);if(it.size>cs){let e=it.size-cs,t=0;for(let[n]of it){if(t>=e)break;it.delete(n),t++}}}function mR(){pr||(pr=setInterval(Gl,pR),typeof pr=="object"&&"unref"in pr&&pr.unref())}var Ol=3,Fl=60;function vl(e,t,n){St({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var fR=()=>({onRateLimit:(e,t,n,r)=>(vl("primary",e,t),r<Ol&&e<Fl),onSecondaryRateLimit:(e,t,n,r)=>(vl("secondary",e,t),r<Ol&&e<Fl)});function hR(e){let t=mo(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Mt}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:fR(),log:r,...e&&{auth:e}};return new lR(o)}async function U(e){mR();let t=e?.token??await os(),n=t?Ml(t):"ANONYMOUS",r=it.get(n);if(r&&!Nl(r))return r.client;it.size>=cs&&Gl();let o=hR(t??void 0);return it.set(n,{client:o,createdAt:Date.now()}),o}var gR=200,mr=new Map;async function Pe(e,t,n){let r=`${e}/${t}`,o=mr.get(r);if(o)return o;let i=await U(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Dl(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}),Dl(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 Dl(e,t){if(mr.size>=gR){let n=mr.keys().next().value;n!==void 0&&mr.delete(n)}mr.set(e,t)}import{RequestError as Bl}from"octokit";var j={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"},me={[j.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."},[j.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."},[j.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},[j.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)."},[j.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."},[j.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."},[j.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."},[j.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."},[j.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."},[j.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Hl={401:j.AUTH_REQUIRED,403:j.FORBIDDEN_PERMISSIONS,404:j.NOT_FOUND,422:j.INVALID_REQUEST,502:j.SERVER_UNAVAILABLE,503:j.SERVER_UNAVAILABLE,504:j.SERVER_UNAVAILABLE},us={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},ls={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ho={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var yR=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function We(e){if(!(e instanceof Bl)||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 yR.some(o=>r.includes(o))})}function W(e){return e instanceof Bl?RR(e):e instanceof Error?ER(e):{error:typeof e=="string"?e:me[j.UNKNOWN].message,type:"unknown"}}function RR(e){let{status:t,message:n,response:r}=e;if(t===403)return bR(n,r);if(t===429)return SR(n,r);let o=Hl[t];return o?TR(o,t):an(j.UNKNOWN,{error:n||me[j.UNKNOWN].message,status:t})}function ds(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function SR(e,t){let n=t?.headers,r=ds(n,"retry-after"),o=ds(n,"x-ratelimit-reset"),i=ds(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ho.RESET_BUFFER_SECONDS,0):void 0);return St({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),an(j.RATE_LIMIT_PRIMARY,{error:e||me[j.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:me[j.RATE_LIMIT_PRIMARY].suggestion})}function bR(e,t){let n=t?.headers;if(ls.SECONDARY.test(e))return CR(n);let r=n?.["x-ratelimit-remaining"],o=wR(t);return r!==void 0&&String(r)==="0"||o?PR(n):xR(n)}function CR(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ho.SECONDARY_FALLBACK_SECONDS:t;return St({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),an(j.RATE_LIMIT_SECONDARY,{error:me[j.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:me[j.RATE_LIMIT_SECONDARY].suggestion})}function PR(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)+ho.RESET_BUFFER_SECONDS,0):void 0,i=r?me[j.RATE_LIMIT_PRIMARY].messageWithTime(r,o):me[j.RATE_LIMIT_PRIMARY].messageWithoutTime;return St({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),an(j.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:me[j.RATE_LIMIT_PRIMARY].suggestion})}function xR(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=me[j.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=LR(String(t),String(n))),an(j.FORBIDDEN_PERMISSIONS,{error:me[j.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function wR(e){return e?.data?.errors?.some(n=>n.type===ls.GRAPHQL_TYPE)??!1}function TR(e,t){let n=me[e];return an(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function ER(e){return us.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:me[j.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:me[j.NETWORK_CONNECTION_FAILED].suggestion}:us.TIMEOUT.some(t=>e.message.includes(t))?{error:me[j.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:me[j.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function an(e,t){return{type:"http",...t}}function LR(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?me[j.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):me[j.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Ul(e){return`user:${e}`}var AR=/[@/]/,_R=/^[A-Za-z0-9_-]+$/;function ps(e){return e.startsWith('"')||_R.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var st=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(Ul(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=AR.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var kR=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ms=class extends st{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(ps))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(kR):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}},fs=class extends st{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(ps)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function hs(e){return new ms().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function gs(e){return new fs().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var ys=class extends st{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function Rs(e){return new ys().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ss(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var bs=class extends st{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function Cs(e){return new bs().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ps(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import IR from"crypto";var OR="v2",FR=new Set([]);function vR(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(FR.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function se(e,t,n){let r=xs(vR(t)),o=n?`${n}:${r}`:r,i=IR.createHash("sha256").update(o).digest("hex");return`${OR}-${e}:${i}`}function xs(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=>xs(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${xs(i,t)}`}).join(",")}}`)}import DR from"node-cache";var MR=300*1e3,Be=new DR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ve={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Ql={"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},Ue=new Map;function NR(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function GR(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function fr(e){let t=NR(e);if(!(!t||!GR(t)))try{ts(t,1)}catch{}}function go(){let e=Date.now();for(let[t,n]of Ue.entries())e-n.startedAt>MR&&Ue.delete(t)}function hr(e){return Ql[e]||Ql.default}function gr(e,t,n){try{return Be.set(e,t,n),ve.sets++,ve.totalKeys=Be.keys().length,!0}catch{try{let r=Be.keys();for(let o of r)Be.get(o);return Be.set(e,t,n),ve.sets++,ve.totalKeys=Be.keys().length,!0}catch{return!1}}}async function fe(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Be.get(e);if(i!==void 0)return ve.hits++,fr(e),i}catch{}go();let r=Ue.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ve.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=hr(u)}gr(e,i,a)}return i}finally{Ue.delete(e)}})();return Ue.set(e,{promise:o,startedAt:Date.now()}),o}import HR from"node-cache";var ws=new HR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function yo(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Be.get(e);if(i!==void 0)return ve.hits++,fr(e),i}catch{}go();let r=Ue.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:ws.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ve.hits++,fr(e);let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=hr(l)}return gr(e,i.data,c),i.data}if(n.forceRefresh||ve.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=hr(l)}gr(e,s.value,c),ws.set(e,{data:s.value,etag:s.etag})}return s.value}finally{Ue.delete(e)}})();return Ue.set(e,{promise:o,startedAt:Date.now()}),o}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as uO,DISCOVERY_IGNORED_FILE_NAMES as lO,DISCOVERY_IGNORED_FOLDER_NAMES as dO,getDiscoveryExtension as $l,shouldIgnoreDiscoveryDir as yr,shouldIgnoreDiscoveryFile as cn}from"@octocodeai/octocode-engine/security";var jl=Symbol.for("octocode.rawResponseChars");function N(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function zl(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function Q(e,t){let n=typeof t=="number"?zl(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,jl,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function te(e){if(!(typeof e!="object"||e===null))return zl(e[jl])}function un(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 Wl(e){let t=un(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function ln(e){let t=un(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function Vl(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var Kl=30;async function Yl(e,t,n){let r=await pe(t),o=se("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await fe(o,async()=>await UR(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function UR(e,t){try{let n=await U(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(h=>h&&h.trim()).length===0)return{error:Ce.QUERY_EMPTY.message,type:"http",status:400};let r=hs(e);if(!r.trim())return{error:Ce.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Kl,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 QR(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,d=Math.min(l,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),f=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...u?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:f,...f?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:un(a.headers),rawResponseChars:N(a.data)}}catch(n){if(We(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Kl,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 W(n)}}async function QR(e,t){let n=$R(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!cn(p.path)),c=0,u=0,l=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],g=await Promise.allSettled((p.text_matches||[]).map(async C=>{let x=C.fragment,T=BR.sanitizeContent(x||"",p.path);x=T.content,T.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(_=>r.add(`${p.path}: ${_}`));try{let _=await F.minifyContent(x||"",p.path);x=_.content,_.failed?o=!0:_.type!=="failed"&&(f.push(_.type),i.push(_.type))}catch{o=!0}let L=C.matches?.flatMap(_=>Array.isArray(_.indices)&&_.indices.length>=2?[[_.indices[0],_.indices[1]]]:[])||[];return{context:x||"",positions:Vl(C.fragment||"",L,x||"")}})),R=g.filter(C=>C.status==="fulfilled").map(C=>C.value),h=g.filter(C=>C.status==="rejected").length;h>0&&(u+=h);let y=p,S=Array.from(new Set(f));return{path:p.path,matches:R,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...y.last_modified_at&&{lastModifiedAt:y.last_modified_at},...S.length>0&&{minificationType:S.join(",")}}})),d=l.filter(p=>p.status==="fulfilled").map(p=>p.value);c=l.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`),u>0&&r.add(`${u} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function $R(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 Xl=30;function ql(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 Jl(e,t,n){let r=await pe(t),o=e,i=se("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await fe(i,async()=>await zR(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function jR(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 W(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 W(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),R=g[0]||"",h=g[1]||"";return{owner:R,repo:h,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},...ql(p)}}),c=a.length,u=c===n,l=(r-1)*n+c,d=s??l+(u?1:0),m=s!==void 0||!u?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:u?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:l,totalMatchesKind:m,hasMore:u,...u?{nextPage:r+1}:{}}},status:200,rawResponseChars:N(i)}}async function zR(e,t){try{let n=await U(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 jR({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=gs(e);if(!i.trim())return{error:Ce.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Xl,100),a=e.page||1,c={q:i,per_page:s,page:a},u=["stars","forks","help-wanted-issues","updated"];e.sort&&u.includes(e.sort)&&(c.sort=e.sort);let l=await n.rest.search.repos(c),d=l.data.items.map(y=>{let C=y.full_name.split("/"),x=C[0]||"",T=C[1]||"";return{owner:x,repo:T,defaultBranch:y.default_branch,stars:y.stargazers_count||0,description:y.description?y.description:"No description",url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at,pushedAt:y.pushed_at,visibility:y.visibility,...y.topics&&y.topics.length>0&&{topics:y.topics},...y.forks_count&&y.forks_count>0&&{forksCount:y.forks_count},...y.open_issues_count&&y.open_issues_count>0&&{openIssuesCount:y.open_issues_count},...y.language&&{language:y.language},...ql(y)}}),m=l.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,f)),R=g<f,h=Math.min(p,f*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:R,...R?{nextPage:g+1}:{}}},status:200,headers:un(l.headers),rawResponseChars:N(l.data)}}catch(n){if(We(n)){let r=Math.min(e.limit||Xl,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 W(n)}}function Ie(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function he(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 WR(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 at(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:WR(e)}}function Ro(e){return VR(e)?at({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 VR(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||KR(n)}function KR(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Rr(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function YR(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,...Rr(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function XR(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,...Rr(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Zl(e,t,n=he){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 Yl(s,t);return Ie(a)?at(a):a.data?{data:YR(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function ed(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 Jl(n,t);return"error"in r?Ro(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:XR(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??N(r.data)}}import{RequestError as Is}from"octokit";import{completeMetadata as Ts}from"@octocodeai/octocode-core";var P=new Proxy({},{get(e,t){return Ts.toolNames[t]},ownKeys(){return Object.keys(Ts.toolNames)},getOwnPropertyDescriptor(e,t){let n=Ts.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as JR}from"@octocodeai/octocode-core";var Es=new Proxy({},{get(e,t){return JR.tools[t]?.description??""}});import{completeMetadata as ZR}from"@octocodeai/octocode-core";function Ls(e){return Object.prototype.hasOwnProperty.call(ZR.tools,e)}import{completeMetadata as eS}from"@octocodeai/octocode-core";function As(){return eS.baseSchema}var tS=new Proxy({},{get(e,t){return As()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(As())]))},getOwnPropertyDescriptor(e,t){let n=As();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});function _s(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 ks(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,u=[],l=c.find(p=>p.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>u.push(p.path)),u.length===0&&d.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(f=>u.push(f.path)),Array.from(new Set(u)).slice(0,3)}catch{return[]}}async function nS(e,t,n,r,o,i,s,a){let c=await Pe(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let l=W(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 ks(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],..._s(i,m)]),{...l,...d&&{scopesSuggestion:d}}}async function rS(e,t,n,r,o,i){let s=W(t),a=await ks(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],..._s(o,a)]),s}async function td(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:yt.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:yt.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:yt.DECODE_FAILED.message,type:"unknown",status:422}}}async function nd(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"?td(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return W(i)}}async function oS(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 Pe(t,n,i).catch(()=>"HEAD"),u=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(u.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let l=u.data.find(m=>m.name===a&&m.type==="file");if(!l)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await nd(e,t,n,l.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 W(s)}}async function Sr(e,t,n={}){try{let r=await U(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},u,l=a;try{u=await r.rest.repos.getContent(c)}catch(p){if(p instanceof Is&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof Is&&p.status===404)if(a){let f=await nS(r,p,c,o,i,s,a,t);if("result"in f)u=f.result,l=f.actualBranch;else return f}else return await rS(r,p,o,i,s,a);else{if(p instanceof Is&&p.status===413)return await oS(r,o,i,s,a||l,t);throw p}}let d=u.data,m=ln(u.headers);if(Array.isArray(d))return{error:yt.PATH_IS_DIRECTORY.message(P.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",f=d.size??0,g;if(p.length>0)g=await td(p,s);else if(f>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await nd(r,o,i,d.sha,s);else return{error:yt.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!l&&!a)try{l=await Pe(o,i,t)}catch{}return{data:{rawContent:g.data,branch:l||void 0,resolvedRef:l||a||"HEAD"},status:200,rawResponseChars:N(d),...m?{etag:m}:{}}}return{error:yt.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return W(r)}}import{ContentSanitizer as Ns}from"@octocodeai/octocode-engine/contentSanitizer";function So(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Ve(e){return So(e).length}function bo(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Invalid regex pattern: ${l}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
10
|
-
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=F.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(u=>({start:u.start,end:u.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(u=>u)}}var
|
|
11
|
-
`)}function
|
|
12
|
-
`,t);return n===-1?void 0:n+1}function
|
|
13
|
-
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function
|
|
14
|
-
`),x=Ve(S),T=e,L,
|
|
15
|
-
`);let Z=B.matchRanges[0],v=B.matchRanges[B.matchRanges.length-1];s=Z.start,a=v.end,L=Z.start,
|
|
16
|
-
`),B>x&&y.add(`Requested endLine ${B} adjusted to ${x} (file end)`)}}let M=
|
|
8
|
+
import{completeMetadata as tg}from"@octocodeai/octocode-core";var D=tg.toolNames,le=D.LSP_GET_SEMANTIC_CONTENT;function Ln(e=process.env){let t=e.ENABLE_RELEASES;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function Vt(e=process.env){let t=e.ENABLE_DISCUSSIONS;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var vE=new Set([D.LOCAL_RIPGREP,D.LOCAL_FETCH_CONTENT,D.LOCAL_FIND_FILES,D.LOCAL_VIEW_STRUCTURE,le]);var Jc=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];function Ze(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0},...e.lineDeviation!==void 0&&{lineDeviation:e.lineDeviation}}}function Di(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}}}import{CloneRepoQuerySchema as sg}from"@octocodeai/octocode-core/schemas";import{z as no}from"zod";function _(e,t){return no.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,no.number().int().min(e).max(t))}var V=_(1,1e3).optional().default(1),Kt=_(0,100).optional(),Yt=_(1,1e9).optional(),rg={responseCharOffset:_(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:_(1,5e4).optional().describe("Full-response char window.")};function K(e,t={}){let{maxQueries:n=5}=t;return no.object({queries:no.array(e).min(1).max(n).describe("Parallel queries."),...rg}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}import{z as Zc}from"zod";function og(e,t){return e?.description&&!t.description?t.describe(e.description):t}function eu(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=og(e.shape[r],o);return n}function ig(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function tu(e,t){if(!t?.length)return e;let n=new Set(t);return Zc.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function Y(e,t={},n={}){let r=tu(e,n.omit),o=ig(r,eu(r,t));return n.strict?o.strict():o}function q(e,t={},n={}){let r=tu(e,n.omit),o=Zc.object({...r.shape,...eu(r,t)});return n.strict?o.strict():o}var Xt=Y(sg),An=K(Xt);import{z as ag}from"zod";import{FileContentQuerySchema as nu}from"@octocodeai/octocode-core/schemas";var cg=ag.enum(["none","standard","symbols"]).optional(),ru={startLine:Yt,endLine:Yt,contextLines:Kt,charOffset:_(0,1e8).optional(),charLength:_(1,5e4).optional(),minify:cg},ug=q(nu,ru),Lt=Y(nu,ru),_n=K(ug);import{z as lg}from"zod";import{GitHubCodeSearchQuerySchema as ou}from"@octocodeai/octocode-core/schemas";var iu={limit:_(1,100).optional(),page:V.default(1),match:lg.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghSearchPullRequests, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},In=Y(ou,iu),On=K(q(ou,iu));import{z as Ni}from"zod";import{GitHubPullRequestSearchQuerySchema as su}from"@octocodeai/octocode-core/schemas";var au={type:Ni.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),prNumber:_(1,1e9).optional(),issueNumber:_(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:_(1,100).optional().default(30),match:Ni.array(Ni.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:V.default(1),filePage:V.optional(),commentPage:V.optional(),commitPage:V.optional(),itemsPerPage:_(1,100).optional().default(20),charOffset:_(0,1e8).optional(),commentBodyOffset:_(0,1e8).optional(),charLength:_(1,5e4).optional()},dg=q(su,au),Gi=Y(su,au),pg=K(dg);import{SearchPullRequestsQuerySchema as cu,SearchIssuesQuerySchema as uu,SearchCommitsQuerySchema as lu,ListReleasesQuerySchema as du}from"@octocodeai/octocode-core/schemas";var pu={limit:_(1,100).optional().default(30),page:V.default(1),itemsPerPage:_(1,100).optional().default(20)},mu={...pu,filePage:V.optional(),commentPage:V.optional(),commitPage:V.optional(),charOffset:_(0,1e8).optional(),commentBodyOffset:_(0,1e8).optional(),charLength:_(1,1e5).optional()},Fn=Y(cu,mu),vn=K(q(cu,mu)),fu={...pu,commentPage:V.optional(),charOffset:_(0,1e8).optional(),commentBodyOffset:_(0,1e8).optional(),charLength:_(1,1e5).optional()},Dn=Y(uu,fu),Mn=K(q(uu,fu)),hu={page:V.default(1),limit:_(1,100).optional().describe("Commits per page \u2014 alias of itemsPerPage (preferred when both are set)."),filePage:V.optional(),charOffset:_(0,1e8).optional(),charLength:_(1,1e5).optional()},Nn=Y(lu,hu),Gn=K(q(lu,hu)),gu={page:V.default(1),limit:_(1,100).optional().describe("Releases per page \u2014 alias of itemsPerPage (preferred when both are set).")},qt=Y(du,gu),Jt=K(q(du,gu));import{SearchDiscussionsQuerySchema as yu}from"@octocodeai/octocode-core/schemas";var Ru={itemsPerPage:_(1,100).optional().default(20),limit:_(1,100).optional()},Zt=Y(yu,Ru),en=K(q(yu,Ru));import{z as Su}from"zod";import{GitHubReposSearchSingleQuerySchema as bu}from"@octocodeai/octocode-core/schemas";var Cu={limit:_(1,100).optional(),page:V.default(1),match:Su.array(Su.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.)")},Hn=Y(bu,Cu),Bn=K(q(bu,Cu));import{GitHubViewRepoStructureQuerySchema as Pu}from"@octocodeai/octocode-core/schemas";var xu={maxDepth:_(0,20).optional(),page:V.default(1),itemsPerPage:_(1,200).optional()},Un=Y(Pu,xu),Qn=K(q(Pu,xu));import{z as ro}from"zod";import{NpmPackageQuerySchema as wu}from"@octocodeai/octocode-core/schemas";var Tu={page:V,keywords:ro.union([ro.string(),ro.array(ro.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},$n=Y(wu,Tu),jn=K(q(wu,Tu,{strict:!0}),{maxQueries:5});import{z as fg}from"zod";import{FetchContentQuerySchema as Eu}from"@octocodeai/octocode-core/schemas";var hg=fg.enum(["none","standard","symbols"]).optional(),Lu={startLine:Yt,endLine:Yt,contextLines:Kt.default(5),charOffset:_(0,1e8).optional(),charLength:_(1,5e4).optional(),minify:hg},gg=q(Eu,Lu),kt=Y(Eu,Lu),zn=K(gg,{maxQueries:5});import{z as Hi}from"zod";import{FindFilesQuerySchema as yg}from"@octocodeai/octocode-core/schemas";var Au={maxDepth:_(0,100).optional(),minDepth:_(0,100).optional(),limit:_(1,1e4).optional().describe("Discovery cap applied after sort, before pagination \u2014 total results are capped here; itemsPerPage/page page within that cap."),page:V.default(1),itemsPerPage:_(1,50).optional(),excludeDir:Hi.array(Hi.string()).optional().describe("Directory names to prune from the walk. Common generated/vendor dirs are pruned by default (node_modules, .git, dist, build, out, coverage, target, .next, .cache); pass [] to prune nothing, or pass an explicit list to choose pruned dirs.")},ku=Hi.object(Object.fromEntries(Object.entries(yg.shape).filter(([e])=>e!=="regexType")));function Rg(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 Sg=q(ku,Au),_t=Y(ku,Au).superRefine(Rg),Vn=K(Sg,{maxQueries:5});import{FindDeadCodeQuerySchema as _u}from"@octocodeai/octocode-core/schemas";var Iu={maxFiles:_(1,5e4).optional(),limit:_(1,5e3).optional(),page:V.default(1),itemsPerPage:_(1,50).optional()},bg=q(_u,Iu),It=Y(_u,Iu),Kn=K(bg,{maxQueries:5});import{z as pt}from"zod";import{RipgrepQuerySchema as Ou}from"@octocodeai/octocode-core/schemas";var Cg=["paginated","discovery","detailed","structural"],Pg=["semanticRanking"],Fu={mode:pt.enum(Cg).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghSearchPullRequests\'s `content.patches.mode` \u2014 different concepts sharing this name.)'),searchText:pt.string().optional().describe('The search pattern. regex:"fixed" for a literal match, "perl" for advanced features (lookaheads, backreferences), else "smart". (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)'),output:pt.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content").describe('"content" (default) matches with line text; "files"/"filesWithout" return matching/non-matching paths; "countLines"/"countMatches" return per-file counts; "matchOnly" returns just the matched substring (required for unique/matchWindow). ("files" is unlike localViewStructure\'s `filesOnly`, which filters a directory listing to file entries.)'),pattern:pt.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Modifiers are part of the node \u2014 `function $NAME` does not match `async function` or `export function`; include the modifiers or use a YAML `kind` rule for modifier-agnostic matches. Use this to find syntax shape, then use lspGetSemantics for semantic proof."),maxDepth:_(0,20).optional().describe("Keep files at most this many directory levels below the search root (0 = files directly in the root). Structural mode pushes this into the native walker; text/regex mode applies it after the native search and emits a warning when it filters deeper matches."),rule:pt.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),captureText:pt.boolean().optional().describe("Structural only: return full verbatim capture text for `$$$` list metavars (bodies, arg lists). Default false \u2014 list-capture text is omitted from `metavars`, and `metavarRanges` entries are comment-pruned and truncated to keep results lean; ranges always remain as line anchors."),contextLines:Kt,matchContentLength:_(1,1e5).optional().default(500),maxMatchesPerFile:_(1,1e5).optional(),maxFiles:_(1,1e5).optional(),matchPage:V.optional(),itemsPerPage:_(1,1e3).optional(),page:V.default(1),unique:pt.enum(["off","list","count"]).optional().default("off").describe('Needs output:"matchOnly". "list" returns each matched value once per file; "count" adds its frequency.')},xg={...Fu,semanticRanking:pt.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},wg=q(Ou,xg),Tg=Y(Ou,Fu,{strict:!0,omit:Pg}),tt=Tg.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let n=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(n){let r=n[0].slice(2);t.addIssue({code:"custom",message:`\`${n[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),Yn=K(wg,{maxQueries:5});import{z as vu}from"zod";import{ViewStructureQuerySchema as Du}from"@octocodeai/octocode-core/schemas";var Mu={excludeDir:vu.array(vu.string()).optional().describe("Directory names to prune from recursive walks (default: common generated/vendor dirs such as node_modules, dist, build, out, coverage, target). Pass [] to inspect everything."),maxDepth:_(0,20).optional(),limit:_(1,1e4).optional(),page:V.default(1),itemsPerPage:_(1,50).optional()},Eg=q(Du,Mu),Ot=Y(Du,Mu),Xn=K(Eg,{maxQueries:5});import{z as oo}from"zod";import{LspGetSemanticsQuerySchema as Nu}from"@octocodeai/octocode-core/schemas";var Lg=_(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),Ag=_(0,1e5).optional(),kg=["structured","compact"],Gu={type:oo.enum(Jc).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:oo.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:Lg.optional(),orderHint:Ag,depth:_(0,20).optional().describe("Traversal depth for call-hierarchy / type-hierarchy queries (0 = direct only)."),includeDeclaration:oo.boolean().optional().default(!0),page:V.describe("Result page for paginated reference/symbol lists (advance while pagination.hasMore)."),itemsPerPage:_(1,100).optional().describe("References/symbols returned per page (with page)."),contextLines:_(0,100).optional().describe("Lines of surrounding source shown around each result location."),format:oo.enum(kg).optional().default("structured")},_g=q(Nu,Gu),qn=Y(Nu,Gu);var Jn=K(_g,{maxQueries:5});var Ui=["GitHub","Local Code","Package","Other"],Hu=new Map([D.GITHUB_SEARCH_CODE,D.GITHUB_SEARCH_REPOSITORIES,D.GITHUB_PULL_REQUESTS,D.GITHUB_ISSUES,D.GITHUB_COMMITS,D.GITHUB_FETCH_CONTENT,D.GITHUB_VIEW_REPO_STRUCTURE,D.GITHUB_CLONE_REPO,D.LOCAL_RIPGREP,D.LOCAL_FIND_FILES,D.LOCAL_FIND_DEAD_CODE,D.LOCAL_FETCH_CONTENT,D.LOCAL_VIEW_STRUCTURE,le,D.PACKAGE_SEARCH,...Vt()?[D.GITHUB_DISCUSSIONS]:[]].map((e,t)=>[e,t])),Fe=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},Ig=["id","mainResearchGoal","researchGoal","reasoning"],Zn=new Set([...Ig]),Bu=[{name:D.GITHUB_SEARCH_CODE,schema:In,inputSchema:On},{name:D.GITHUB_FETCH_CONTENT,schema:Lt,inputSchema:_n},{name:D.GITHUB_VIEW_REPO_STRUCTURE,schema:Un,inputSchema:Qn},{name:D.GITHUB_SEARCH_REPOSITORIES,schema:Hn,inputSchema:Bn},{name:D.GITHUB_PULL_REQUESTS,schema:Fn,inputSchema:vn},{name:D.GITHUB_ISSUES,schema:Dn,inputSchema:Mn},{name:D.GITHUB_COMMITS,schema:Nn,inputSchema:Gn},...Ln()?[{name:D.GITHUB_RELEASES,schema:qt,inputSchema:Jt}]:[],...Vt()?[{name:D.GITHUB_DISCUSSIONS,schema:Zt,inputSchema:en}]:[],{name:D.PACKAGE_SEARCH,schema:$n,inputSchema:jn},{name:D.GITHUB_CLONE_REPO,schema:Xt,inputSchema:An},{name:D.LOCAL_RIPGREP,schema:tt,inputSchema:Yn},{name:D.LOCAL_VIEW_STRUCTURE,schema:Ot,inputSchema:Xn},{name:D.LOCAL_FIND_FILES,schema:_t,inputSchema:Vn},{name:D.LOCAL_FIND_DEAD_CODE,schema:It,inputSchema:Kn},{name:D.LOCAL_FETCH_CONTENT,schema:kt,inputSchema:zn},{name:le,schema:qn,inputSchema:Jn}],Og=[...Ln()?[]:[{name:D.GITHUB_RELEASES,schema:qt,inputSchema:Jt,disabled:{envVar:"ENABLE_RELEASES"}}],...Vt()?[]:[{name:D.GITHUB_DISCUSSIONS,schema:Zt,inputSchema:en,disabled:{envVar:"ENABLE_DISCUSSIONS"}}]];function nt(e){return Bu.find(t=>t.name===e)??Og.find(t=>t.name===e)}function Ft(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===D.PACKAGE_SEARCH?"Package":"Other"}function Fg(e){return[...e].sort((t,n)=>{let r=Ui.indexOf(Ft(t)),o=Ui.indexOf(Ft(n));if(r!==o)return r-o;let i=Hu.get(t)??Number.MAX_SAFE_INTEGER,s=Hu.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}import{z as Uu}from"zod";var vg=["id","researchGoal","reasoning"];function Dg(e){let t=nt(e);if(!t)return"{}";try{return JSON.stringify(Uu.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Uu.toJSONSchema(t.schema,{io:"input"}),null,2)}}function Mg(e){return JSON.stringify(e??{},null,2)}function Ng(e){let t=Ft(e),n=[...vg];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function Gg(e,t){return t?.tools?.[e]?.description??e}import{z as Hg}from"zod";function er(e){let t=nt(e);if(!t)return[];let n=Hg.toJSONSchema(t.schema,{io:"input"});if(!tn(n))return[];let r=rt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Zn.has(i)&&!ji(r[i])):[]);return $i(r,o)}function Bg(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 Qi(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=tn(e.items)?e.items:void 0;return`array<${n?Qi(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(tn).map(Qi).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 $i(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Zn.has(o))continue;let s=tn(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Qi(s),constraints:Bg(s),description:typeof s.description=="string"?s.description:void 0}),rt(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!ji(s.properties?.[l]):!1):[]);r.push(...$i(s.properties,u,a))}let c=s.type==="array"&&tn(s.items)?s.items:void 0;if(c&&rt(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!ji(c.properties?.[l]):!1):[]);r.push(...$i(c.properties,u,a))}}return r}function $u(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[Qu(e,n)]}return Qu(e,t)}function Qu(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 rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tn(e){return rt(e)}function ji(e){return tn(e)&&"default"in e}function ju(e){return e===D.GITHUB_PULL_REQUESTS?[{label:"PR search (list)",query:{owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"PR detail (diffs + reviews)",query:{owner:"sindresorhus",repo:"slugify",prNumber:1,content:{comments:{discussion:!0},reviews:!0,patches:{mode:"all"}}}}]:e===D.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===D.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===D.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===D.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===D.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===D.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===D.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===D.LOCAL_FIND_DEAD_CODE?[{label:"default entrypoints (package.json + tests)",query:{path:"packages/octocode-tools-core",itemsPerPage:20}},{label:"explicit entrypoints",query:{path:"packages/octocode-tools-core",entrypoints:["src/index.ts","src/direct.ts"],includeTests:!1}}]:e===D.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,entryType:"f",itemsPerPage:100}}]:e===D.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===D.GITHUB_COMMITS?[{label:"file history (bounded window)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",since:"6m",itemsPerPage:10}},{label:"compare two refs (base...head)",query:{owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===D.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{packageName:"schema validation",page:1}}]:e===le?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function zu(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function Ug(e){let t=ju(e);if(t.length>0)return t.map(r=>({...r,command:zu(e,r.query)}));let n=$g(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:zu(e,n)}]}function Qg(e){return Ug(e)[0]?.query??{}}function $g(e){if(!nt(e))return{};let t=er(e),n=t.filter(i=>!i.name.includes(".")),r=jg(n),o={};for(let i of r)o[i.name]=$u(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===le&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}var Wu=4,zi=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]]),Vu=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function jg(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&&zg(i)).sort(Wg),o=Math.max(Wu,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=>!Vu.has(i.name)).filter(i=>i.type!=="boolean").slice(0,Wu)}function zg(e){return Vu.has(e.name)||e.type==="boolean"?!1:Vg(e)?zi.has(e.name):!0}function Wg(e,t){let n=zi.get(e.name)??Number.MAX_SAFE_INTEGER,r=zi.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function Vg(e){return e.constraints?.includes("default ")===!0}function Kg(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Fe("Tool input must be valid JSON.")}return Ku(e,r,n)}function Ku(e,t,n={}){let r=Xg(e,t,n),o=nt(e);if(!o)throw new Fe(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Fe("Tool input does not match the expected schema.",Yg(i.error));return i.data}function Yg(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function Xg(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(rt(t)&&Array.isArray(t.queries))r=t.queries;else if(rt(t))r=[t];else throw new Fe('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Fe("At least one query is required.");let o=rt(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>qg(e,a,oy(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function qg(e,t,n,r){let o={...n},i=Ft(e),s=r.sourceLabel??"direct tool execution",a=Jg(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 Jg(e,t){return`Execute ${e} via ${t}`}function Zg(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 ey(e,t){let n=e.toLowerCase(),r,o=Number.POSITIVE_INFINITY,i,s=Number.POSITIVE_INFINITY;for(let a of t){let c=a.toLowerCase(),u=Zg(n,c);if(c.includes(n)||n.includes(c)){u<o&&(r=a,o=u);continue}if(n.length<3)continue;let l=Math.max(2,Math.floor(a.length/3));u<=l&&u<s&&(i=a,s=u)}return r??i}var ty=new Set(["none","standard","symbols"]),ny={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"searchText",keywords:"searchText",language:"langType"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:{field:"minify",map:e=>{if(e===!0)return"standard";if(e===!1)return"none";if(typeof e=="string"&&ty.has(e))return e}}},ghSearchPullRequests:{merged:{field:"state",map:e=>e===!0?"merged":void 0}},ghSearchCommits:{filePath:"path"},localFindFiles:{maxResults:"limit"}};function ry(e,t){let n=ny[e];if(!n)return t;let r;for(let[o,i]of Object.entries(n)){if(!(o in t))continue;let s=typeof i=="string"?i:i.field;if(s in t){r??={...t},delete r[o];continue}let a=typeof i=="string"?t[o]:i.map(t[o]);a!==void 0&&(r??={...t},r[s]=a,delete r[o])}return r??t}function oy(e,t,n,r={}){if(!rt(t))throw new Fe("Tool input must be a JSON object or an array of objects.");let o=ry(e,t),i=new Set([...er(e).filter(c=>!c.name.includes(".")).map(c=>c.name),...Zn]),s={},a=[];for(let[c,u]of Object.entries(o)){if(i.has(c)){s[c]=u;continue}a.push(c)}if(a.length>0&&i.size>0&&(r.onUnknownFields?.(a,n),r.rejectUnknownFields===!0)){let c=a.map(u=>{let l=ey(u,i);return l?`'${u}' \u2192 did you mean '${l}'?`:""}).filter(Boolean);throw new Fe(`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}function mt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function nn(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 io(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var tr=new Map,iy=300*1e3;function sy(e){let t=mt(e),n=tr.get(t);return!n||Date.now()-n.cachedAt>=iy?!1:n.credentials?!nn(n.credentials):!0}function Wi(e){e?tr.delete(mt(e)):tr.clear()}function Yu(e){let t=mt(e);if(sy(t))return tr.get(t).credentials}function Xu(e,t){let n=mt(e);tr.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as Zu,readFileSync as el,writeFileSync as tl,unlinkSync as Sk,statSync as fy,chmodSync as hy}from"node:fs";import{createCipheriv as gy,createDecipheriv as yy,randomBytes as nl}from"node:crypto";import{existsSync as ay,mkdirSync as cy}from"node:fs";import{join as He}from"node:path";import{getOctocodeHome as uy}from"@octocodeai/config";var ly=448;function dy(){return uy(process.env)}function rn(){return _e}var _e=dy(),ot={home:_e,config:He(_e,".octocoderc"),credentials:He(_e,"credentials.json"),key:He(_e,".key"),session:He(_e,"session.json"),stats:He(_e,"stats.json"),tmp:He(_e,"tmp"),clone:He(_e,"tmp","clone"),tree:He(_e,"tmp","tree"),repos:He(_e,"tmp","clone"),cliConfig:He(_e,"config.json"),lspConfig:He(_e,"lsp-servers.json")};function qu(){ay(ot.home)||cy(ot.home,{recursive:!0,mode:ly})}import{z as ge}from"zod";var py=ge.object({token:ge.string(),tokenType:ge.literal("oauth"),scopes:ge.array(ge.string()).optional(),refreshToken:ge.string().optional(),expiresAt:ge.string().optional(),refreshTokenExpiresAt:ge.string().optional()}),my=ge.object({hostname:ge.string(),username:ge.string(),token:py,gitProtocol:ge.enum(["ssh","https"]),createdAt:ge.string(),updatedAt:ge.string()}),Ju=ge.object({version:ge.number(),credentials:ge.record(ge.string(),my)});var rl=ot.home,nr=ot.credentials,vt=ot.key,ol="aes-256-gcm",Ry=16;function Dt(){qu()}function il(){if(Dt(),Zu(vt))return fy(vt).mode&511&63&&hy(vt,384),Buffer.from(el(vt,"utf8"),"hex");let e=nl(32);return tl(vt,e.toString("hex"),{mode:384}),e}function Vi(e){let t=il(),n=nl(Ry),r=gy(ol,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 Ki(e){let t=il(),[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=yy(ol,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function so(){if(Dt(),!Zu(nr))return{version:1,credentials:{}};try{let e=el(nr,"utf8"),t=Ki(e),n=JSON.parse(t),r=Ju.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function sl(e){Dt();let t=Vi(JSON.stringify(e,null,2));tl(nr,t,{mode:384})}import{refreshToken as Sy}from"@octokit/oauth-methods";import{request as by}from"@octokit/request";var rr="178c6fc778ccc68e1d6a",on="github.com";function Cy(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 Py(e){return e==="github.com"||e===on?"https://api.github.com":`https://${e}/api/v3`}async function al(e,t=on,n=rr){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(io(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Sy({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:by.defaults({baseUrl:Py(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?Cy(o.message):"Token refresh failed"}}}async function cl(e,t=on,n=rr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!nn(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await al(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as Ty}from"@octocodeai/config";import{execFile as xy}from"child_process";var wy=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Yi(e){return new Promise(t=>{let n=["auth","token"];e&&n.push("--hostname",e);let r=process.env.PATH??"",o=new Set(r.split(":")),i=wy.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;xy("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Xi=null;function ul(e){Xi=e}function Ey(){if(!Xi)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Xi}async function ao(e){let t=e?.hostname??on,n=e?.clientId??rr,r=e?.getGhCliToken??Yi,o=Ty();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await Ey().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}async function ll(e){let t=mt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=so();return r.credentials[t]=n,sl(r),Wi(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function qi(e="github.com",t){let n=mt(e);if(!t?.bypassCache){let i=Yu(n);if(i!==void 0)return i}let o=so().credentials[n]||null;return Xu(n,o),o}async function dl(e,t){let n=await qi(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await ll(n),!0):!1}async function pl(e,t){return cl({getCredentials:qi,updateToken:dl},e,t)}ul({getTokenWithRefresh:pl});import co from"node:os";import s_ from"node:path";var _y=co.platform()==="win32",Iy=co.platform()==="darwin",Oy=co.platform()==="linux",Fy=co.homedir();import{randomUUID as v_}from"node:crypto";import{existsSync as yl,readFileSync as Rl,writeFileSync as Gy,unlinkSync as R_,renameSync as Hy}from"node:fs";import{isStatsEnabled as Sl}from"@octocodeai/config";import{z}from"zod";var vy=z.object({rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),calls:z.number()}),Dy=z.object({hits:z.record(z.string(),z.number()).default({}),rateLimits:z.number().default(0)}),uo=z.record(z.string(),z.number()).default({}),My=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:uo,rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),charSavingsCalls:z.number(),githubCacheHits:z.number(),githubCacheRateLimits:z.number(),packageRegistryFailures:z.number().default(0),packageRegistryFailuresByRegistry:uo}),lo=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:uo,charsSavedByTool:z.record(z.string(),vy).default({}),githubCacheHits:Dy.default({hits:{},rateLimits:0}),packageRegistryFailures:uo,totalUsage:My.optional()}),ml=z.object({version:z.literal(1),sessionId:z.string(),createdAt:z.string(),lastActiveAt:z.string(),stats:lo.optional()}),fl=z.object({version:z.literal(1),stats:lo});function hl(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Ny(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:hl(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:hl(o),packageRegistryFailuresByRegistry:o}}function ft(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Ny(t)}}function sn(){return ft({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var or=ot.session,ir=ot.stats;function gl(e,t){let n=`${e}.tmp`;Gy(n,JSON.stringify(t,null,2),{mode:384}),Hy(n,e)}function By(e){let t=JSON.parse(e),n=fl.safeParse(t);if(n.success)return ft(n.data.stats);let r=lo.safeParse(t);return r.success?ft(r.data):null}function Uy(){if(!yl(ir))return sn();try{let e=Rl(ir,"utf8");return By(e)??sn()}catch{return sn()}}function Ji(e){Dt(),Sl()&&gl(ir,{version:e.version,stats:ft(e.stats)});let{stats:t,...n}=e;gl(or,n)}function bl(){if(!yl(or))return null;try{let e=Rl(or,"utf8"),t=JSON.parse(e),n=ml.safeParse(t);return n.success?{...n.data,stats:Sl()?Uy():sn()}:null}catch{return null}}var Qy=6e4,ht=null,sr=!1,Zi=null,Cl=!1,Pl=null,xl=null,wl=null,es=!1;function $y(){Cl||(Cl=!0,Pl=()=>{po()},xl=()=>{po()},wl=()=>{po()},process.on("exit",Pl),process.on("SIGINT",xl),process.on("SIGTERM",wl))}function jy(){Zi||(Zi=setInterval(()=>{sr&&ht&&(Ji(ht),sr=!1)},Qy),Zi.unref())}function Tl(){if(ht)return ht;let e=bl();return e&&(ht=e),e}function El(e){ht=e,sr=!0,$y(),jy()}function po(){if(!es&&sr&&ht){es=!0;try{Ji(ht),sr=!1}catch{}finally{es=!1}}}function zy(e){return ft(e)}function Wy(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 Ll(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 Vy(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 gt(e){let t=Tl();if(!t)return{success:!1,session:null};let n=zy(t.stats),r=ft({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Ll(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Wy(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:Vy(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Ll(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return El(o),{success:!0,session:o}}function ts(e=1){return gt({rateLimits:e})}function ns(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return gt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function rs(e,t=1){return gt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function os(e=1){return gt({githubCacheHits:{hits:{},rateLimits:e}})}import{z as ue}from"zod";var Ky=ue.looseObject({$schema:ue.string().optional(),version:ue.number().int().optional(),github:ue.record(ue.string(),ue.unknown()).optional(),local:ue.record(ue.string(),ue.unknown()).optional(),tools:ue.record(ue.string(),ue.unknown()).optional(),network:ue.record(ue.string(),ue.unknown()).optional(),lsp:ue.record(ue.string(),ue.unknown()).optional(),output:ue.record(ue.string(),ue.unknown()).optional()});import{existsSync as Yy,readdirSync as Xy,lstatSync as qy}from"node:fs";import{join as Jy}from"node:path";function mo(e){if(!Yy(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Xy(r)}catch{continue}for(let i of o){let s=Jy(r,i);try{let a=qy(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}import{getConfigSync as Al,invalidateConfigCache as xI}from"@octocodeai/config";var Mt="18.1.2";var is={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},ar={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"}},cr={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})`}},eR={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"}},yt={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}`}},Rt={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"}},Ce={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}`}},tR={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}`}},ur={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Query ${e+1} timed out after ${t}ms \u2014 retry it alone, with tighter caps (maxFiles/maxMatchesPerFile/itemsPerPage) if it was large`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},nR={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}`}},SI={...is,...ar,...cr,...eR,...yt,...Rt,...Ce,...tR,...ur,...nR};import{maskSensitiveData as rR}from"@octocodeai/octocode-engine/mask";var dr=null,lr=null,oR=ao;var iR=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function kl(){try{let e=await oR({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:iR.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function _l(){if(dr!==null)return;if(lr!==null)return lr;let e=(async()=>{let t=Al(),n=await kl();dr={version:Mt,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}})();lr=e;try{await e}catch(t){throw lr===e&&(dr=null,lr=null),t}}function fo(){if(!dr){let e=rR(is.NOT_INITIALIZED.message);throw new Error(e)}return dr}async function ss(){return(await kl()).token}function Il(){let e=fo();return e.enableLocal&&e.enableClone}function as(){return"github"}function cs(){let e=Al().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{ContentSanitizer as $R}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as sR}from"node:module";var aR=sR(import.meta.url),Ol="@octocodeai/octocode-engine",cR=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??aR(Ol),ho,uR=cR,us=class extends Error{constructor(n){super(`Failed to load native dependency ${Ol}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function J(){if(ho)return ho;try{return ho=uR(),ho}catch(e){throw new us(e)}}var F={applyContentViewMinification(e,t){return J().applyContentViewMinification(e,t)},applyMinification(e,t){return J().applyMinification(e,t)},minifyContent(e,t){return J().minifyContent(e,t)},minifyContentSync(e,t){return J().minifyContentSync(e,t)},minifyContentResult(e,t){return J().minifyContentResult(e,t)},minifyMarkdownCore(e){return J().minifyMarkdownCore(e)},extractSignatures(e,t){return J().extractSignatures(e,t)},extractJsSymbols(e,t){return J().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return J().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return J().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return J().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return J().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return J().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return J().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return J().structuralSearchFiles(e)},structuralSearchFilesDetailed(e){return J().structuralSearchFilesDetailed(e)},getSupportedStructuralExtensions(){return J().getSupportedStructuralExtensions()},validateRipgrepPattern(e,t,n){return J().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return J().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return J().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return J().parseRipgrepJson(e,t)},searchRipgrep(e){return J().searchRipgrep(e)},queryFileSystem(e){return J().queryFileSystem(e)},extractMatchingLines(e,t,n){return J().extractMatchingLines(e,t,n)},filterPatch(e,t){return J().filterPatch(e,t)},computeLineDiff(e,t){return J().computeLineDiff(e,t)},charToByteOffset(e,t){return J().charToByteOffset(e,t)},byteToCharOffset(e,t){return J().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return J().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return J().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return J().SIGNATURES_ONLY_HINT}};import{Octokit as lR}from"octokit";import{throttling as dR}from"@octokit/plugin-throttling";import{createHash as pR}from"crypto";function St(e){(e.provider?gt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):ts(1)).session&&e.provider==="github"&&os(1)}function Fl(e){gt({packageRegistryFailures:{[e]:1}})}function Gl(e){return pR("sha256").update(e).digest("hex").substring(0,16)}async function pe(e){let t=e?.token??await ss(),n=t?Gl(t):"anon",r=fo().githubApiUrl||"https://api.github.com";try{let o=new URL(r).host;if(o&&o!=="api.github.com")return`${n}@${o}`}catch{}return n}var mR=lR.plugin(dR),fR=300*1e3,ls=50,hR=60*1e3;function Hl(e){return Date.now()-e.createdAt>fR}var it=new Map,pr=null;function Bl(){for(let[e,t]of it.entries())Hl(t)&&it.delete(e);if(it.size>ls){let e=it.size-ls,t=0;for(let[n]of it){if(t>=e)break;it.delete(n),t++}}}function gR(){pr||(pr=setInterval(Bl,hR),typeof pr=="object"&&"unref"in pr&&pr.unref())}var vl=3,Dl=60;function Ml(e,t,n){St({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var yR=()=>({onRateLimit:(e,t,n,r)=>(Ml("primary",e,t),r<vl&&e<Dl),onSecondaryRateLimit:(e,t,n,r)=>(Ml("secondary",e,t),r<vl&&e<Dl)});function RR(e){let t=fo(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Mt}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:yR(),log:r,...e&&{auth:e}};return new mR(o)}async function U(e){gR();let t=e?.token??await ss(),n=t?Gl(t):"ANONYMOUS",r=it.get(n);if(r&&!Hl(r))return r.client;it.size>=ls&&Bl();let o=RR(t??void 0);return it.set(n,{client:o,createdAt:Date.now()}),o}var SR=200,mr=new Map;async function Pe(e,t,n){let r=`${e}/${t}`,o=mr.get(r);if(o)return o;let i=await U(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Nl(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}),Nl(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 Nl(e,t){if(mr.size>=SR){let n=mr.keys().next().value;n!==void 0&&mr.delete(n)}mr.set(e,t)}import{RequestError as Ql}from"octokit";var j={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"},me={[j.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."},[j.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."},[j.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},[j.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)."},[j.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."},[j.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."},[j.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."},[j.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."},[j.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."},[j.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Ul={401:j.AUTH_REQUIRED,403:j.FORBIDDEN_PERMISSIONS,404:j.NOT_FOUND,422:j.INVALID_REQUEST,502:j.SERVER_UNAVAILABLE,503:j.SERVER_UNAVAILABLE,504:j.SERVER_UNAVAILABLE},ds={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},ps={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},go={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var bR=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function We(e){if(!(e instanceof Ql)||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 bR.some(o=>r.includes(o))})}function W(e){return e instanceof Ql?CR(e):e instanceof Error?kR(e):{error:typeof e=="string"?e:me[j.UNKNOWN].message,type:"unknown"}}function CR(e){let{status:t,message:n,response:r}=e;if(t===403)return xR(n,r);if(t===429)return PR(n,r);let o=Ul[t];return o?AR(o,t):an(j.UNKNOWN,{error:n||me[j.UNKNOWN].message,status:t})}function ms(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function PR(e,t){let n=t?.headers,r=ms(n,"retry-after"),o=ms(n,"x-ratelimit-reset"),i=ms(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+go.RESET_BUFFER_SECONDS,0):void 0);return St({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),an(j.RATE_LIMIT_PRIMARY,{error:e||me[j.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:me[j.RATE_LIMIT_PRIMARY].suggestion})}function xR(e,t){let n=t?.headers;if(ps.SECONDARY.test(e))return wR(n);let r=n?.["x-ratelimit-remaining"],o=LR(t);return r!==void 0&&String(r)==="0"||o?TR(n):ER(n)}function wR(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?go.SECONDARY_FALLBACK_SECONDS:t;return St({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),an(j.RATE_LIMIT_SECONDARY,{error:me[j.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:me[j.RATE_LIMIT_SECONDARY].suggestion})}function TR(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)+go.RESET_BUFFER_SECONDS,0):void 0,i=r?me[j.RATE_LIMIT_PRIMARY].messageWithTime(r,o):me[j.RATE_LIMIT_PRIMARY].messageWithoutTime;return St({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),an(j.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:me[j.RATE_LIMIT_PRIMARY].suggestion})}function ER(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=me[j.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=_R(String(t),String(n))),an(j.FORBIDDEN_PERMISSIONS,{error:me[j.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function LR(e){return e?.data?.errors?.some(n=>n.type===ps.GRAPHQL_TYPE)??!1}function AR(e,t){let n=me[e];return an(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function kR(e){return ds.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:me[j.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:me[j.NETWORK_CONNECTION_FAILED].suggestion}:ds.TIMEOUT.some(t=>e.message.includes(t))?{error:me[j.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:me[j.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function an(e,t){return{type:"http",...t}}function _R(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?me[j.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):me[j.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function $l(e){return`user:${e}`}var IR=/[@/]/,OR=/^[A-Za-z0-9_-]+$/;function fs(e){return e.startsWith('"')||OR.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var st=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($l(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=IR.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}build(){return this.queryParts.join(" ").trim()}};var FR=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,hs=class extends st{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(fs))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(FR):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}},gs=class extends st{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(fs)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}};function ys(e){return new hs().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function Rs(e){return new gs().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var Ss=class extends st{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function bs(e){return new Ss().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Cs(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Ps=class extends st{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:issue"),this}addStateFilters(t){return(t.state==="open"||t.state==="closed")&&this.addSimpleFilter(t.state,"is"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this}addNegativeFilters(t){return t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),this}};function xs(e){return new Ps().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function ws(e){return typeof e.query=="string"&&e.query.trim().length>0||e.author!==void 0||e.assignee!==void 0||e.label!==void 0&&(Array.isArray(e.label),e.label.length>0)||e.mentions!==void 0||e.commenter!==void 0||e.reactions!==void 0||e.comments!==void 0||e.milestone!==void 0||e.locked!==void 0||e.visibility!==void 0||e.created!==void 0||e.updated!==void 0||e.closed!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import vR from"crypto";var DR="v2",MR=new Set([]);function NR(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(MR.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function se(e,t,n){let r=Ts(NR(t)),o=n?`${n}:${r}`:r,i=vR.createHash("sha256").update(o).digest("hex");return`${DR}-${e}:${i}`}function Ts(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=>Ts(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Ts(i,t)}`}).join(",")}}`)}import GR from"node-cache";var HR=300*1e3,Be=new GR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ve={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},jl={"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},Ue=new Map;function BR(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function UR(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function fr(e){let t=BR(e);if(!(!t||!UR(t)))try{rs(t,1)}catch{}}function yo(){let e=Date.now();for(let[t,n]of Ue.entries())e-n.startedAt>HR&&Ue.delete(t)}function hr(e){return jl[e]||jl.default}function gr(e,t,n){try{return Be.set(e,t,n),ve.sets++,ve.totalKeys=Be.keys().length,!0}catch{try{let r=Be.keys();for(let o of r)Be.get(o);return Be.set(e,t,n),ve.sets++,ve.totalKeys=Be.keys().length,!0}catch{return!1}}}async function fe(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Be.get(e);if(i!==void 0)return ve.hits++,fr(e),i}catch{}yo();let r=Ue.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ve.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=hr(u)}gr(e,i,a)}return i}finally{Ue.delete(e)}})();return Ue.set(e,{promise:o,startedAt:Date.now()}),o}import QR from"node-cache";var Es=new QR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function Ro(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Be.get(e);if(i!==void 0)return ve.hits++,fr(e),i}catch{}yo();let r=Ue.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:Es.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ve.hits++,fr(e);let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=hr(l)}return gr(e,i.data,c),i.data}if(n.forceRefresh||ve.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=hr(l)}gr(e,s.value,c),Es.set(e,{data:s.value,etag:s.etag})}return s.value}finally{Ue.delete(e)}})();return Ue.set(e,{promise:o,startedAt:Date.now()}),o}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as xO,DISCOVERY_IGNORED_FILE_NAMES as wO,DISCOVERY_IGNORED_FOLDER_NAMES as TO,getDiscoveryExtension as zl,shouldIgnoreDiscoveryDir as yr,shouldIgnoreDiscoveryFile as cn}from"@octocodeai/octocode-engine/security";var Wl=Symbol.for("octocode.rawResponseChars");function N(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Vl(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function Q(e,t){let n=typeof t=="number"?Vl(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,Wl,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function te(e){if(!(typeof e!="object"||e===null))return Vl(e[Wl])}function un(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 Kl(e){let t=un(e),n=Number(t["x-ratelimit-remaining"]),r=Number(t["x-ratelimit-limit"]),o=Number(t["x-ratelimit-reset"]);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0||n>Math.max(3,r*.15))return;let i=Number.isFinite(o)?Math.max(0,Math.round((o*1e3-Date.now())/1e3)):void 0;return`GitHub rate limit low: ${n}/${r} remaining${i!==void 0?` (resets in ~${i}s)`:""} \u2014 pace or narrow further requests.`}function ln(e){let t=un(e),n=t.etag||t.ETag||t.Etag||Object.entries(t).find(([r])=>r.toLowerCase()==="etag")?.[1];return n&&n.length>0?n:void 0}function Yl(e,t,n){let r=[],o=0;for(let[i,s]of t){let a=e.slice(i,s);if(!a)continue;let c=n.indexOf(a,o);c===-1&&(c=n.indexOf(a),c===-1)||(r.push([c,c+a.length]),o=c+a.length)}return r}var Xl=30;async function ql(e,t,n){let r=await pe(t),o=se("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await fe(o,async()=>await jR(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function jR(e,t){try{let n=await U(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(h=>h&&h.trim()).length===0)return{error:Ce.QUERY_EMPTY.message,type:"http",status:400};let r=ys(e);if(!r.trim())return{error:Ce.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Xl,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 zR(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,d=Math.min(l,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),f=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...u?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:f,...f?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:un(a.headers),rawResponseChars:N(a.data)}}catch(n){if(We(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Xl,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 W(n)}}async function zR(e,t){let n=WR(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!cn(p.path)),c=0,u=0,l=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],g=await Promise.allSettled((p.text_matches||[]).map(async C=>{let x=C.fragment,T=$R.sanitizeContent(x||"",p.path);x=T.content,T.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${p.path}: ${k}`));try{let k=await F.minifyContent(x||"",p.path);x=k.content,k.failed?o=!0:k.type!=="failed"&&(f.push(k.type),i.push(k.type))}catch{o=!0}let L=C.matches?.flatMap(k=>Array.isArray(k.indices)&&k.indices.length>=2?[[k.indices[0],k.indices[1]]]:[])||[];return{context:x||"",positions:Yl(C.fragment||"",L,x||"")}})),R=g.filter(C=>C.status==="fulfilled").map(C=>C.value),h=g.filter(C=>C.status==="rejected").length;h>0&&(u+=h);let y=p,S=Array.from(new Set(f));return{path:p.path,matches:R,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...y.last_modified_at&&{lastModifiedAt:y.last_modified_at},...S.length>0&&{minificationType:S.join(",")}}})),d=l.filter(p=>p.status==="fulfilled").map(p=>p.value);c=l.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`),u>0&&r.add(`${u} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function WR(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 Jl=30;function Zl(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 ed(e,t,n){let r=await pe(t),o=e,i=se("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,repo:o.repo,stars:e.stars,updated:e.updated,language:o.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page,archived:o.archived,visibility:o.visibility,forks:o.forks,license:o.license,goodFirstIssues:o.goodFirstIssues,auth:r},n);return await fe(i,async()=>await KR(e,t),{shouldCache:a=>"data"in a&&!a.error})}async function VR(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 W(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 W(g)}}let a=i.map(p=>{let g=p.full_name.split("/"),R=g[0]||"",h=g[1]||"";return{owner:R,repo:h,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},...Zl(p)}}),c=a.length,u=c===n,l=(r-1)*n+c,d=s??l+(u?1:0),m=s!==void 0||!u?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:u?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:l,totalMatchesKind:m,hasMore:u,...u?{nextPage:r+1}:{}}},status:200,rawResponseChars:N(i)}}async function KR(e,t){try{let n=await U(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 VR({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=Rs(e);if(!i.trim())return{error:Ce.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Jl,100),a=e.page||1,c={q:i,per_page:s,page:a},u=["stars","forks","help-wanted-issues","updated"];e.sort&&u.includes(e.sort)&&(c.sort=e.sort);let l=await n.rest.search.repos(c),d=l.data.items.map(y=>{let C=y.full_name.split("/"),x=C[0]||"",T=C[1]||"";return{owner:x,repo:T,defaultBranch:y.default_branch,stars:y.stargazers_count||0,description:y.description?y.description:"No description",url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at,pushedAt:y.pushed_at,visibility:y.visibility,...y.topics&&y.topics.length>0&&{topics:y.topics},...y.forks_count&&y.forks_count>0&&{forksCount:y.forks_count},...y.open_issues_count&&y.open_issues_count>0&&{openIssuesCount:y.open_issues_count},...y.language&&{language:y.language},...Zl(y)}}),m=l.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,f)),R=g<f,h=Math.min(p,f*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:h,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:R,...R?{nextPage:g+1}:{}}},status:200,headers:un(l.headers),rawResponseChars:N(l.data)}}catch(n){if(We(n)){let r=Math.min(e.limit||Jl,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 W(n)}}function Ie(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function he(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 YR(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 at(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:YR(e)}}function So(e){return XR(e)?at({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 XR(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||qR(n)}function qR(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function Rr(e){let t=typeof e?.totalMatchesCapped=="boolean"?e.totalMatchesCapped:typeof e?.reportedTotalMatches=="number"&&typeof e?.reachableTotalMatches=="number"?e.reportedTotalMatches>e.reachableTotalMatches:void 0;return{...typeof t=="boolean"?{totalMatchesCapped:t}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function JR(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,...Rr(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function ZR(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,...Rr(e.pagination)},nonExistentScope:e.nonExistentScope}}async function td(e,t,n=he){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 ql(s,t);return Ie(a)?at(a):a.data?{data:JR(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function nd(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 ed(n,t);return"error"in r?So(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:ZR(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??N(r.data)}}import{RequestError as Fs}from"octokit";import{completeMetadata as Ls}from"@octocodeai/octocode-core";var P=new Proxy({},{get(e,t){return Ls.toolNames[t]},ownKeys(){return Object.keys(Ls.toolNames)},getOwnPropertyDescriptor(e,t){let n=Ls.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as tS}from"@octocodeai/octocode-core";var As=new Proxy({},{get(e,t){return tS.tools[t]?.description??""}});import{completeMetadata as nS}from"@octocodeai/octocode-core";function ks(e){return Object.prototype.hasOwnProperty.call(nS.tools,e)}import{completeMetadata as rS}from"@octocodeai/octocode-core";function _s(){return rS.baseSchema}var oS=new Proxy({},{get(e,t){return _s()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(_s())]))},getOwnPropertyDescriptor(e,t){let n=_s();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});function Is(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 Os(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,u=[],l=c.find(p=>p.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>u.push(p.path)),u.length===0&&d.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(f=>u.push(f.path)),Array.from(new Set(u)).slice(0,3)}catch{return[]}}async function iS(e,t,n,r,o,i,s,a){let c=await Pe(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let l=W(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 Os(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Is(i,m)]),{...l,...d&&{scopesSuggestion:d}}}async function sS(e,t,n,r,o,i){let s=W(t),a=await Os(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Is(o,a)]),s}async function rd(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:yt.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:yt.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:yt.DECODE_FAILED.message,type:"unknown",status:422}}}async function od(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"?rd(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return W(i)}}async function aS(e,t,n,r,o,i){try{let s=r.split("/").slice(0,-1).join("/"),a=r.split("/").pop();if(!a)return{error:`Cannot determine file name from path: ${r}`,type:"unknown",status:400};let c=o||await Pe(t,n,i).catch(()=>"HEAD"),u=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(u.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let l=u.data.find(m=>m.name===a&&m.type==="file");if(!l)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await od(e,t,n,l.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 W(s)}}async function Sr(e,t,n={}){try{let r=await U(t),{owner:o,repo:i,path:s,branch:a}=e,c={owner:o,repo:i,path:s,...a&&{ref:a},...n.ifNoneMatch?{headers:{"If-None-Match":n.ifNoneMatch}}:{}},u,l=a;try{u=await r.rest.repos.getContent(c)}catch(p){if(p instanceof Fs&&p.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(p instanceof Fs&&p.status===404)if(a){let f=await iS(r,p,c,o,i,s,a,t);if("result"in f)u=f.result,l=f.actualBranch;else return f}else return await sS(r,p,o,i,s,a);else{if(p instanceof Fs&&p.status===413)return await aS(r,o,i,s,a||l,t);throw p}}let d=u.data,m=ln(u.headers);if(Array.isArray(d))return{error:yt.PATH_IS_DIRECTORY.message(P.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in d&&d.type==="file"){let p=typeof d.content=="string"?d.content:"",f=d.size??0,g;if(p.length>0)g=await rd(p,s);else if(f>0&&"sha"in d&&typeof d.sha=="string"&&d.sha)g=await od(r,o,i,d.sha,s);else return{error:yt.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!l&&!a)try{l=await Pe(o,i,t)}catch{}return{data:{rawContent:g.data,branch:l||void 0,resolvedRef:l||a||"HEAD"},status:200,rawResponseChars:N(d),...m?{etag:m}:{}}}return{error:yt.UNSUPPORTED_TYPE.message(d.type),type:"unknown",status:415}}catch(r){return W(r)}}import{ContentSanitizer as Hs}from"@octocodeai/octocode-engine/contentSanitizer";function bo(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Ve(e){return bo(e).length}function Co(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Invalid regex pattern: ${l}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
|
|
10
|
+
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=F.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(u=>({start:u.start,end:u.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(u=>u)}}var cS=/\.(?:md|markdown|mdx)$/i;function uS(e){return cS.test(e.split(/[?#]/,1)[0]??e)}function id(e,t){return uS(t)?dS(lS(e)):null}function Po(e,t){let n=id(e,t);if(n===null||n.length===0)return null;let r=[];return ad(n,r),r.join(`
|
|
11
|
+
`)}function sd(e,t){let n=id(e,t);return n===null?null:n.map(cd)}function lS(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let u=s[1][0],l=s[1].length;r?r.marker===u&&l>=r.length&&(r=void 0):r={marker:u,length:l};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function dS(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 ad(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}`),ad(n.children,t)}}function cd(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(cd)}}import{getConfigSync as pS,DEFAULT_OUTPUT_CONFIG as mS}from"@octocodeai/config";function Nt(){try{return pS().output.pagination.defaultCharLength}catch{return mS.pagination.defaultCharLength}}function vs(e,t){return F.byteToCharOffset(e,t)}function ud(e,t){return F.charToByteOffset(e,t)}function ld(e){return F.charToByteOffset(e,e.length)}function Ds(e,t,n,r){return F.sliceContent(e,t,n,r)}function xo(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=ld(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,u,l,d,m,p,f,g;if(o==="bytes"){let R=Math.min(t,s),h=Math.min(R+n,s);d=vs(e,R),m=vs(e,h),m<i&&ud(e,m)<h&&(m+=1);let y=Ds(e,d,m-d);c=y.text,d=y.charOffset,m=y.charOffset+y.charLength,u=y.byteOffset,l=y.byteOffset+y.byteLength,p=l<s;let S=r.actualOffset??R;f=Math.floor(S/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let R=Ds(e,t,n);c=R.text,d=R.charOffset,m=R.charOffset+R.charLength,u=R.byteOffset,l=R.byteOffset+R.byteLength,p=m<i;let h=r.actualOffset??d;f=Math.floor(h/a)+1,g=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:u,byteLength:l-u,totalBytes:s,nextByteOffset:p?l:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:g}}function Ms(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 fS=8e3,hS="__octocode_generic__.unknown";function gS(e){return e&&e.trim().length>0?e:hS}async function dd(e,t){return(await F.getSemanticBoundaryOffsets(e,gS(t))).filter(r=>Number.isInteger(r)&&r>=0&&r<=e.length)}function yS(e,t){let n=e.indexOf(`
|
|
12
|
+
`,t);return n===-1?void 0:n+1}function wo(e){let t=e.trimEnd().split(`
|
|
13
|
+
`).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}async function To(e,t,n){let r=yS(e,Math.max(0,t));return r===void 0?void 0:(await dd(e,n)).find(i=>i>=r&&i>t)}async function Eo(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 dd(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(l=>l>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=fS?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function SS(){let e=Nt();return Math.min(e,8e3)}async function Ns(e,t,n){let r=e.content??"",o=n??SS();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=await Eo(r,t,o,i),c=xo(r,t,s,{pageSize:o}),u;if(c.hasMore&&a==="char-limit"&&wo(c.paginatedContent)){let l=c.charOffset+c.charLength;u=await To(r,l,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...u!==void 0&&{nextBlockChar:u}}}}async function Gs(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}function br(e,t){return{sourceChars:e,sourceBytes:t}}async function pd(e,t,n,r,o,i,s,a,c=5,u,l,d,m="standard"){let p=e.length,f=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",R=g?"standard":"none",h;if(m==="symbols"){let I=F.extractSignatures(e,o);if(I===null){let B=Po(e,o);if(B!==null){let Z=Hs.sanitizeContent(B,o),v=[F.SIGNATURES_ONLY_HINT];return Z.hasSecrets&&v.push(`Secrets detected and redacted: ${Z.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Z.content,contentView:"symbols",branch:r,totalLines:Ve(e),...br(p,f),isPartial:!1,signaturesExtracted:!0,hints:v}}h=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(I!==null){let B=Hs.sanitizeContent(I,o),Z=F.applyContentViewMinification(B.content,o),v=[F.SIGNATURES_ONLY_HINT];return u&&v.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),B.hasSecrets&&v.push(`Secrets detected and redacted: ${B.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Z,contentView:"symbols",branch:r,totalLines:Ve(e),...br(p,f),isPartial:!1,signaturesExtracted:!0,hints:v}}}let y=new Set,S=e,C=S.split(`
|
|
14
|
+
`),x=Ve(S),T=e,L,k,w=!1,b,A;if(i)T=e;else if(u){let I=d===!0,B;try{B=Co(C,u,c,l??!1,I)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:x,...br(p,f),matchNotFound:!0,searchedFor:u,hints:[`Invalid regex "${u}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(B.matchCount===0){let ie=l?[`Regex "${u}" matched no lines. Verify the pattern, check flags (case-${I?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${u}" not found in file${I?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:x,...br(p,f),matchNotFound:!0,searchedFor:u,hints:ie}}T=B.lines.join(`
|
|
15
|
+
`);let Z=B.matchRanges[0],v=B.matchRanges[B.matchRanges.length-1];s=Z.start,a=v.end,L=Z.start,k=v.end,w=!0,b=B.matchRanges,A=B.matchingLines;let X=B.matchingLines.slice(0,5).join(", "),ae=B.matchingLines.length>5?` and ${B.matchingLines.length-5} more`:"";y.add(B.matchCount>1?`Found ${B.matchCount} occurrences of "${u}" on lines ${X}${ae} \u2014 all shown as ${B.matchRanges.length} slice${B.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${u}" on line ${B.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let I=s||1,B=a||x;if(I<1||I>x)T=e,y.add(`Requested startLine ${I} is out of range for this ${x}-line file \u2014 returning the full file instead of a range.`);else if(B<I)T=e,y.add(`Requested range startLine=${I}, endLine=${B} is invalid (endLine before startLine) \u2014 returning the full file instead of a range.`);else{let Z=Math.max(1,I),v=Math.min(x,B),X=C.slice(Z-1,v);L=Z,k=v,w=!0,T=X.join(`
|
|
16
|
+
`),B>x&&y.add(`Requested endLine ${B} adjusted to ${x} (file end)`)}}let M=Hs.sanitizeContent(T,o);if(T=g?F.applyContentViewMinification(M.content,o):M.content,M.hasSecrets&&y.add(`Secrets detected and redacted: ${M.secretsDetected.join(", ")}`),M.warnings.length>0&&M.warnings.forEach(I=>y.add(I)),x>2e3&&m!=="symbols"&&!u&&!s&&!a&&!i){let I=Math.max(1,x-200);y.add(`Large file (${x} lines) \u2014 minify:"symbols" for an export index, or startLine=${I} for the tail.`)}let H=Array.from(y);return{owner:t,repo:n,path:o,content:T,contentView:R,branch:r,totalLines:x,...br(p,f),...w&&{startLine:L,endLine:k,isPartial:w},...b&&{matchRanges:b},...A&&{matchedLines:A},...H.length>0&&{matchLocations:H},...(H.length>0||h)&&{warnings:[...h?[h]:[],...H]}}}async function md(e,t,n){let r=await pe(t),o=se("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,auth:r},n),i=await Ro(o,async({ifNoneMatch:g})=>{let R=await Sr(e,t,{ifNoneMatch:g}),{etag:h,notModified:y,...S}=R;return{value:S,etag:h,notModified:y}},{shouldCache:g=>"data"in g&&!g.error,forceRefresh:e.forceRefresh===!0});if(!("data"in i)||!i.data)return i;let s=i.data.branch||i.data.resolvedRef||e.branch||"",a=await pd(i.data.rawContent,e.owner,e.repo,s,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in a)return{error:a.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:c,...u}=a,l=e.charOffset??0,d=e.charLength,m=e.fullContent===!0&&l===0&&d===void 0,p=c||m?u:await Ns(u,l,d),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let g=await U(t),R=await fe(se("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0,auth:r},n),()=>Gs(g,e.owner,e.repo,e.path,e.branch),{shouldCache:h=>h!==null,forceRefresh:e.forceRefresh===!0});R&&(p.lastModified=R.lastModified,p.lastModifiedBy=R.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:i.rawResponseChars}}function bS(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,contentView:e.contentView,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,matchedLines:e.matchedLines,warnings:CS(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function CS(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 fd(e,t,n=he){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 md(i,t);if(Ie(s))return at(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:bS(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s.data),...a?.length?{hints:a}:{}}}import{ContentSanitizer as yd}from"@octocodeai/octocode-engine/contentSanitizer";var xS=2;function hd(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return F.filterPatch(e,r)}function gd(e){return e?F.filterPatch(e,{trimContext:!0,contextLines:xS}):""}function Bs(e){let t=yd.sanitizeContent(e.title??""),n=e.body?yd.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}var wS=Nt(),TS=Math.round(Nt()/4),Rd=3;function Sd(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 dn(e,t={}){let n=t.charOffset??0,r=t.charLength??wS,o=t.charLength??TS,i=typeof e.body=="string"?F.minifyMarkdownCore(e.body):e.body,s=Sd(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,g)=>{let R=f.commentType==="review_inline"?0:1,h=g.commentType==="review_inline"?0:1;return R-h}),c=a.filter(f=>f.commentType==="review_inline").length,u=a.length-c,l=t.includeFullCommentDetails?a:a.slice(0,Rd),d=l.map(f=>{let g=Sd(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:g.value??"",...g.pagination?{bodyPagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>l.length||d.some(f=>"bodyPagination"in f)),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 ${Rd} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??void 0,mergedAt:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(f=>({id:0,name:f,color:""}))}:{},headRef:e.head||"",...e.head_sha?{headSha:e.head_sha}:{},baseRef:e.base||"",...e.base_sha?{baseSha:e.base_sha}:{},body:s.value,...s.pagination?{bodyPagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{commentDetailsBreakdown:{inlineReview:c,discussion:u}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((f,g)=>f+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((f,g)=>f+g.deletions,0)||e.deletions||0,changedFiles:e.file_changes?.total_count||0,...e.file_changes&&{fileChanges:e.file_changes.files?.map(f=>({filename:f.filename,status:f.status,additions:f.additions,deletions:f.deletions,patch:f.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commitDetails:e.commits},...d.length>0&&{commentDetails:d,commentDetailsShown:d.length,commentDetailsTotal:a.length,...m?{commentDetailsPaginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{sanitizationWarnings:[...e._sanitization_warnings||[],...p]}}}function Cr(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 Pr(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?hd(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?gd(a.patch):a.patch}))}function pn(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function bd(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Lo(e){let t=bd(e);return t?t.discussion!==!1:!1}function Ao(e){let t=bd(e);return t?t.reviewInline!==!1:!1}function ko(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function _o(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Us(e){return e.prNumber!==void 0||e.reviewMode==="full"?!0:pn(e)||Lo(e)||Ao(e)||ko(e)||_o(e)}function Qs(e){return!!e.content?.comments?.includeBots}function Io(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()}import{ContentSanitizer as $s}from"@octocodeai/octocode-engine/contentSanitizer";var xS=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function Gt(e){let t=e.toLowerCase();return t.endsWith("[bot]")||xS.has(t)}async function Io(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=N(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Us(e,t,n,r){let o=await U(r),{items:i,rawResponseChars:s}=await Io(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return Q({total_count:i.length,files:i},s)}async function wS(e,t,n,r){let o=await U(r),{items:i,rawResponseChars:s}=await Io(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return Q(i,s)}async function TS(e,t,n,r){try{let i=await(await U(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return Q(i.data.files||[],i.data)}catch{return null}}var ES=5;async function LS(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 Qs(e,t,n,r,o){let i=await wS(e,t,n,o);if(!i)return null;let s=te(i)??0,a=[...i].sort((u,l)=>{let d=u.commit.author?.date?new Date(u.commit.author.date).getTime():0;return(l.commit.author?.date?new Date(l.commit.author.date).getTime():0)-d}),c=await LS(a,ES,async u=>{let l=await TS(e,t,u.sha,o),d=[];return l&&(s+=te(l)??0,d=Pr(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:d}});return Q(c,s)}async function js(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+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Gt(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=F.minifyMarkdownCore(ko(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:$s.sanitizeContent(f).content,createdAt:p.created_at??"",updatedAt:p.updated_at??"",commentType:"discussion"}}),m=[];return l>0&&m.push(`${l} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:Q(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:Q([],0)}}}async function zs(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Io(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return Q(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:$s.sanitizeContent(F.minifyMarkdownCore(ko(s.body??""))).content,submittedAt:s.submitted_at??void 0,commitId:s.commit_id??void 0})),i)}catch{return Q([],0)}}async function Ws(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+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Gt(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=F.minifyMarkdownCore(ko(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:$s.sanitizeContent(f).content,createdAt:p.created_at??"",updatedAt:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{inReplyToId:p.in_reply_to_id}:{}}}),m=[];return l>0&&m.push(`${l} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:Q(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:Q([],0)}}}async function Vs(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Gs(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&Hs(t))try{let{owner:u,repo:l}=Cr(t);if(u&&l){let d=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(d.data&&(s+=N(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,pn(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),pn(t))){let m=await Us(u,l,e.number);m&&(s+=te(m)??0,m.files=Pr(m.files,t),o.file_changes=m)}}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let a=Eo(t),c=Lo(t);if(a||c){let{owner:u,repo:l}=Cr(t);if(u&&l){let d=Bs(t),m=()=>Promise.resolve({comments:Q([],0)}),[{comments:p,note:f},{comments:g,note:R}]=await Promise.all([a?js(n,u,l,e.number,d):m(),c?Ws(n,u,l,e.number,d):m()]);o.comments=[...p,...g],s+=(te(p)??0)+(te(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}}if(_o(t))try{let{owner:u,repo:l}=Cr(t);if(u&&l){let d=await zs(n,u,l,e.number);s+=te(d)??0,o.reviews=d}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(Ao(t))try{let{owner:u,repo:l}=Cr(t);if(u&&l){let d=await Qs(u,l,e.number,t);d&&(s+=te(d)??0,o.commits=d)}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return Q(o,s)}async function xr(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Gs(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,pn(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),pn(t))try{let d=await Us(a,c,e.number,r);d&&(s+=te(d)??0,d.files=Pr(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 u=Eo(t),l=Lo(t);if(u||l){let d=Bs(t),m=()=>Promise.resolve({comments:Q([],0)}),[{comments:p,note:f},{comments:g,note:R}]=await Promise.all([u?js(n,a,c,e.number,d):m(),l?Ws(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(te(p)??0)+(te(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}if(_o(t))try{let d=await zs(n,a,c,e.number);s+=te(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(Ao(t))try{let d=await Qs(a,c,e.number,t,r);d&&(s+=te(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return Q(o,s)}function AS(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function Sd(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pullRequests:[],totalCount:0,error:Ce.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pullRequests:[],totalCount:0,error:Ce.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await U(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await xr(a,e,i,t);return{pullRequests:[dn(c,{includeFullBody:!0,includeFullCommentDetails:!0})],totalCount:1,rawResponseChars:N(s.data)+(te(c)??0)}}catch(i){let s=W(i);return AS(s,Ce.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}function Ks(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Ys(e){let t=Math.min(e.limit||30,100);return{pullRequests:[],totalCount:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function bd(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 xr(m,t,e))),c=a.reduce((m,p)=>m+(te(p)??0),0),u=a.map(m=>dn(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),l=s.data.length===o,d=(i-1)*o+u.length;return{pullRequests:u,totalCount:u.length,pagination:{currentPage:i,totalPages:l?i+1:i,perPage:o,totalMatches:d+(l?1:0),reachableTotalMatches:d,totalMatchesKind:l?"lowerBound":"exact",hasMore:l,...l?{nextPage:i+1}:{}},rawResponseChars:N(s.data)+c}}catch(n){if(We(n))return Ys(t);let r=W(n);return Ks(r,Ce.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}async function _S(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 kS(e,t,n="anon"){return se("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,project:e.project,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function Cd(e,t,n){let r=await pe(t),o=kS(e,n,r);return await fe(o,async()=>await IS(e,t,n),{shouldCache:s=>!s.error})}async function IS(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Sd(e,t);let r=await U(t);if(!Ss(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await bd(r,e);let i=await _S(r,e),s=Rs(i);if(!s)return{pullRequests:[],totalCount:0,error:Ce.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),u=i.page||1,l=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:u}),m=d.data.items?.filter(T=>!!T.pull_request)||[],p=await Promise.all(m.map(async T=>await Vs(T,i,r))),f=p.reduce((T,L)=>T+(te(L)??0),0),g=p.map(T=>dn(T,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),R=d.data.total_count,h=Math.min(R,1e3),y=Math.min(Math.ceil(h/c),10),S=Math.min(u,Math.max(1,y)),C=S<y,x=Math.min(h,y*c);return{pullRequests:g,totalCount:d.data.total_count,effectiveQuery:l,...d.data.incomplete_results&&{incompleteResults:!0},pagination:{currentPage:S,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:R,reachableTotalMatches:x,totalMatchesKind:"reported",totalMatchesCapped:R>h,hasMore:C,...C?{nextPage:S+1}:{}},rawResponseChars:N(d.data)+f}}catch(r){if(We(r))return Ys(e);let o=W(r);return Ks(o,Ce.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}function OS(e,t,n=he){let r=(e.pullRequests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.bodyPagination&&{bodyPagination:a.bodyPagination},state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.headRef||"",targetBranch:a.baseRef||"",sourceSha:a.headSha,targetSha:a.baseSha,createdAt:a.createdAt,updatedAt:a.updatedAt,closedAt:a.closedAt,mergedAt:a.mergedAt,commentsCount:a.comments,changedFilesCount:a.changedFiles,additions:a.additions,deletions:a.deletions,comments:a.commentDetails?.map(c=>({id:c.id,author:c.user,body:c.body,...c.bodyPagination&&{bodyPagination:c.bodyPagination},createdAt:c.createdAt,updatedAt:c.updatedAt,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.inReplyToId!=null&&{inReplyToId:c.inReplyToId}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submittedAt,commitId:c.commitId})),commits:a.commitDetails?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.fileChanges?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a.sanitizationWarnings)&&a.sanitizationWarnings.length>0?{sanitizationWarnings:a.sanitizationWarnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.totalCount||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Rr(e.pagination)},...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}function FS(e,t,n){return{owner:t,repo:n,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength}}async function Pd(e,t,n=he){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},i=r||e.owner,s=FS(e,i,o),a=await Cd(s,t);return a.error?at({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:OS(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a)}}var bt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function Oo(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function xd(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:w,...b}=e;return b}let r=t.itemsPerPage??bt.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),u=n.slice(a,c),l=Object.create(null),d=e.path==="/"?"":e.path,m=w=>{let b=w;d&&w.startsWith(d)&&(b=w.slice(d.length),b.startsWith("/")&&(b=b.slice(1)));let A=b.lastIndexOf("/");return A===-1?".":b.slice(0,A)},p=w=>{let b=w.lastIndexOf("/");return b===-1?w:w.slice(b+1)};for(let w of u){let b=m(w.path);l[b]||(l[b]={files:[],folders:[]});let A=p(w.path);w.type==="file"?l[b].files.push(A):l[b].folders.push(A)}for(let w of Object.keys(l)){let b=l[w];b&&(b.files.sort(),b.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((w,b)=>w==="."?-1:b==="."?1:w.localeCompare(b));for(let w of g){let b=l[w];b&&(f[w]=b)}let R=u.filter(w=>w.type==="file").length,h=u.filter(w=>w.type==="dir").length,y=n.filter(w=>w.type==="file").length,S=n.filter(w=>w.type==="dir").length,C=o<s,x={currentPage:o,totalPages:s,hasMore:C,...C?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},T=Oo(x,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:R,pageFolders:h,allFiles:y,allFolders:S}),L,_=e._cachedFileSizeMap;if(_){let w=new Set(u.filter(M=>M.type==="file").map(M=>M.path)),b=e.path==="/"?"":e.path,A=Object.create(null);for(let[M,H]of Object.entries(_))for(let[k,B]of Object.entries(H)){let Z=M==="."?b?`${b}/${k}`:k:b?`${b}/${M}/${k}`:`${M}/${k}`;w.has(Z)&&(A[M]||(A[M]=Object.create(null)),A[M][k]=B)}Object.keys(A).length>0&&(L=A)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:y,totalFolders:S,truncated:C,filtered:!0,originalCount:i},structure:f,...L!==void 0&&{fileSizeMap:L},..._!==void 0&&{_cachedFileSizeMap:_},pagination:x,hints:T,rawResponseChars:e.rawResponseChars}}import{RequestError as DS}from"octokit";var Td=Symbol.for("octocode.recursiveFetchFailures"),MS=new Set([401,403,429]);function wd(e){return e instanceof DS&&MS.has(e.status)}function Xs(e,t){try{Object.defineProperty(e,Td,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function wr(e){if(typeof e!="object"||e===null)return 0;let t=e[Td];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Tr(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Xs(Q([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(f){if(wd(f))throw f;return Xs(Q([],0),1)}let u=N(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(f=>f.type==="file"||f.type==="dir").map(f=>({name:f.name,path:f.path,type:f.type,size:"size"in f?f.size:void 0,download_url:"download_url"in f?f.download_url:void 0,url:f.url,html_url:f.html_url,git_url:f.git_url,sha:f.sha})),m=[...d],p=0;if(i<s){let f=d.filter(R=>R.type==="dir"),g=3;for(let R=0;R<f.length;R+=g){let h=f.slice(R,R+g),y=await Promise.allSettled(h.map(S=>Tr(e,t,n,r,S.path,i+1,s,a)));for(let S of y)if(S.status==="fulfilled"){let C=S.value;u+=te(C)??0,p+=wr(C),m.push(...C)}else{if(wd(S.reason))throw S.reason;p+=1}}}return Xs(Q(m,u),p)}import{RequestError as NS}from"octokit";function GS(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let u=a.lastIndexOf("/"),l=u===-1?a:a.slice(u+1);i.push({name:l,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function Ed(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function Ld(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 NS&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=ln(o.headers);return{items:GS(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:N(n)+N(i),...s?{etag:s}:{}}}import{RequestError as Ad}from"octokit";async function qs(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Pe(t,n,i),a=c)}catch(u){let l=W(u);return{error:Rt.NOT_FOUND.message(t,n,l.error),status:l.status}}try{let u=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),l=ln(u.headers);return{data:u.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...l?{etag:l}:{}}}catch(u){if(u instanceof Ad&&u.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(u instanceof Ad&&u.status===404)){let d=W(u);return{error:Rt.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let l=W(u);return{error:Rt.PATH_NOT_FOUND.message(r,t,n,a),status:l.status}}}function _d(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function HS(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let u=c.lastIndexOf("/");return u===-1?".":c.slice(0,u)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let u=o(a.path);a.type==="file"?n[c].files.push(u):n[c].folders.push(u)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function kd(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 Fo(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:u,includeSizes:l,extraHints:d=[]}=e,m=e.allItems.filter(k=>k.type==="dir"?!yr(k.name):!cn(k.path));m.sort((k,B)=>{if(k.type!==B.type)return k.type==="dir"?-1:1;let Z=k.path.split("/").length,v=B.path.split("/").length;return Z!==v?Z-v:k.path.localeCompare(B.path)});let p=e.itemsPerPage??bt.ENTRIES_PER_PAGE,f=e.page??1,g=m.length,R=Math.max(1,Math.ceil(g/p)),h=(f-1)*p,y=Math.min(h+p,g),S=m.slice(h,y),C=HS(S,i),x=l?kd(m,i):void 0,T=x!==void 0?kd(S,i):void 0,L=S.filter(k=>k.type==="file").length,_=S.filter(k=>k.type==="dir").length,w=m.filter(k=>k.type==="file").length,b=m.filter(k=>k.type==="dir").length,A=f<R,M={currentPage:f,totalPages:R,hasMore:A,...A?{nextPage:f+1}:{},entriesPerPage:p,totalEntries:g},H=Oo(M,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:L,pageFolders:_,allFiles:w,allFolders:b});a>0&&H.unshift(`Partial tree: ${a} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`);for(let k of d)H.unshift(k);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:w,totalFolders:b,truncated:A,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:C,...T!==void 0&&{fileSizeMap:T},...x!==void 0&&{_cachedFileSizeMap:x},pagination:M,hints:H,rawResponseChars:u,_cachedItems:m.map(k=>({path:k.path,type:k.type}))}}async function Js(e,t,n){let r=await pe(t),o=se("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await yo(o,async({ifNoneMatch:s})=>{let a=await BS({...e,itemsPerPage:e.itemsPerPage??bt.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?xd(i,e):i}async function BS(e,t,n){try{let r=await U(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,u=a.replace(/^\/+|\/+$/g,"");if(c>1&&Ed())return await US(r,e,u,c,t,n);let l=await qs(r,o,i,u,s,t,c===1?n:void 0);if("error"in l)return{result:l};if(l.notModified)return{result:{error:"not-modified",status:304},etag:l.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:f}=l,g=N(d),R=Array.isArray(d)?d:[d],h=_d(R),y=0;if(c>1){let S=await Tr(r,o,i,m,u,1,c);y=wr(S),g=te(S)??0,h=S}return{result:Fo({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:u,depth:c,allItems:h,partialTreeFailures:y,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&f?{etag:f}:{}}}catch(r){let o=W(r);return{result:{error:Rt.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function US(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,u,l;try{c?u=c:(l=await Pe(s,a,o),u=l)}catch(h){let y=W(h);return{result:{error:Rt.NOT_FOUND.message(s,a,y.error),status:y.status}}}let d;try{d=await Ld(e,{owner:s,repo:a,workingBranch:u,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(h){let y=await qs(e,s,a,n,u,o);if("error"in y)return{result:y};let S=await Tr(e,s,a,y.workingBranch,n,1,r);return{result:Fo({owner:s,repo:a,workingBranch:y.workingBranch,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:S,partialTreeFailures:wr(S),incompleteTree:!1,rawResponseChars:te(S)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${h instanceof Error?h.message:String(h)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,f=d.rawResponseChars,g=d.truncated,R=[];if(g){R.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let h=await Tr(e,s,a,u,n,1,r);p=wr(h),f+=te(h)??0,m=[...m,...h].filter((S,C,x)=>x.findIndex(T=>T.path===S.path)===C)}catch{}}return{result:Fo({owner:s,repo:a,workingBranch:u,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:f,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:R}),...d.etag&&!g?{etag:d.etag}:{}}}async function QS(e,t,n){try{let o=await(await U(n)).rest.repos.listLanguages({owner:e,repo:t}),i=Object.entries(o.data).sort((s,a)=>a[1]-s[1]);return i.length===0?void 0:{languages:Object.fromEntries(i),dominantLanguage:i[0][0]}}catch{return}}async function $S(e,t,n){try{let i=(await(await U(n)).rest.repos.listContributors({owner:e,repo:t,per_page:30})).data.filter(s=>typeof s.login=="string").map(s=>({login:s.login,contributions:s.contributions??0}));return i.length>0?{contributors:i}:void 0}catch{return}}async function jS(e,t,n){try{let i=(await(await U(n)).rest.repos.listBranches({owner:e,repo:t,per_page:100})).data.map(s=>s.name).filter(s=>typeof s=="string");return i.length>0?{branches:i}:void 0}catch{return}}async function zS(e,t,n){try{let i=(await(await U(n)).rest.repos.listTags({owner:e,repo:t,per_page:50})).data.filter(s=>typeof s.name=="string").map(s=>({name:s.name,sha:s.commit?.sha??""}));return i.length>0?{tags:i}:void 0}catch{return}}function WS(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 Id(e,t,n=he){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},[s,a,c,u,l]=await Promise.all([Js(i,t),e.includeLanguages?QS(r,o,t):Promise.resolve(void 0),e.includeContributors?$S(r,o,t):Promise.resolve(void 0),e.includeBranches?jS(r,o,t):Promise.resolve(void 0),e.includeTags?zS(r,o,t):Promise.resolve(void 0)]);return"error"in s?Ro(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:{...WS(s),...a?{languages:a.languages,dominantLanguage:a.dominantLanguage}:{},...c?{contributors:c.contributors}:{},...u?{branches:u.branches}:{},...l?{tags:l.tags}:{}},status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s)}}var Od={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};var vo=class{type="github";capabilities=Od.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Zl(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await pd(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await ed(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Pd(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Id(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=he(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Pe(n,r,this.authInfo)}handleError(t){let n=W(t);return at(n)}};import{createHash as KS}from"crypto";var YS=3600*1e3,Zs=20,Ke=new Map;function Fd(e){return Date.now()-e.createdAt<YS}function XS(){for(let[e,t]of Ke.entries())Fd(t)||Ke.delete(e);if(Ke.size>Zs){let e=[...Ke.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Ke.size-Zs;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ke.delete(r[0])}}}function qS(e){return e?KS("sha256").update(e).digest("hex").slice(0,16):"default"}function JS(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 ZS(e,t){let n=JS(t?.baseUrl||"default"),r=qS(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function ea(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=ZS(e,t),r=Ke.get(n);if(r&&Fd(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Ke.delete(n),Ke.size>=Zs&&XS();let o=new vo({...t,type:e}),i=Date.now();return Ke.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function vd(){try{return ea("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}]}}import{getConfigSync as
|
|
18
|
+
`).trim()}import{ContentSanitizer as zs}from"@octocodeai/octocode-engine/contentSanitizer";var ES=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function Gt(e){let t=e.toLowerCase();return t.endsWith("[bot]")||ES.has(t)}async function Oo(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=N(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function $s(e,t,n,r){let o=await U(r),{items:i,rawResponseChars:s}=await Oo(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return Q({total_count:i.length,files:i},s)}async function LS(e,t,n,r){let o=await U(r),{items:i,rawResponseChars:s}=await Oo(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return Q(i,s)}async function AS(e,t,n,r){try{let i=await(await U(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return Q(i.data.files||[],i.data)}catch{return null}}var kS=5;async function _S(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 js(e,t,n,r,o){let i=await LS(e,t,n,o);if(!i)return null;let s=te(i)??0,a=[...i].sort((u,l)=>{let d=u.commit.author?.date?new Date(u.commit.author.date).getTime():0;return(l.commit.author?.date?new Date(l.commit.author.date).getTime():0)-d}),c=await _S(a,kS,async u=>{let l=await AS(e,t,u.sha,o),d=[];return l&&(s+=te(l)??0,d=Pr(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:d}});return Q(c,s)}async function Ws(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+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Gt(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=F.minifyMarkdownCore(Io(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:zs.sanitizeContent(f).content,createdAt:p.created_at??"",updatedAt:p.updated_at??"",commentType:"discussion"}}),m=[];return l>0&&m.push(`${l} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:Q(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:Q([],0)}}}async function Vs(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Oo(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return Q(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:zs.sanitizeContent(F.minifyMarkdownCore(Io(s.body??""))).content,submittedAt:s.submitted_at??void 0,commitId:s.commit_id??void 0})),i)}catch{return Q([],0)}}async function Ks(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+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Gt(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=F.minifyMarkdownCore(Io(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:zs.sanitizeContent(f).content,createdAt:p.created_at??"",updatedAt:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{inReplyToId:p.in_reply_to_id}:{}}}),m=[];return l>0&&m.push(`${l} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:Q(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:Q([],0)}}}async function Ys(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Bs(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request&&Us(t))try{let{owner:u,repo:l}=Cr(t);if(u&&l){let d=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(d.data&&(s+=N(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,pn(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),pn(t))){let m=await $s(u,l,e.number);m&&(s+=te(m)??0,m.files=Pr(m.files,t),o.file_changes=m)}}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let a=Lo(t),c=Ao(t);if(a||c){let{owner:u,repo:l}=Cr(t);if(u&&l){let d=Qs(t),m=()=>Promise.resolve({comments:Q([],0)}),[{comments:p,note:f},{comments:g,note:R}]=await Promise.all([a?Ws(n,u,l,e.number,d):m(),c?Ks(n,u,l,e.number,d):m()]);o.comments=[...p,...g],s+=(te(p)??0)+(te(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}}if(_o(t))try{let{owner:u,repo:l}=Cr(t);if(u&&l){let d=await Vs(n,u,l,e.number);s+=te(d)??0,o.reviews=d}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(ko(t))try{let{owner:u,repo:l}=Cr(t);if(u&&l){let d=await js(u,l,e.number,t);d&&(s+=te(d)??0,o.commits=d)}}catch(u){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return Q(o,s)}async function xr(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Bs(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,pn(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),pn(t))try{let d=await $s(a,c,e.number,r);d&&(s+=te(d)??0,d.files=Pr(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 u=Lo(t),l=Ao(t);if(u||l){let d=Qs(t),m=()=>Promise.resolve({comments:Q([],0)}),[{comments:p,note:f},{comments:g,note:R}]=await Promise.all([u?Ws(n,a,c,e.number,d):m(),l?Ks(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(te(p)??0)+(te(g)??0);let h=[f,R].filter(y=>typeof y=="string");h.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...h])}if(_o(t))try{let d=await Vs(n,a,c,e.number);s+=te(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(ko(t))try{let d=await js(a,c,e.number,t,r);d&&(s+=te(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return Q(o,s)}function IS(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function Cd(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pullRequests:[],totalCount:0,error:Ce.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pullRequests:[],totalCount:0,error:Ce.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await U(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await xr(a,e,i,t);return{pullRequests:[dn(c,{includeFullBody:!0,includeFullCommentDetails:!0})],totalCount:1,rawResponseChars:N(s.data)+(te(c)??0)}}catch(i){let s=W(i);return IS(s,Ce.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}function Xs(e,t,n){return{pullRequests:[],totalCount:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function qs(e){let t=Math.min(e.limit||30,100);return{pullRequests:[],totalCount:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Pd(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 xr(m,t,e))),c=a.reduce((m,p)=>m+(te(p)??0),0),u=a.map(m=>dn(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),l=s.data.length===o,d=(i-1)*o+u.length;return{pullRequests:u,totalCount:u.length,pagination:{currentPage:i,totalPages:l?i+1:i,perPage:o,totalMatches:d+(l?1:0),reachableTotalMatches:d,totalMatchesKind:l?"lowerBound":"exact",hasMore:l,...l?{nextPage:i+1}:{}},rawResponseChars:N(s.data)+c}}catch(n){if(We(n))return qs(t);let r=W(n);return Xs(r,Ce.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}async function OS(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 FS(e,t,n="anon"){return se("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,project:e.project,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,auth:n},t)}async function xd(e,t,n){let r=await pe(t),o=FS(e,n,r);return await fe(o,async()=>await vS(e,t,n),{shouldCache:s=>!s.error})}async function vS(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Cd(e,t);let r=await U(t);if(!Cs(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Pd(r,e);let i=await OS(r,e),s=bs(i);if(!s)return{pullRequests:[],totalCount:0,error:Ce.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),u=i.page||1,l=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:u}),m=d.data.items?.filter(T=>!!T.pull_request)||[],p=await Promise.all(m.map(async T=>await Ys(T,i,r))),f=p.reduce((T,L)=>T+(te(L)??0),0),g=p.map(T=>dn(T,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),R=d.data.total_count,h=Math.min(R,1e3),y=Math.min(Math.ceil(h/c),10),S=Math.min(u,Math.max(1,y)),C=S<y,x=Math.min(h,y*c);return{pullRequests:g,totalCount:d.data.total_count,effectiveQuery:l,...d.data.incomplete_results&&{incompleteResults:!0},pagination:{currentPage:S,totalPages:y,perPage:c,totalMatches:h,reportedTotalMatches:R,reachableTotalMatches:x,totalMatchesKind:"reported",totalMatchesCapped:R>h,hasMore:C,...C?{nextPage:S+1}:{}},rawResponseChars:N(d.data)+f}}catch(r){if(We(r))return qs(e);let o=W(r);return Xs(o,Ce.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}function DS(e,t,n=he){let r=(e.pullRequests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.bodyPagination&&{bodyPagination:a.bodyPagination},state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.headRef||"",targetBranch:a.baseRef||"",sourceSha:a.headSha,targetSha:a.baseSha,createdAt:a.createdAt,updatedAt:a.updatedAt,closedAt:a.closedAt,mergedAt:a.mergedAt,commentsCount:a.comments,changedFilesCount:a.changedFiles,additions:a.additions,deletions:a.deletions,comments:a.commentDetails?.map(c=>({id:c.id,author:c.user,body:c.body,...c.bodyPagination&&{bodyPagination:c.bodyPagination},createdAt:c.createdAt,updatedAt:c.updatedAt,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.inReplyToId!=null&&{inReplyToId:c.inReplyToId}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submittedAt,commitId:c.commitId})),commits:a.commitDetails?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.fileChanges?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a.sanitizationWarnings)&&a.sanitizationWarnings.length>0?{sanitizationWarnings:a.sanitizationWarnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.totalCount||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Rr(e.pagination)},...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}function MS(e,t,n){return{owner:t,repo:n,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength}}async function wd(e,t,n=he){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},i=r||e.owner,s=MS(e,i,o),a=await xd(s,t);return a.error?at({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:DS(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a)}}var bt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function Fo(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function Td(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:w,...b}=e;return b}let r=t.itemsPerPage??bt.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),u=n.slice(a,c),l=Object.create(null),d=e.path==="/"?"":e.path,m=w=>{let b=w;d&&w.startsWith(d)&&(b=w.slice(d.length),b.startsWith("/")&&(b=b.slice(1)));let A=b.lastIndexOf("/");return A===-1?".":b.slice(0,A)},p=w=>{let b=w.lastIndexOf("/");return b===-1?w:w.slice(b+1)};for(let w of u){let b=m(w.path);l[b]||(l[b]={files:[],folders:[]});let A=p(w.path);w.type==="file"?l[b].files.push(A):l[b].folders.push(A)}for(let w of Object.keys(l)){let b=l[w];b&&(b.files.sort(),b.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((w,b)=>w==="."?-1:b==="."?1:w.localeCompare(b));for(let w of g){let b=l[w];b&&(f[w]=b)}let R=u.filter(w=>w.type==="file").length,h=u.filter(w=>w.type==="dir").length,y=n.filter(w=>w.type==="file").length,S=n.filter(w=>w.type==="dir").length,C=o<s,x={currentPage:o,totalPages:s,hasMore:C,...C?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},T=Fo(x,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:R,pageFolders:h,allFiles:y,allFolders:S}),L,k=e._cachedFileSizeMap;if(k){let w=new Set(u.filter(M=>M.type==="file").map(M=>M.path)),b=e.path==="/"?"":e.path,A=Object.create(null);for(let[M,H]of Object.entries(k))for(let[I,B]of Object.entries(H)){let Z=M==="."?b?`${b}/${I}`:I:b?`${b}/${M}/${I}`:`${M}/${I}`;w.has(Z)&&(A[M]||(A[M]=Object.create(null)),A[M][I]=B)}Object.keys(A).length>0&&(L=A)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:y,totalFolders:S,truncated:C,filtered:!0,originalCount:i},structure:f,...L!==void 0&&{fileSizeMap:L},...k!==void 0&&{_cachedFileSizeMap:k},pagination:x,hints:T,rawResponseChars:e.rawResponseChars}}import{RequestError as GS}from"octokit";var Ld=Symbol.for("octocode.recursiveFetchFailures"),HS=new Set([401,403,429]);function Ed(e){return e instanceof GS&&HS.has(e.status)}function Js(e,t){try{Object.defineProperty(e,Ld,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function wr(e){if(typeof e!="object"||e===null)return 0;let t=e[Ld];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Tr(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Js(Q([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(f){if(Ed(f))throw f;return Js(Q([],0),1)}let u=N(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(f=>f.type==="file"||f.type==="dir").map(f=>({name:f.name,path:f.path,type:f.type,size:"size"in f?f.size:void 0,download_url:"download_url"in f?f.download_url:void 0,url:f.url,html_url:f.html_url,git_url:f.git_url,sha:f.sha})),m=[...d],p=0;if(i<s){let f=d.filter(R=>R.type==="dir"),g=3;for(let R=0;R<f.length;R+=g){let h=f.slice(R,R+g),y=await Promise.allSettled(h.map(S=>Tr(e,t,n,r,S.path,i+1,s,a)));for(let S of y)if(S.status==="fulfilled"){let C=S.value;u+=te(C)??0,p+=wr(C),m.push(...C)}else{if(Ed(S.reason))throw S.reason;p+=1}}}return Js(Q(m,u),p)}import{RequestError as BS}from"octokit";function US(e,t){let n=(t.pathPrefix??"").replace(/^\/+|\/+$/g,""),r=n?`${n}/`:"",o=Math.max(1,t.maxDepth),i=[];for(let s of e){if(!s.path||s.type!=="blob"&&s.type!=="tree")continue;let a=s.path;if(n){if(s.path===n||!s.path.startsWith(r))continue;a=s.path.slice(r.length)}let c=a.split("/").filter(Boolean).length;if(c===0||c>o)continue;let u=a.lastIndexOf("/"),l=u===-1?a:a.slice(u+1);i.push({name:l,path:s.path,type:s.type==="tree"?"dir":"file",size:s.type==="blob"?s.size:void 0,sha:s.sha,url:s.url,html_url:void 0,git_url:void 0,download_url:void 0})}return i}function Ad(e=process.env){return e.OCTOCODE_GH_STRUCTURE_TREES!=="0"}async function kd(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 BS&&c.status===304)return{items:[],truncated:!1,rawResponseChars:0,etag:t.ifNoneMatch,notModified:!0};throw c}let i=o.data,s=ln(o.headers);return{items:US(i.tree,{pathPrefix:t.pathPrefix,maxDepth:t.maxDepth}),truncated:!!i.truncated,rawResponseChars:N(n)+N(i),...s?{etag:s}:{}}}import{RequestError as _d}from"octokit";async function Zs(e,t,n,r,o,i,s){let a,c;try{o?a=o:(c=await Pe(t,n,i),a=c)}catch(u){let l=W(u);return{error:Rt.NOT_FOUND.message(t,n,l.error),status:l.status}}try{let u=await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:a,...s?{headers:{"If-None-Match":s}}:{}}),l=ln(u.headers);return{data:u.data,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},...l?{etag:l}:{}}}catch(u){if(u instanceof _d&&u.status===304)return{data:null,workingBranch:a,...c!==void 0?{repoDefaultBranch:c}:{},etag:s,notModified:!0};if(!(u instanceof _d&&u.status===404)){let d=W(u);return{error:Rt.ACCESS_FAILED.message(t,n,d.error),status:d.status,rateLimitRemaining:d.rateLimitRemaining,rateLimitReset:d.rateLimitReset,retryAfter:d.retryAfter}}let l=W(u);return{error:Rt.PATH_NOT_FOUND.message(r,t,n,a),status:l.status}}}function Id(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function QS(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let u=c.lastIndexOf("/");return u===-1?".":c.slice(0,u)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let u=o(a.path);a.type==="file"?n[c].files.push(u):n[c].folders.push(u)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function Od(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 vo(e){let{owner:t,repo:n,workingBranch:r,repoDefaultBranch:o,cleanPath:i,depth:s,partialTreeFailures:a,incompleteTree:c,rawResponseChars:u,includeSizes:l,extraHints:d=[]}=e,m=e.allItems.filter(I=>I.type==="dir"?!yr(I.name):!cn(I.path));m.sort((I,B)=>{if(I.type!==B.type)return I.type==="dir"?-1:1;let Z=I.path.split("/").length,v=B.path.split("/").length;return Z!==v?Z-v:I.path.localeCompare(B.path)});let p=e.itemsPerPage??bt.ENTRIES_PER_PAGE,f=e.page??1,g=m.length,R=Math.max(1,Math.ceil(g/p)),h=(f-1)*p,y=Math.min(h+p,g),S=m.slice(h,y),C=QS(S,i),x=l?Od(m,i):void 0,T=x!==void 0?Od(S,i):void 0,L=S.filter(I=>I.type==="file").length,k=S.filter(I=>I.type==="dir").length,w=m.filter(I=>I.type==="file").length,b=m.filter(I=>I.type==="dir").length,A=f<R,M={currentPage:f,totalPages:R,hasMore:A,...A?{nextPage:f+1}:{},entriesPerPage:p,totalEntries:g},H=Fo(M,{owner:t,repo:n,branch:r,path:i,depth:s,pageFiles:L,pageFolders:k,allFiles:w,allFolders:b});a>0&&H.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)H.unshift(I);return{owner:t,repo:n,branch:r,...o!==void 0&&{defaultBranch:o},path:i||"/",apiSource:!0,summary:{totalFiles:w,totalFolders:b,truncated:A,filtered:!0,originalCount:m.length,...c?{incompleteTree:!0}:{}},structure:C,...T!==void 0&&{fileSizeMap:T},...x!==void 0&&{_cachedFileSizeMap:x},pagination:M,hints:H,rawResponseChars:u,_cachedItems:m.map(I=>({path:I.path,type:I.type}))}}async function ea(e,t,n){let r=await pe(t),o=se("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth,auth:r},n),i=await Ro(o,async({ifNoneMatch:s})=>{let a=await $S({...e,itemsPerPage:e.itemsPerPage??bt.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?Td(i,e):i}async function $S(e,t,n){try{let r=await U(t),{owner:o,repo:i,branch:s,path:a="",maxDepth:c=1}=e,u=a.replace(/^\/+|\/+$/g,"");if(c>1&&Ad())return await jS(r,e,u,c,t,n);let l=await Zs(r,o,i,u,s,t,c===1?n:void 0);if("error"in l)return{result:l};if(l.notModified)return{result:{error:"not-modified",status:304},etag:l.etag??n,notModified:!0};let{data:d,workingBranch:m,repoDefaultBranch:p,etag:f}=l,g=N(d),R=Array.isArray(d)?d:[d],h=Id(R),y=0;if(c>1){let S=await Tr(r,o,i,m,u,1,c);y=wr(S),g=te(S)??0,h=S}return{result:vo({owner:o,repo:i,workingBranch:m,repoDefaultBranch:p,cleanPath:u,depth:c,allItems:h,partialTreeFailures:y,incompleteTree:!1,rawResponseChars:g,includeSizes:e.includeSizes===!0,itemsPerPage:e.itemsPerPage,page:e.page}),...c===1&&f?{etag:f}:{}}}catch(r){let o=W(r);return{result:{error:Rt.STRUCTURE_EXPLORATION_FAILED.message,status:o.status,rateLimitRemaining:o.rateLimitRemaining,rateLimitReset:o.rateLimitReset,retryAfter:o.retryAfter}}}}async function jS(e,t,n,r,o,i){let{owner:s,repo:a,branch:c}=t,u,l;try{c?u=c:(l=await Pe(s,a,o),u=l)}catch(h){let y=W(h);return{result:{error:Rt.NOT_FOUND.message(s,a,y.error),status:y.status}}}let d;try{d=await kd(e,{owner:s,repo:a,workingBranch:u,pathPrefix:n,maxDepth:r,ifNoneMatch:i})}catch(h){let y=await Zs(e,s,a,n,u,o);if("error"in y)return{result:y};let S=await Tr(e,s,a,y.workingBranch,n,1,r);return{result:vo({owner:s,repo:a,workingBranch:y.workingBranch,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:S,partialTreeFailures:wr(S),incompleteTree:!1,rawResponseChars:te(S)??0,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:[`Git Trees fetch failed (${h instanceof Error?h.message:String(h)}); used Contents recursion instead.`]})}}if(d.notModified)return{result:{error:"not-modified",status:304},etag:d.etag??i,notModified:!0};let m=d.items,p=0,f=d.rawResponseChars,g=d.truncated,R=[];if(g){R.push("Git Trees response was truncated by GitHub \u2014 this structure listing may be incomplete. Narrow path/depth or set OCTOCODE_GH_STRUCTURE_TREES=0 for Contents recursion.");try{let h=await Tr(e,s,a,u,n,1,r);p=wr(h),f+=te(h)??0,m=[...m,...h].filter((S,C,x)=>x.findIndex(T=>T.path===S.path)===C)}catch{}}return{result:vo({owner:s,repo:a,workingBranch:u,repoDefaultBranch:l,cleanPath:n,depth:r,allItems:m,partialTreeFailures:p,incompleteTree:g,rawResponseChars:f,includeSizes:t.includeSizes===!0,itemsPerPage:t.itemsPerPage,page:t.page,extraHints:R}),...d.etag&&!g?{etag:d.etag}:{}}}async function zS(e,t,n){try{let o=await(await U(n)).rest.repos.listLanguages({owner:e,repo:t}),i=Object.entries(o.data).sort((s,a)=>a[1]-s[1]);return i.length===0?void 0:{languages:Object.fromEntries(i),dominantLanguage:i[0][0]}}catch{return}}async function WS(e,t,n){try{let i=(await(await U(n)).rest.repos.listContributors({owner:e,repo:t,per_page:30})).data.filter(s=>typeof s.login=="string").map(s=>({login:s.login,contributions:s.contributions??0}));return i.length>0?{contributors:i}:void 0}catch{return}}async function VS(e,t,n){try{let i=(await(await U(n)).rest.repos.listBranches({owner:e,repo:t,per_page:100})).data.map(s=>s.name).filter(s=>typeof s=="string");return i.length>0?{branches:i}:void 0}catch{return}}async function KS(e,t,n){try{let i=(await(await U(n)).rest.repos.listTags({owner:e,repo:t,per_page:50})).data.filter(s=>typeof s.name=="string").map(s=>({name:s.name,sha:s.commit?.sha??""}));return i.length>0?{tags:i}:void 0}catch{return}}function YS(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 Fd(e,t,n=he){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},[s,a,c,u,l]=await Promise.all([ea(i,t),e.includeLanguages?zS(r,o,t):Promise.resolve(void 0),e.includeContributors?WS(r,o,t):Promise.resolve(void 0),e.includeBranches?VS(r,o,t):Promise.resolve(void 0),e.includeTags?KS(r,o,t):Promise.resolve(void 0)]);return"error"in s?So(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:{...YS(s),...a?{languages:a.languages,dominantLanguage:a.dominantLanguage}:{},...c?{contributors:c.contributors}:{},...u?{branches:u.branches}:{},...l?{tags:l.tags}:{}},status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s)}}var vd={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};var Do=class{type="github";capabilities=vd.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await td(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await fd(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await nd(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await wd(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Fd(t,this.authInfo,he)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=he(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Pe(n,r,this.authInfo)}handleError(t){let n=W(t);return at(n)}};import{createHash as qS}from"crypto";var JS=3600*1e3,ta=20,Ke=new Map;function Dd(e){return Date.now()-e.createdAt<JS}function ZS(){for(let[e,t]of Ke.entries())Dd(t)||Ke.delete(e);if(Ke.size>ta){let e=[...Ke.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Ke.size-ta;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Ke.delete(r[0])}}}function eb(e){return e?qS("sha256").update(e).digest("hex").slice(0,16):"default"}function tb(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 nb(e,t){let n=tb(t?.baseUrl||"default"),r=eb(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function na(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=nb(e,t),r=Ke.get(n);if(r&&Dd(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Ke.delete(n),Ke.size>=ta&&ZS();let o=new Do({...t,type:e}),i=Date.now();return Ke.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function Md(){try{return na("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}]}}import{getConfigSync as RE}from"@octocodeai/config";import{existsSync as rb,readdirSync as ob,lstatSync as ib}from"node:fs";import{join as sb}from"node:path";function Nd(e){if(!rb(e))return 0;let t;try{t=ob(e)}catch{return 0}let n=0;for(let r of t){if(r===".git")continue;let o=sb(e,r);try{let i=ib(o);if(i.isSymbolicLink())continue;i.isDirectory()?n+=mo(o):i.isFile()&&(n+=i.size)}catch{}}return n}async function Gd(e,t={}){if(!Array.isArray(e))throw new Error(ar.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(ar.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(ar.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,u)=>typeof c=="function"?c:()=>Promise.reject(new Error(ur.NOT_A_FUNCTION.message(u))));if(r<i.length)return ab(i,r,n,o);let s=i.map((c,u)=>Hd(c,u,n,o));return(await Promise.allSettled(s)).map((c,u)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:u})}async function Hd(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,u)=>{o=setTimeout(()=>{u(new Error(ur.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 ab(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,u=e[c];if(!u){o[c]={success:!1,error:new Error(ur.FUNCTION_UNDEFINED.message),index:c};continue}try{let l=await Hd(u,c,n,r);o[c]=l}catch(l){o[c]={success:!1,error:l instanceof Error?l:new Error(String(l)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Bd=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,cb=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,ub=5e3;function Ud(e,t,n){if(e<=1)return Bd;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(cb/o),s=Math.max(ub,Math.min(i,Bd));return n?Math.max(s,n):s}async function Qd(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,u)=>()=>t(c,u).then(l=>({result:l,queryIndex:u,originalQuery:c})));return(await Gd(s,{timeout:Ud(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,u)=>{i.push({queryIndex:u,error:c.message})}})).forEach(c=>{if(c.success&&c.data){let u=c.data.result,l=u&&Object.keys(u).some(m=>m!=="status"&&m!=="error"&&m!=="data");if(u&&u.error===void 0&&(u.data===null||u.data===void 0)&&!l&&u.status!=="error"){i.push({queryIndex:c.data.queryIndex,error:"Query resolved without a payload (possible timeout or resource exhaustion) \u2014 retry this query alone, with tighter caps if it was large"});return}o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}else c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function Er(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 Lr(e){let t=new Set;return e.map((n,r)=>{let o=Er(n,r);if(t.has(o)){let i=2;for(;t.has(`${o}#${i}`);)i+=1;o=`${o}#${i}`}return t.add(o),o})}import{ContentSanitizer as lb}from"@octocodeai/octocode-engine/contentSanitizer";import{getConfigSync as db}from"@octocodeai/config";function pb(){try{return db().output.format}catch{return"yaml"}}function Qe(e){if(e==null)return e;if(typeof e=="string")return lb.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Qe(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))n!=="warnings"&&(t[n]=Qe(r));return t}return e}function mb(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 Bt(e,t){let n=Ht(e)??{},r=Qe(n),o=
|
|
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
|
|
21
|
+
`):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Bt(e,t){let n=Ht(e)??{},r=Qe(n),o=pb(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Mo(r,t||i),null,2):F.jsonToYamlString(r,{keysPriority:t||i})}function Mo(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Mo(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Mo(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Mo(n[o],t));return r}var fb=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"]),hb=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"];function gb(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=>fb.has(r))||hb.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 Ht(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=>Ht(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(s==="warnings"||gb(a))continue;let c=(s==="files"||s==="repositories")&&!n,u=Ht(a,{inFilesObject:n||c,depth:c?0:r+1});u!==void 0&&(o[s]=u,i=!0)}return i?o:void 0}return e}import $d from"node:path";import{fileURLToPath as yb}from"node:url";function Rb(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}var jd=["path","uri","absolutePath"],zd=new Set(["next","location"]);function ra(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let i of e)ra(i,t,n+1);return}let r=e,o=Sb(r);o&&t.push({obj:r,abs:o});for(let[i,s]of Object.entries(r))zd.has(i)||s&&typeof s=="object"&&ra(s,t,n+1)}function Sb(e){let t=e.absolutePath;if(typeof t=="string"&&$d.isAbsolute(t))return t;let n=e.uri;if(typeof n=="string"&&n.startsWith("file://"))try{return yb(n)}catch{return}let r=e.path;if(typeof r=="string"&&$d.isAbsolute(r))return r}function mn(e){let t=[];for(let i of e)ra(i?.data,t,0);if(t.length===0)return;let n=Rb(t.map(i=>i.abs));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,abs:s}of t)s.startsWith(r)&&(i.path=s.slice(o),delete i.absolutePath,delete i.uri);return bb(e,r),n}function bb(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(zd.has(s))continue;let a=i[s];typeof a=="string"?!jd.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function Cb(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 Pb(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var xb=new Set([...jd,"owner","repo","name","id","type","kind","reason"]);function fn(e){let t=Cb(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(xb.has(i))continue;let s=n[i];Pb(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}function oa(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 wb(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=oa(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function Tb(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=oa(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 ia(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=oa(e,s,i),c=a<o,u=wb(e,s,i),l=Tb(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${u}/${l}. Next: responseCharOffset=${a}
|
|
23
23
|
`:`# Response page ${u}/${l}.
|
|
24
|
-
`}${d}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function
|
|
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 ia(e){return e instanceof Se}function Wd(e,t=G.TOOL_EXECUTION_FAILED,n){if(ia(e))return e;if(e instanceof Error)return new Se(t,e.message,n,e);let r=String(e);return new Se(t,r,n)}function Eb(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function O(e,t,n={}){let{extra:r}=n,o={status:"error"};if(Eb(e))o.error=e;else if(ia(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Wd(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:Q(o,n.rawResponse)}function xe(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:O(i,t,{toolName:n.toolName})}}function oe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:Q(s,o.rawResponse)}function Mo(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 O(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ye(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return O(i,t,{toolName:r})}async function Te({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ye(o,t,r,e)}}function sa(e){return e.data!==void 0&&!e.error}import{maskSensitiveData as Vd}from"@octocodeai/octocode-engine/mask";var aa=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function Lb(){return ss().provider??is()}function Ab(e){let t=ss(),n=t.provider??is(),{baseUrl:r,token:o}=t;try{let i=ea(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=Vd(s);throw new aa(n,`Failed to initialize ${n} provider: ${a}`)}}function De(e){let t;return()=>t??=Ab(e)}function No(e,t){return e.capabilities[t]}async function ct(e,t){let n=await t();return sa(n)?{ok:!0,response:n}:{ok:!1,result:Mo(n,e)}}async function Kd(e,t){let n=t??Lb(),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:Vd(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)sa(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}import{existsSync as Yb,mkdirSync as la,renameSync as Xb,rmSync as qb}from"fs";import{join as vr}from"path";import{createHash as Jb}from"crypto";var Go=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Ar=[...Go,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Yd=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function Xd(e={},t=Go){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}import{spawn as _b}from"child_process";var kb=10*1024*1024,Ib=5e3;function _r(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Go,maxOutputSize:a=kb}=n;return new Promise(c=>{let u={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},l=()=>u.stdoutChunks.join(""),d=()=>u.stderrChunks.join(""),m={cwd:o,env:Xd(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=_b(e,t,m)}catch(y){c({stdout:"",stderr:"",exitCode:null,success:!1,error:y instanceof Error?y:new Error(`Failed to spawn command '${e}'`)});return}let f,g=setTimeout(()=>{if(!u.killed){u.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Ib),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),R=()=>{clearTimeout(g),f!==void 0&&(clearTimeout(f),f=void 0)},h=()=>{if(u.totalOutputSize>a){if(!u.killed){u.killed=!0;try{p.kill("SIGKILL")}catch{}R(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stdoutChunks.push(S)}),p.stderr?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stderrChunks.push(S)}),p.on("close",y=>{u.killed||(R(),c({stdout:l(),stderr:d(),exitCode:y,success:y===0}))}),p.on("error",y=>{u.killed||(u.killed=!0,R(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:y}))})})}var eM=1*1024*1024;function qd(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}}import{existsSync as Fr,readFileSync as Fb,writeFileSync as vb,mkdirSync as Db,rmSync as Or,readdirSync as Mb,statSync as Nb}from"node:fs";import{join as Ct}from"node:path";import{join as Ho}from"node:path";import{createHash as Jd}from"node:crypto";function Bo(e){return Ho(e,"tmp","clone")}function Uo(e){return Ho(e,"tmp","tree")}function Ob(e){return e?`__sp_${Jd("sha256").update(e).digest("hex").substring(0,6)}`:""}function Zd(e){if(!/[\\/]/.test(e))return e;let t=Jd("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function ca(e,t,n,r,o){let i=`${Zd(r)}${Ob(o)}`;return Ho(Bo(e),t,n,i)}function kr(e,t,n,r){return Ho(Uo(e),t,n,Zd(r))}var Gb=1440*60*1e3,mM=600*1e3,Hb=2*1024*1024*1024,Bb=50,tp=".octocode-clone-meta.json";function Ub(e){return typeof e=="object"&&e!==null}function Qb(e){if(!Ub(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 ua(e){let t=Ct(e,tp);if(!Fr(t))return null;try{return Qb(JSON.parse(Fb(t,"utf-8")))}catch{return null}}function hn(e,t){try{vb(Ct(e,tp),JSON.stringify(t,null,2),"utf-8")}catch{}}function np(e){return Date.now()<new Date(e.expiresAt).getTime()}function gn(e){let t=ua(e);return t?np(t)?Fr(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 Gb}function jb(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Hb}function zb(){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 Bb}function yn(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 Pt(e){let t=Ct(e,"..");try{Fr(t)||Db(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 Qo(e){try{Fr(e)&&Or(e,{recursive:!0,force:!0})}catch{}}function Ir(e){try{return Nb(e).isDirectory()}catch{return!1}}function Ut(e){try{return Mb(e)}catch{return[]}}function*rp(e){for(let t of Ut(e)){let n=Ct(e,t);if(Ir(n))for(let r of Ut(n)){let o=Ct(n,r);if(Ir(o))for(let i of Ut(o)){let s=Ct(o,i);Ir(s)&&(yield s)}}}}function ep(e){for(let t of[...Ut(e)]){let n=Ct(e,t);if(Ir(n)){for(let r of[...Ut(n)]){let o=Ct(n,r);if(Ir(o)&&Ut(o).length===0)try{Or(o,{recursive:!0,force:!0})}catch{}}if(Ut(n).length===0)try{Or(n,{recursive:!0,force:!0})}catch{}}}}function Wb(e){let t=0;for(let n of rp(e))try{let r=ua(n);(!r||!np(r))&&(Or(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Vb(e){let t=[];for(let n of rp(e)){let r=ua(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??po(n)})}return t}function Kb(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{Or(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function op(e){if(!Fr(e))return 0;let t=0;try{t+=Wb(e)}catch{return t}ep(e);let n=Kb(Vb(e),jb(),zb());return t+=n,n>0&&ep(e),t}function ip(e){return op(Bo(e))}function $o(e){return op(Uo(e))}var sp=120*1e3,Zb=30*1e3,eC=300*1e3,tC=100,ap="clone-locks",nC="clone-tmp",cp=[...Ar,"GIT_TERMINAL_PROMPT"];async function up(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await dC();let a=e.branch??await Pe(r,o,t),c=rn(),u=ca(c,r,o,a,i);return rC(c,u,async()=>{let l=gn(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};ip(c),Pt(u);let d=lC(t,n),m=iC(c,u);Qo(m);try{if(i){if(await uC(r,o,a,m,i,d),!Yb(vr(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await cC(r,o,a,m,d);let p=yn(r,o,a,"clone",i);return hn(m,p),sC(m,u),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw Qo(m),p}})}async function rC(e,t,n){Pt(t);let r=oC(e,t);la(vr(e,"tmp",ap),{recursive:!0,mode:448});let o=Date.now();for(;;)try{la(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>eC)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await aC(tC)}try{return await n()}finally{qb(r,{recursive:!0,force:!0})}}function lp(e){return Jb("sha256").update(e).digest("hex").slice(0,16)}function oC(e,t){return vr(e,"tmp",ap,lp(t))}function iC(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=vr(e,"tmp",nC);return la(r,{recursive:!0,mode:448}),vr(r,`${lp(t)}-${n}`)}function sC(e,t){Qo(t),Pt(t),Xb(e,t)}function aC(e){return new Promise(t=>setTimeout(t,e))}async function cC(e,t,n,r,o){let i=pp(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",dp(e,t),r),await da(i,sp,`full clone of ${e}/${t}`,o)}async function uC(e,t,n,r,o,i){let s=pp(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",dp(e,t),r),await da(s,sp,`sparse clone of ${e}/${t}`,i),await da(["-C",r,"sparse-checkout","set","--skip-checks","--",o],Zb,`sparse-checkout set ${o}`,void 0)}function dp(e,t){return`https://github.com/${e}/${t}.git`}function pp(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function lC(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function dC(){try{if(!(await _r("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:cp,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 pC(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 da(e,t,n,r){let o=await _r("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:cp,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=pC(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}async function mp(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>Te({toolName:P.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!No(s,"cloneRepo"))return ye(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",P.GITHUB_CLONE_REPO);let a;try{a=await up(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return O(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=Dd(a.localPath),u={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},l={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},d={owner:o.owner,repo:o.repo,totalSize:c,location:u,next:l};return oe(o,d,!0,P.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:P.GITHUB_CLONE_REPO,keysPriority:["totalSize","location","error"]},e)}import{readdirSync as mC,statSync as fp}from"node:fs";import{join as fC}from"node:path";var Dr=50,jo=5*1024*1024,pa=300*1024,hp=5,hC=1e4,gp=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"]),ma={maxDirectoryFiles:Dr,maxTotalSize:jo,maxFileSize:pa};function fa(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function yp(e){return Object.values(e).every(t=>t===0)}function ha(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 Rp(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 yC(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var gC=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function yC(e,t){try{let o=new URL(e);if(!gC.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(),hC);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 Sp(e,t){let n=[],r=0;function o(i){let s;try{s=mC(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=fC(i,a);try{let u=fp(c);if(u.isDirectory())o(c);else if(u.isFile()){let l=c.substring(t.length+1);r+=u.size,n.push({path:l,size:u.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function bp(e){try{return fp(e).size}catch{return 0}}import{writeFileSync as RC,mkdirSync as Cp,existsSync as ga,rmSync as SC}from"node:fs";import{join as Pp,dirname as bC,resolve as xp,sep as wp}from"node:path";async function ya(e,t,n,r,o,i=!1){let s=rn(),a=kr(s,e,t,r),c=xp(Pp(a,n));if(!c.startsWith(a+wp)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=gn(a);if(u.hit&&!i&&ga(c)){let b=Sp(c,a),A=fa();return{localPath:c,repoRoot:a,files:b.files,fileCount:b.fileCount,totalSize:b.totalSize,complete:!0,verified:!1,...u.meta.commitSha?{commitSha:u.meta.commitSha}:{},directoryEntryCount:b.fileCount,eligibleFileCount:b.fileCount,savedFileCount:b.fileCount,skipped:A,limits:ma,warnings:ha(!0,!1),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await U(o),d;try{d=(await l.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await l.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let p=m,f=fa(),g=[];for(let b of p){if(b.type!=="file"){f.nonFile+=1;continue}if(!b.download_url){f.missingDownloadUrl+=1;continue}if(b.size>pa){f.oversized+=1;continue}let A=$l(b.name,{lowercase:!0,leadingDot:!0});if(gp.has(A)){f.binary+=1;continue}g.push(b)}f.fileLimit=Math.max(0,g.length-Dr);let R=g.slice(0,Dr),h=o?.token,y=await Rp(R,hp,h);f.fetchFailed=R.length-y.length;let S=0,C=[];for(let b=0;b<y.length;b+=1){let{entry:A,content:M}=y[b];if(S+M.length>jo){f.totalSizeLimit=y.length-b;break}S+=M.length,C.push({entry:A,content:M})}$o(s),Pt(a),ga(c)&&SC(c,{recursive:!0,force:!0}),Cp(c,{recursive:!0,mode:448});let x=[];for(let{entry:b,content:A}of C){let M=xp(Pp(a,b.path));if(!M.startsWith(a+wp)){f.pathTraversal+=1;continue}let H=bC(M);ga(H)||Cp(H,{recursive:!0,mode:448}),RC(M,A,"utf-8"),x.push({path:b.path,size:A.length,type:"file"})}let T=yn(e,t,r,"treeFetch",void 0,void 0,d);hn(a,T);let L=yp(f),_=L,w=f.nonFile>0;return{localPath:c,repoRoot:a,files:x,fileCount:x.length,totalSize:S,complete:L,verified:_,...d?{commitSha:d}:{},...w?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:x.length,skipped:f,limits:ma,warnings:ha(L,_),cached:!1,expiresAt:T.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}import{writeFileSync as CC,mkdirSync as PC,existsSync as Tp}from"node:fs";import{join as xC,dirname as wC,resolve as TC,sep as EC}from"node:path";async function Ra(e,t,n,r,o,i=!1){let s=rn(),a=kr(s,e,t,r),c=TC(xC(a,n));if(!c.startsWith(a+EC)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=gn(a);if(!i&&u.hit&&Tp(c))return{localPath:c,repoRoot:a,path:n,size:bp(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await Sr({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in l)||!l.data){let f="error"in l?l.error:void 0;throw new Error(f||`Failed to fetch ${e}/${t}/${n}`)}$o(s),Pt(a);let d=wC(c);Tp(d)||PC(d,{recursive:!0,mode:448}),CC(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,p=yn(e,t,m,"treeFetch");return hn(a,p),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}function zo(e,t){return e&&t?`${e}/${t}`:void 0}function Wo(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Vo(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function AC(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 Ep(e){return{keywords:e.keywords??[],projectId:zo(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 Lp(e,t){let n=t.match==="path",r=new Map;for(let i of e.items){let s=i.repository.name||"",{owner:a,repo:c}=Wo(s),u=`${a}/${c}`,l=r.get(u);if(l||(l={id:u,owner:a,repo:c,matches:[]},r.set(u,l)),n||!i.matches?.length){l.matches.push({path:i.path,...n?{}:{pathOnly:!0}});continue}let d=!1;for(let m of i.matches){if(!m.context)continue;let p=AC(m.context),f={path:i.path,value:p};if(m.positions?.length>0){let g=m.positions.filter(([,R])=>R<=p.length);g.length>0&&(f.matchIndices=g.map(([R,h])=>({start:R,end:h,lineOffset:(m.context??"").substring(0,R).split(`
|
|
26
|
-
`).length-1})))}l.matches.push(f),d=!0}d||l.matches.push({path:i.path,pathOnly:!0})}let o={results:Array.from(r.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(o.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Vo(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),o}function Ap(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,license:t.license,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function _p(e){return e.map(t=>{let{owner:n,repo:r}=Wo(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function Ko(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function kp(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Ko),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:zo(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,draft:e.draft,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function _C(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=>!Gt(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 kC(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:_C(e,t??[])}}function Ip(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,u=kC(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(l=>({...l,...l.bodyPagination&&{bodyPagination:l.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...u&&{reviewSummary:u},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...Vo(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pullRequests:r,...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},...o?{pagination:o}:{totalCount:e.totalCount||r.length}},pagination:o}}function Op(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 Fp(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.matchedLines?.length&&{matchedLines:e.matchedLines},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function Sa(e,t){let n=e.include??[];return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??bt.ENTRIES_PER_PAGE,page:(()=>{let r=e.page;return typeof r=="number"?r:void 0})(),includeSizes:n.includes("sizes"),includeLanguages:n.includes("languages"),includeContributors:n.includes("contributors"),includeBranches:n.includes("branches"),includeTags:n.includes("tags"),mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function vp(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([p],[f])=>p==="."?-1:f==="."?1:p.localeCompare(f)).map(([p,f])=>({dir:p,files:f.files,folders:f.folders})),c=e.fileSizeMap,u={};if(c){for(let[p,f]of Object.entries(c))if(n[p]){let g=new Set(n[p].files);for(let[R,h]of Object.entries(f))if(g.has(R)){let y=p==="."?R:`${p}/${R}`;u[y]=h}}}let l=Object.values(n).reduce((p,f)=>(p.totalFiles+=f.files.length,p.totalFolders+=f.folders.length,p),{totalFiles:0,totalFolders:0}),d=e,m={structure:a,...Object.keys(u).length>0&&{fileSizes:u},...d.languages?{languages:d.languages,dominantLanguage:d.dominantLanguage}:{},...d.contributors?{contributors:d.contributors,totalContributors:d.contributors.length}:{},...d.branches?{branches:d.branches,totalBranches:d.branches.length}:{},...d.tags?{tags:d.tags,totalTags:d.tags.length}:{},summary:{totalFiles:l.totalFiles,totalFolders:l.totalFolders}};return i&&(m.resolvedBranch=i),s&&(m.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(m.pagination=e.pagination),m}function Yo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function IC(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:Yo(t.status),retryAfterSeconds:Yo(t.retryAfter),rateLimitRemaining:Yo(t.rateLimitRemaining),rateLimitReset:Yo(t.rateLimitReset)}}return{message:"Provider error"}}function Xo(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=IC(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 qo(e,t,n){let r=t,o=e.results;if(Array.isArray(o)){let s=o,a=mn(s);a&&(e.base=a);let c=fn(s);c&&(e.shared=c),(a||c)&&(r=[...a?["base"]:[],...c?["shared"]:[],...t])}let i=Bt(e,[...r]);return{structuredContent:Qe(Ht(e)??{}),text:i,isError:n}}import{z as $}from"zod";var OC=$.object({currentPage:$.number(),totalPages:$.number(),hasMore:$.boolean(),nextPage:$.number().optional(),pageSize:$.number().optional(),totalItems:$.number().optional(),perPage:$.number().optional(),totalFound:$.number().optional(),returned:$.number().optional(),totalMatches:$.number().optional(),reportedTotalMatches:$.number().optional().describe("Provider-reported raw total (e.g. GitHub's match count) \u2014 may exceed what pagination can actually reach."),reachableTotalMatches:$.number().optional().describe("Matches reachable by walking pages (bounded by the provider's result window, e.g. GitHub caps at 1000); totalPages is computed from this, not from reportedTotalMatches."),totalMatchesKind:$.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:$.boolean().optional(),totalResults:$.number().optional(),itemsPerPage:$.number().optional()}),TN=$.object({charOffset:$.number(),charLength:$.number(),totalChars:$.number(),hasMore:$.boolean(),nextCharOffset:$.number().optional(),currentPage:$.number().optional(),totalPages:$.number().optional(),chunkMode:$.enum(["semantic","char-limit"]).optional()}),EN=$.object({tool:$.string(),query:$.record($.string(),$.unknown()),why:$.string().optional(),confidence:$.enum(["exact","high","medium","low"]).optional()}),LN=OC.extend({filesPerPage:$.number().optional(),entriesPerPage:$.number().optional(),matchesPerPage:$.number().optional(),totalFiles:$.number().optional(),totalEntries:$.number().optional(),totalMatches:$.number().optional(),totalFilesFound:$.number().optional(),nextMatchPage:$.number().optional()}),FC=["id","mainResearchGoal","researchGoal","reasoning"];function vC(e){let t;for(let n of FC)n in e&&(t??={...e},delete t[n]);return t??e}function Rn(e,t,n="Continue to the next page of results."){return{tool:e,query:vC(t),why:n,confidence:"exact"}}function Jo(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}:{}}}}}function Zo(e){return typeof e=="object"&&e!==null}function Me(e){return typeof e=="string"&&e.length>0?e:void 0}function je(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Dp(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function $e(e,t){return je(e[t])??0}function DC(e){if(Zo(e))return{nonFile:$e(e,"nonFile"),missingDownloadUrl:$e(e,"missingDownloadUrl"),oversized:$e(e,"oversized"),binary:$e(e,"binary"),fileLimit:$e(e,"fileLimit"),fetchFailed:$e(e,"fetchFailed"),totalSizeLimit:$e(e,"totalSizeLimit"),pathTraversal:$e(e,"pathTraversal")}}function MC(e){if(Zo(e))return{maxDirectoryFiles:$e(e,"maxDirectoryFiles"),maxTotalSize:$e(e,"maxTotalSize"),maxFileSize:$e(e,"maxFileSize")}}var NC=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function GC(e){if(!Zo(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 NC){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function HC(e,t){return Jo("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 BC(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 Mp(e,t){let n=GC(e.pagination),r=!1;try{r=_l()}catch{r=!1}let o={...HC(n,t),...r?{cloneForSemantics:BC(t)}:{}};return{path:Me(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:Me(e.localPath),repoRoot:Me(e.repoRoot),contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:je(e.totalLines),sourceChars:je(e.sourceChars),resolvedBranch:Me(e.resolvedBranch),pagination:n,...Object.keys(o).length>0?{next:o}:{},...e.isPartial===!0||n?.hasMore===!0?{isPartial:!0}:{},startLine:je(e.startLine),endLine:je(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},...Array.isArray(e.matchedLines)&&e.matchedLines.length>0?{matchedLines:e.matchedLines}:{},lastModified:Me(e.lastModified),lastModifiedBy:Me(e.lastModifiedBy),warnings:Dp(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Me(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function Np(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Zo).map(c=>({path:Me(c.path)??"",size:je(c.size)??0,type:Me(c.type)??"file"})),o=DC(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:Me(e.localPath)??"",repoRoot:Me(e.repoRoot),fileCount:je(e.fileCount)??r.length,totalSize:je(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:je(e.directoryEntryCount),eligibleFileCount:je(e.eligibleFileCount),savedFileCount:je(e.savedFileCount),skipped:o,limits:MC(e.limits),warnings:Dp(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Me(e.resolvedBranch)}}function UC(e,t){return`${e}/${t}`}function QC(e,t,n){let r=UC(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 $C(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=QC(n,i,s),c=r.data;if(o.type==="directory"){let l=a.directories??[];l.push(Np(c,o)),a.directories=l;return}let u=a.files??[];u.push(Mp(c,o)),a.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function jC(e,t){return Xo(e).map(r=>{let o=t.get(r.id),s=/\b404\b|not found/i.test(r.error)&&o?.owner&&o?.repo?`${r.error} \u2014 verify the path (exact case, no leading slash) and the branch (a bad ref also 404s); list the tree with ghViewRepoStructure(owner:"${o.owner}", repo:"${o.repo}")`:r.error;return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:s}})}function Gp(){return({queries:e,results:t})=>{let n=new Map,r=Lr(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=$C(t,n),i=jC(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),qo(s,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}async function Hp(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{let s=xe(Lt,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=a.minify??(a.fullContent===!0?"none":"standard"),u={...a,minify:c},l=r();return u.type==="directory"?zC(u,n,l):WC(u,n,l)}catch(s){return ye(s,o,void 0,P.GITHUB_FETCH_CONTENT)}},{toolName:P.GITHUB_FETCH_CONTENT,finalize:Gp()},e)}async function zC(e,t,n){if(!No(n,"fetchDirectoryToDisk"))return ye(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",P.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return O("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Pe(e.owner,e.repo,t),o=await ya(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,l])=>l>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return oe(e,u,!0,P.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??N(o)})}async function WC(e,t,n){let r=await ct(e,()=>n.provider.getFileContent(Op(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await VC(e,t):void 0,i={...Fp(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 oe(e,i,s,P.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function VC(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Pe(e.owner,e.repo,t);return Ra(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function Mr(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function Bp(e,t){let n=Mr(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function Up(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 KC(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function YC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XC(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${YC(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function qC(e,t){return{...e,matches:t}}function ba(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?KC(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:XC(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:qC(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function $p(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 Qp(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 jp(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:Qp(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:Qp(r.get(i)),...s?{pagination:s}:{}}}})}function zp(e,t,n){let r=Mr(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),u=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!u)continue;let l=e.length===1?"getLines":`getLines:${i.id}`;o[l]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:u},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"low"}}return Object.keys(o).length>0?o:void 0}function Ca(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Mr(e);t.forEach((S,C)=>{if(S.status==="error")return;let x=Up(S);x.repoState&&s.push({id:S.id,state:x.repoState,query:a.get(S.id)}),x.incompleteResults&&(i=!0),x.results.reduce((_,w)=>_+w.matches.length,0)===0&&o.push({id:S.id,...x.nonExistentScope?{nonExistentScope:!0}:{},...x.incompleteResults?{incompleteResults:!0}:{}});let L=x.results;n.push({id:S.id,groups:L}),x.pagination&&r.set(S.id,x.pagination)});let c=Array.from(new Set(e.flatMap(S=>{let C=S.keywords;return Array.isArray(C)?C.filter(x=>typeof x=="string"):[]}))),u=ba($p(n),c),l=Xo(t),d=e.some(S=>S.concise===!0),m=jp(e,u,r),p=zp(m,e,c);if(d)for(let S of m)S.data.files=S.data.files.map(C=>`${C.owner}/${C.repo}:${C.path}`);let f={results:m,...p?{next:p}:{}};o.length>0&&(f.emptyQueries=o.map(({id:S,nonExistentScope:C,incompleteResults:x})=>({id:S,...C?{nonExistentScope:C}:{},...x?{incompleteResults:x}:{}}))),l.length>0&&(f.errors=l);let g=[],R=(S,C)=>{g.push(C)};i&&R("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&Bp(o,e)&&R("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let h=8,y=o.filter(({id:S,nonExistentScope:C,incompleteResults:x})=>{if(C||x)return!1;let T=a.get(S)?.keywords;return Array.isArray(T)&&T.length>h});y.length>0&&R("ghQueryPossiblyTooComplex",`Quer${y.length>1?"ies":"y"} ${y.map(S=>S.id).join(", ")} used more than ${h} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:S,state:C,query:x}of s)if(C.kind==="renamed"){let[T,L]=C.fullName.split("/");R("ghRepoRenamed",`Query ${S}: the repository was RENAMED to ${C.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let _=x?.keywords;f.next={...f.next??{},[`retryRenamed:${S}`]:{tool:"ghSearchCode",query:{owner:T,repo:L,...Array.isArray(_)?{keywords:_}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else C.kind==="archived"?R("ghRepoArchived",`Query ${S}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):R("ghRepoNotFound",`Query ${S}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`);return qo(f,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","errors"],u.length===0&&l.length>0)}}function JC(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function ZC(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 eP(e,t,n){try{let r=await U(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 Wp(e){let{queries:t}=e,n=De(e.authInfo);return ee(t,async(r,o)=>{try{let i=ZC(r);if(i)return O(i.error,r);if(!JC(r))return O("At least one search term or scope filter is required.",r);let s=n(),a=await ct(r,()=>s.provider.searchCode(Ep(r)));if(a.ok===!1)return a.result;let c=Lp(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let u=await eP(String(r.owner),String(r.repo),e.authInfo);u&&(c.repoState=u)}return oe(r,c,c.results.length>0,P.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ye(i,r,void 0,P.GITHUB_SEARCH_CODE)}},{toolName:P.GITHUB_SEARCH_CODE,finalize:Ca()},e)}var tP=/^(\d+)\s*([hdwmy])$/i;function Pa(e){let t=e.trim(),n=tP.exec(t);if(n){let r=Number(n[1]),o=n[2].toLowerCase(),i=new Date;switch(o){case"h":i.setUTCHours(i.getUTCHours()-r);break;case"d":i.setUTCDate(i.getUTCDate()-r);break;case"w":i.setUTCDate(i.getUTCDate()-r*7);break;case"m":i.setUTCMonth(i.getUTCMonth()-r);break;case"y":i.setUTCFullYear(i.getUTCFullYear()-r);break}return{value:i.toISOString()}}return Number.isNaN(Date.parse(t))?{warning:`"${e}" is not a valid date or relative window \u2014 use e.g. "30d", "2w", "6m", "1y", or an ISO date like "2026-01-01". Filter skipped.`}:{value:t}}function xa(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function wa(e,t){let n=e.map(l=>{let d=l.patch!==void 0?xa(l.patch,t.charOffset,t.charLength):void 0;return{filename:l.filename,status:l.status,additions:l.additions,deletions:l.deletions,...d!==void 0?{patch:d.patch,...d.patchPagination?{patchPagination:d.patchPagination}:{}}:{},...l.previous_filename?{previousFilename:l.previous_filename}:{}}}),r=Math.max(1,t.filePage??1),o=Math.max(1,t.itemsPerPage??20),i=n.length,s=Math.max(1,Math.ceil(i/o)),a=Math.min(r,s),c=(a-1)*o;return{files:n.slice(c,c+o),filesPagination:{currentPage:a,totalPages:s,itemsPerPage:o,totalFiles:i,hasMore:a<s,...a<s?{nextFilePage:a+1}:{}}}}var nP=5;function Sn(e){return e?e.includes('rel="next"'):!1}async function rP(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function Vp(e,t,n){let r=await pe(t),o=se("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,committer:e.committer,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return fe(o,()=>oP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function oP(e,t){try{let n=await U(t),r=[],o=e.since?Pa(e.since):void 0,i=e.until?Pa(e.until):void 0;o?.warning&&r.push(`since ${o.warning}`),i?.warning&&r.push(`until ${i.warning}`);let s={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...o?.value?{since:o.value}:{},...i?.value?{until:i.value}:{},...e.author?{author:e.author}:{},...e.committer?{committer:e.committer}:{}},a=await n.rest.repos.listCommits(s),c=a.headers.link,u=Sn(c),l=a.data.map(h=>{let y=h.commit.author,S=h.commit.committer,C=S?.date??y?.date??"",x=h.commit.message,T=x.split(`
|
|
27
|
-
`)[0]??x,L=x.slice(T.length).trim(),
|
|
28
|
-
${_?`${L.slice(0,500)}\u2026`:L}`,b=S?.name===y?.name&&S?.email===y?.email||h.committer?.login==="web-flow";return{sha:h.sha,date:C,...w===T?{}:{message:w},..._?{messageTruncated:!0}:{},messageHeadline:T,author:{name:y?.name??"unknown",email:y?.email??"",...h.author?.login?{login:h.author.login}:{}},...S&&!b?{committer:{name:S.name??"unknown",email:S.email??"",...h.committer?.login?{login:h.committer.login}:{}}}:{}}});l.length===0&&(o?.value!==void 0||i?.value!==void 0)&&r.push("no commits matched the since/until window \u2014 GitHub filters by committer date (not author date; rebases and squash-merges reset it), and a path-scoped walk does not follow renames. Widen or drop since/until and inspect commit dates directly.");let d={currentPage:e.page,perPage:e.perPage,hasMore:u,...u?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:d,...r.length?{warnings:r}:{}},status:200};let m=!1,p=!1,f=await rP(l,nP,async(h,y)=>{try{let S=a.data[y]?.sha??h.sha,C=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:S});if(e.type==="file"&&e.path){let x=e.path,T=C.data.files?.find(w=>w.filename===x||w.previous_filename===x);if(T){let w=T.patch!==void 0?xa(T.patch,e.charOffset,e.charLength):void 0;return{...h,additions:T.additions,deletions:T.deletions,status:T.status,...w!==void 0?{patch:w.patch,...w.patchPagination?{patchPagination:w.patchPagination}:{}}:{},...T.previous_filename?{previousFilename:T.previous_filename}:{}}}let L=x.endsWith("/")?x:`${x}/`,_=(C.data.files??[]).filter(w=>w.filename.startsWith(L));return _.length>0?(m=!0,{...h,...wa(_,e)}):(p=!0,h)}else{let x=e.path,T=(C.data.files??[]).filter(L=>!x||L.filename.startsWith(x));return{...h,...wa(T,e)}}}catch{}return h}),g=[];m&&g.push(`path '${e.path}' matched no single file in these commits but matches files under it \u2014 treated as a directory filter and returned per-commit changed files (append '/' to select directory mode explicitly).`),p&&g.push(`includeDiff: some commits contain no file matching '${e.path}' (rename or shallow diff?) \u2014 those commits are listed without a diff.`);let R=[...r,...g];return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:f,pagination:d,...R.length?{warnings:R}:{}},status:200}}catch(n){return W(n)}}async function Kp(e,t,n){let r=await pe(t),o=se("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,includeAssets:e.includeAssets===!0,auth:r},n);return fe(o,()=>iP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function iP(e,t){try{let n=await U(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},...e.includeAssets&&c.assets&&c.assets.length>0?{assets:c.assets.map(u=>({name:u.name,size:u.size,downloadCount:u.download_count,url:u.browser_download_url}))}:{}})),a=Sn(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 W(n)}}var sP=30;async function Yp(e,t,n){let r=t;if(!r.owner||!r.repo)return O("owner and repo are required for releases mode.",e);let o=e.limit,i=Number(typeof o=="number"?o:r.itemsPerPage)||sP,s=await Kp({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:i,includeAssets:r.includeAssets===!0},n);if(Ie(s))return O(s,e,{toolName:P.GITHUB_RELEASES});let a=s.data.releases.length>0||s.data.latest!==void 0,c=s.data.pagination?.nextPage,u={...s.data,...c!==void 0?{next:{nextPage:{tool:"ghListReleases",query:{owner:r.owner,repo:r.repo,page:c,itemsPerPage:i},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return oe(e,u,a,P.GITHUB_RELEASES,{rawResponse:s.rawResponseChars})}function Ye(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function Ta(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Ko),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function Xp(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 ei(e){return e.pull_request!=null}function aP(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function ti(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:aP(e.labels),createdAt:e.created_at??"",updatedAt:e.updated_at??"",...e.closed_at?{closedAt:e.closed_at}:{}}}function bn(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function Ea(e,t,n="anon"){return se("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:Ta(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,locked:e.locked,visibility:e.visibility,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}import{ContentSanitizer as qp}from"@octocodeai/octocode-engine/contentSanitizer";async function ni(e,t,n){try{let r=await e.rest.repos.get({owner:t,repo:n}),[o,i]=r.data.full_name?.split("/")??[];return!o||!i?{owner:t,repo:n,renamed:!1}:{owner:o,repo:i,renamed:o!==t||i!==n}}catch{return{owner:t,repo:n,renamed:!1}}}async function Jp(e,t){let n=Ye(e.owner),r=Ye(e.repo),o=e.issueNumber;if(!n||!r||o==null)return bn("owner, repo, and issueNumber are required for issue detail mode.");let i=await U(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(ei(s.data))return bn(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,u=e.content?.comments?.includeBots===!0,l=ti(s.data),d={};if(a){let m=qp.sanitizeContent(s.data.body??"").content,p=Xp(m,e.charOffset,e.charLength);l.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),f=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=u?f.data:f.data.filter(h=>!Gt(h.user?.login??""));l.comments=g.map(h=>({id:String(h.id),user:h.user?.login??"unknown",body:qp.sanitizeContent(h.body??"").content,createdAt:h.created_at??"",updatedAt:h.updated_at??"",commentType:"discussion"}));let R=Sn(f.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:l.comments.length,hasMore:R,...R?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(l.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[l],totalCount:1},status:200}}async function Zp(e,t,n){let r=Ye(t.owner)??"",o=Ye(t.repo)??"",i=await U(n),s=[],a=e;if(r&&o){let h=await ni(i,r,o);h.renamed&&(s.push(`Repository ${r}/${o} was renamed to ${h.owner}/${h.repo} \u2014 GitHub search does not follow renames, so the canonical name was searched instead.`),a={...e,owner:h.owner,repo:h.repo})}let c=Cs(a),u=Math.min(t.limit??30,100),l=t.page??1,d=t.sort&&t.sort!=="best-match"?t.sort:void 0,m=await i.rest.search.issuesAndPullRequests({q:c,sort:d,order:t.order||"desc",per_page:u,page:l}),p=Wl(m.headers);p&&s.push(p);let f=(m.data.items??[]).filter(h=>!ei(h)).map(h=>ti(h)),g=m.data.total_count??f.length,R=l*u<g&&f.length===u;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?f.map(h=>`#${h.number} ${h.title}`):f,totalCount:g,effectiveQuery:c,...s.length?{warnings:s}:{},...m.data.incomplete_results?{incompleteResults:!0}:{},pagination:{currentPage:l,perPage:u,hasMore:R,...R?{nextPage:l+1}:{},...g>1e3?{totalMatchesCapped:!0}:{}}},status:200}}async function em(e,t){let n=Ye(e.owner),r=Ye(e.repo);if(!n||!r)return bn("owner and repo are required for issues mode.");let o=await U(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),u=c.data.filter(p=>!ei(p)).map(p=>ti(p)),l=Sn(c.headers.link),d=!l&&s===1,m=[];return u.length===0&&l&&m.push("This page contained only pull requests (the GitHub issues endpoint returns both; PRs are filtered out) \u2014 follow pagination.nextPage, later pages may contain issues."),{data:{type:"issues",owner:n,repo:r,issues:e.concise?u.map(p=>`#${p.number} ${p.title}`):u,...d?{totalCount:u.length}:{},...m.length?{warnings:m}:{},pagination:{currentPage:s,perPage:i,hasMore:l,...l?{nextPage:s+1}:{}}},status:200}}async function La(e,t,n){let r=await pe(t),o=Ea(e,n,r);return fe(o,()=>cP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function cP(e,t){try{if(e.state==="merged")return bn('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await Jp(e,t);let n={...e,query:Ta(e)};return Ps(n)?await Zp(n,e,t):await em(e,t)}catch(n){return We(n)?{data:{type:"issues",owner:Ye(e.owner)??"",repo:Ye(e.repo)??"",issues:[],totalCount:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:W(n)}}async function tm(e,t,n){let r=t;if(!r.owner||!r.repo)return O("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await La({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,locked:r.locked,visibility:r.visibility,match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(Ie(i))return O(i,e,{toolName:P.GITHUB_ISSUES});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let l=a[0];if(typeof l=="number")return l;if(typeof l=="string"){let d=l.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(l&&typeof l=="object"&&typeof l.number=="number")return l.number})(),u={};return o==null&&c!=null&&(u.readIssue={tool:"ghSearchIssues",query:{owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"low"}),u.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"low"},oe(e,{...i.data,next:u},s,P.GITHUB_ISSUES,{rawResponse:i.rawResponseChars})}async function nm(e,t){try{let o=(await(await U(t)).rest.repos.compareCommitsWithBasehead({owner:e.owner,repo:e.repo,basehead:`${e.base}...${e.head}`})).data,i=(o.commits??[]).map(a=>({sha:a.sha,messageHeadline:(a.commit.message??"").split(`
|
|
29
|
-
`)[0]??"",author:
|
|
30
|
-
`).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(`
|
|
31
|
-
`)}function cm(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(ai(p))):o,a=Nr(t),c=a?s.filter(p=>Cn(ai(p),a)||Cn(p.patch,a)):s,{items:u,pagination:l}=Gr(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=u.map(p=>{let f=fP(p,!1);if(!d||typeof p.patch!="string")return f;let g=r&&!a?hP(p.patch):p.patch,R=Qt(g,t.charOffset??0,t.charLength??12e3);return{...f,patch:R?.content??"",...R?{patchPagination:R.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:l}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(ai).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function $t(e,t){return{...e,content:t}}function gP(e,t){return{...e,...t}}function um(e,t,n,r){let o=Aa(e,t);return{target:o,...n.body?{}:{getBody:$t(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:$t(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:$t(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:$t(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:$t(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:$t(o,{reviews:!0})},...n.commits?{}:{getCommits:$t(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:gP(o,{reviewMode:"full"})}}}function yP(e){return e.replace(/\n{3,}/g,`
|
|
24
|
+
`}${d}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function sa(e,t){return t?{...e,responsePagination:t}:e}var Eb=3;async function ee(e,t,n,r){let o=n.concurrency??Eb,{results:i,errors:s}=await Qd(e,t,o,n.minQueryTimeoutMs);return Lb(n,i,s,e,r)}function Lb(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length),u=Lr(r);t.forEach(R=>{let h=R.result.status;c[R.queryIndex]={id:u[R.queryIndex]??Er(R.originalQuery,R.queryIndex),...h!==void 0?{status:h}:{},data:Ab(R.result)}}),n.forEach(R=>{let h=r[R.queryIndex];h&&(c[R.queryIndex]={id:u[R.queryIndex]??Er(h,R.queryIndex),status:"error",data:{error:R.error}})});let l=c.filter(R=>R!==void 0);if(e.finalize){let R=e.finalize({queries:r,results:l,config:e}),h=ia(R.text,o),y=sa(R.structuredContent,h.pagination);return Wd(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:y,isError:R.isError??(l.length>0&&l.every(C=>C.status==="error"))}}let d={results:l};if(Array.isArray(d.results)){let R=mn(d.results);R&&(d.base=R);let h=fn(d.results);h&&(d.shared=h)}let m=Bt(d,a),p=ia(m,o),f=sa(Qe(Ht(d)??{}),p.pagination);return Wd(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(R=>R.status==="error")}}function Wd(e,t,n,r){let o=t.reduce((i,s)=>i+(te(s.result)??N(s.result)),0)+n.reduce((i,s)=>i+N(s),0);try{ns(e,o,r)}catch{}}function Ab(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 G={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"};var Vd={[G.PATH_VALIDATION_FAILED]:{code:G.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[G.FILE_ACCESS_FAILED]:{code:G.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[G.FILE_READ_FAILED]:{code:G.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[G.FILE_TOO_LARGE]:{code:G.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[G.BINARY_FILE_UNSUPPORTED]:{code:G.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[G.NO_MATCHES]:{code:G.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[G.OUTPUT_TOO_LARGE]:{code:G.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[G.COMMAND_NOT_AVAILABLE]:{code:G.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[G.COMMAND_EXECUTION_FAILED]:{code:G.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[G.COMMAND_TIMEOUT]:{code:G.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[G.TOOL_EXECUTION_FAILED]:{code:G.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[G.LSP_SERVER_UNAVAILABLE]:{code:G.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}};var Se=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Vd[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 aa(e){return e instanceof Se}function Kd(e,t=G.TOOL_EXECUTION_FAILED,n){if(aa(e))return e;if(e instanceof Error)return new Se(t,e.message,n,e);let r=String(e);return new Se(t,r,n)}function kb(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function O(e,t,n={}){let{extra:r}=n,o={status:"error"};if(kb(e))o.error=e;else if(aa(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Kd(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:Q(o,n.rawResponse)}function xe(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:O(i,t,{toolName:n.toolName})}}function oe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:Q(s,o.rawResponse)}function No(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 O(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ye(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return O(i,t,{toolName:r})}async function Te({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ye(o,t,r,e)}}function ca(e){return e.data!==void 0&&!e.error}import{maskSensitiveData as Yd}from"@octocodeai/octocode-engine/mask";var ua=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function _b(){return cs().provider??as()}function Ib(e){let t=cs(),n=t.provider??as(),{baseUrl:r,token:o}=t;try{let i=na(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=Yd(s);throw new ua(n,`Failed to initialize ${n} provider: ${a}`)}}function De(e){let t;return()=>t??=Ib(e)}function Go(e,t){return e.capabilities[t]}async function ct(e,t){let n=await t();return ca(n)?{ok:!0,response:n}:{ok:!1,result:No(n,e)}}async function Xd(e,t){let n=t??_b(),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:Yd(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)ca(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}import{existsSync as Jb,mkdirSync as pa,renameSync as Zb,rmSync as eC}from"fs";import{join as vr}from"path";import{createHash as tC}from"crypto";var Ho=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Ar=[...Ho,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],qd=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function Jd(e={},t=Ho){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}import{spawn as Ob}from"child_process";var Fb=10*1024*1024,vb=5e3;function kr(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Ho,maxOutputSize:a=Fb}=n;return new Promise(c=>{let u={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},l=()=>u.stdoutChunks.join(""),d=()=>u.stderrChunks.join(""),m={cwd:o,env:Jd(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=Ob(e,t,m)}catch(y){c({stdout:"",stderr:"",exitCode:null,success:!1,error:y instanceof Error?y:new Error(`Failed to spawn command '${e}'`)});return}let f,g=setTimeout(()=>{if(!u.killed){u.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},vb),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),R=()=>{clearTimeout(g),f!==void 0&&(clearTimeout(f),f=void 0)},h=()=>{if(u.totalOutputSize>a){if(!u.killed){u.killed=!0;try{p.kill("SIGKILL")}catch{}R(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stdoutChunks.push(S)}),p.stderr?.on("data",y=>{if(u.killed)return;let S=y.toString();u.totalOutputSize+=Buffer.byteLength(S),!h()&&u.stderrChunks.push(S)}),p.on("close",y=>{u.killed||(R(),c({stdout:l(),stderr:d(),exitCode:y,success:y===0}))}),p.on("error",y=>{u.killed||(u.killed=!0,R(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:y}))})})}var fM=1*1024*1024;function Zd(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}}import{existsSync as Fr,readFileSync as Mb,writeFileSync as Nb,mkdirSync as Gb,rmSync as Or,readdirSync as Hb,statSync as Bb}from"node:fs";import{join as Ct}from"node:path";import{join as Bo}from"node:path";import{createHash as ep}from"node:crypto";function Uo(e){return Bo(e,"tmp","clone")}function Qo(e){return Bo(e,"tmp","tree")}function Db(e){return e?`__sp_${ep("sha256").update(e).digest("hex").substring(0,6)}`:""}function tp(e){if(!/[\\/]/.test(e))return e;let t=ep("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function la(e,t,n,r,o){let i=`${tp(r)}${Db(o)}`;return Bo(Uo(e),t,n,i)}function _r(e,t,n,r){return Bo(Qo(e),t,n,tp(r))}var Ub=1440*60*1e3,LM=600*1e3,Qb=2*1024*1024*1024,$b=50,rp=".octocode-clone-meta.json";function jb(e){return typeof e=="object"&&e!==null}function zb(e){if(!jb(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 da(e){let t=Ct(e,rp);if(!Fr(t))return null;try{return zb(JSON.parse(Mb(t,"utf-8")))}catch{return null}}function hn(e,t){try{Nb(Ct(e,rp),JSON.stringify(t,null,2),"utf-8")}catch{}}function op(e){return Date.now()<new Date(e.expiresAt).getTime()}function gn(e){let t=da(e);return t?op(t)?Fr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Wb(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Ub}function Vb(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Qb}function Kb(){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 $b}function yn(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Wb()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function Pt(e){let t=Ct(e,"..");try{Fr(t)||Gb(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 $o(e){try{Fr(e)&&Or(e,{recursive:!0,force:!0})}catch{}}function Ir(e){try{return Bb(e).isDirectory()}catch{return!1}}function Ut(e){try{return Hb(e)}catch{return[]}}function*ip(e){for(let t of Ut(e)){let n=Ct(e,t);if(Ir(n))for(let r of Ut(n)){let o=Ct(n,r);if(Ir(o))for(let i of Ut(o)){let s=Ct(o,i);Ir(s)&&(yield s)}}}}function np(e){for(let t of[...Ut(e)]){let n=Ct(e,t);if(Ir(n)){for(let r of[...Ut(n)]){let o=Ct(n,r);if(Ir(o)&&Ut(o).length===0)try{Or(o,{recursive:!0,force:!0})}catch{}}if(Ut(n).length===0)try{Or(n,{recursive:!0,force:!0})}catch{}}}}function Yb(e){let t=0;for(let n of ip(e))try{let r=da(n);(!r||!op(r))&&(Or(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Xb(e){let t=[];for(let n of ip(e)){let r=da(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??mo(n)})}return t}function qb(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{Or(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function sp(e){if(!Fr(e))return 0;let t=0;try{t+=Yb(e)}catch{return t}np(e);let n=qb(Xb(e),Vb(),Kb());return t+=n,n>0&&np(e),t}function ap(e){return sp(Uo(e))}function jo(e){return sp(Qo(e))}var cp=120*1e3,nC=30*1e3,rC=300*1e3,oC=100,up="clone-locks",iC="clone-tmp",lp=[...Ar,"GIT_TERMINAL_PROMPT"];async function dp(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await fC();let a=e.branch??await Pe(r,o,t),c=rn(),u=la(c,r,o,a,i);return sC(c,u,async()=>{let l=gn(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};ap(c),Pt(u);let d=mC(t,n),m=cC(c,u);$o(m);try{if(i){if(await pC(r,o,a,m,i,d),!Jb(vr(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 dC(r,o,a,m,d);let p=yn(r,o,a,"clone",i);return hn(m,p),uC(m,u),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(p){throw $o(m),p}})}async function sC(e,t,n){Pt(t);let r=aC(e,t);pa(vr(e,"tmp",up),{recursive:!0,mode:448});let o=Date.now();for(;;)try{pa(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>rC)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await lC(oC)}try{return await n()}finally{eC(r,{recursive:!0,force:!0})}}function pp(e){return tC("sha256").update(e).digest("hex").slice(0,16)}function aC(e,t){return vr(e,"tmp",up,pp(t))}function cC(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=vr(e,"tmp",iC);return pa(r,{recursive:!0,mode:448}),vr(r,`${pp(t)}-${n}`)}function uC(e,t){$o(t),Pt(t),Zb(e,t)}function lC(e){return new Promise(t=>setTimeout(t,e))}async function dC(e,t,n,r,o){let i=fp(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",mp(e,t),r),await ma(i,cp,`full clone of ${e}/${t}`,o)}async function pC(e,t,n,r,o,i){let s=fp(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",mp(e,t),r),await ma(s,cp,`sparse clone of ${e}/${t}`,i),await ma(["-C",r,"sparse-checkout","set","--skip-checks","--",o],nC,`sparse-checkout set ${o}`,void 0)}function mp(e,t){return`https://github.com/${e}/${t}.git`}function fp(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function mC(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function fC(){try{if(!(await kr("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:lp,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 hC(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 ma(e,t,n,r){let o=await kr("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:lp,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=hC(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}async function hp(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>Te({toolName:P.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Go(s,"cloneRepo"))return ye(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",P.GITHUB_CLONE_REPO);let a;try{a=await dp(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return O(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=Nd(a.localPath),u={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},l={viewStructure:{tool:"localViewStructure",query:{path:a.localPath},why:"Browse the cloned directory; once you know what to search for, call localSearchCode with real keywords against this localPath",confidence:"exact"}},d={owner:o.owner,repo:o.repo,totalSize:c,location:u,next:l};return oe(o,d,!0,P.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:P.GITHUB_CLONE_REPO,keysPriority:["totalSize","location","error"]},e)}import{readdirSync as gC,statSync as gp}from"node:fs";import{join as yC}from"node:path";var Dr=50,zo=5*1024*1024,fa=300*1024,yp=5,RC=1e4,Rp=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"]),ha={maxDirectoryFiles:Dr,maxTotalSize:zo,maxFileSize:fa};function ga(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function Sp(e){return Object.values(e).every(t=>t===0)}function ya(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 bp(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 bC(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var SC=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function bC(e,t){try{let o=new URL(e);if(!SC.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(),RC);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 Cp(e,t){let n=[],r=0;function o(i){let s;try{s=gC(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=yC(i,a);try{let u=gp(c);if(u.isDirectory())o(c);else if(u.isFile()){let l=c.substring(t.length+1);r+=u.size,n.push({path:l,size:u.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function Pp(e){try{return gp(e).size}catch{return 0}}import{writeFileSync as CC,mkdirSync as xp,existsSync as Ra,rmSync as PC}from"node:fs";import{join as wp,dirname as xC,resolve as Tp,sep as Ep}from"node:path";async function Sa(e,t,n,r,o,i=!1){let s=rn(),a=_r(s,e,t,r),c=Tp(wp(a,n));if(!c.startsWith(a+Ep)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=gn(a);if(u.hit&&!i&&Ra(c)){let b=Cp(c,a),A=ga();return{localPath:c,repoRoot:a,files:b.files,fileCount:b.fileCount,totalSize:b.totalSize,complete:!0,verified:!1,...u.meta.commitSha?{commitSha:u.meta.commitSha}:{},directoryEntryCount:b.fileCount,eligibleFileCount:b.fileCount,savedFileCount:b.fileCount,skipped:A,limits:ha,warnings:ya(!0,!1),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await U(o),d;try{d=(await l.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:m}=await l.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(m))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let p=m,f=ga(),g=[];for(let b of p){if(b.type!=="file"){f.nonFile+=1;continue}if(!b.download_url){f.missingDownloadUrl+=1;continue}if(b.size>fa){f.oversized+=1;continue}let A=zl(b.name,{lowercase:!0,leadingDot:!0});if(Rp.has(A)){f.binary+=1;continue}g.push(b)}f.fileLimit=Math.max(0,g.length-Dr);let R=g.slice(0,Dr),h=o?.token,y=await bp(R,yp,h);f.fetchFailed=R.length-y.length;let S=0,C=[];for(let b=0;b<y.length;b+=1){let{entry:A,content:M}=y[b];if(S+M.length>zo){f.totalSizeLimit=y.length-b;break}S+=M.length,C.push({entry:A,content:M})}jo(s),Pt(a),Ra(c)&&PC(c,{recursive:!0,force:!0}),xp(c,{recursive:!0,mode:448});let x=[];for(let{entry:b,content:A}of C){let M=Tp(wp(a,b.path));if(!M.startsWith(a+Ep)){f.pathTraversal+=1;continue}let H=xC(M);Ra(H)||xp(H,{recursive:!0,mode:448}),CC(M,A,"utf-8"),x.push({path:b.path,size:A.length,type:"file"})}let T=yn(e,t,r,"treeFetch",void 0,void 0,d);hn(a,T);let L=Sp(f),k=L,w=f.nonFile>0;return{localPath:c,repoRoot:a,files:x,fileCount:x.length,totalSize:S,complete:L,verified:k,...d?{commitSha:d}:{},...w?{hasSubdirectories:!0}:{},directoryEntryCount:p.length,eligibleFileCount:g.length,savedFileCount:x.length,skipped:f,limits:ha,warnings:ya(L,k),cached:!1,expiresAt:T.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}import{writeFileSync as wC,mkdirSync as TC,existsSync as Lp}from"node:fs";import{join as EC,dirname as LC,resolve as AC,sep as kC}from"node:path";async function ba(e,t,n,r,o,i=!1){let s=rn(),a=_r(s,e,t,r),c=AC(EC(a,n));if(!c.startsWith(a+kC)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=gn(a);if(!i&&u.hit&&Lp(c))return{localPath:c,repoRoot:a,path:n,size:Pp(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await Sr({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in l)||!l.data){let f="error"in l?l.error:void 0;throw new Error(f||`Failed to fetch ${e}/${t}/${n}`)}jo(s),Pt(a);let d=LC(c);Lp(d)||TC(d,{recursive:!0,mode:448}),wC(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,p=yn(e,t,m,"treeFetch");return hn(a,p),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}function Wo(e,t){return e&&t?`${e}/${t}`:void 0}function Vo(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function Ko(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function IC(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 Ap(e){return{keywords:e.keywords??[],projectId:Wo(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 kp(e,t){let n=t.match==="path",r=new Map;for(let i of e.items){let s=i.repository.name||"",{owner:a,repo:c}=Vo(s),u=`${a}/${c}`,l=r.get(u);if(l||(l={id:u,owner:a,repo:c,matches:[]},r.set(u,l)),n||!i.matches?.length){l.matches.push({path:i.path,...n?{}:{pathOnly:!0}});continue}let d=!1;for(let m of i.matches){if(!m.context)continue;let p=IC(m.context),f={path:i.path,value:p};if(m.positions?.length>0){let g=m.positions.filter(([,R])=>R<=p.length);g.length>0&&(f.matchIndices=g.map(([R,h])=>({start:R,end:h,lineOffset:(m.context??"").substring(0,R).split(`
|
|
26
|
+
`).length-1})))}l.matches.push(f),d=!0}d||l.matches.push({path:i.path,pathOnly:!0})}let o={results:Array.from(r.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(o.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...Ko(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),o}function _p(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,license:t.license,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Ip(e){return e.map(t=>{let{owner:n,repo:r}=Vo(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function Yo(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Op(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Yo),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Wo(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,draft:e.draft,match:e.match,checks:e.checks,review:e.review,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function OC(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=>!Gt(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 FC(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:OC(e,t??[])}}function Fp(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,u=FC(c,i.reviews);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(l=>({...l,...l.bodyPagination&&{bodyPagination:l.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...u&&{reviewSummary:u},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...Ko(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pullRequests:r,...e.effectiveQuery?{effectiveQuery:e.effectiveQuery}:{},...o?{pagination:o}:{totalCount:e.totalCount||r.length}},pagination:o}}function vp(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 Dp(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.matchedLines?.length&&{matchedLines:e.matchedLines},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function Ca(e,t){let n=e.include??[];return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??bt.ENTRIES_PER_PAGE,page:(()=>{let r=e.page;return typeof r=="number"?r:void 0})(),includeSizes:n.includes("sizes"),includeLanguages:n.includes("languages"),includeContributors:n.includes("contributors"),includeBranches:n.includes("branches"),includeTags:n.includes("tags"),mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Mp(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([p],[f])=>p==="."?-1:f==="."?1:p.localeCompare(f)).map(([p,f])=>({dir:p,files:f.files,folders:f.folders})),c=e.fileSizeMap,u={};if(c){for(let[p,f]of Object.entries(c))if(n[p]){let g=new Set(n[p].files);for(let[R,h]of Object.entries(f))if(g.has(R)){let y=p==="."?R:`${p}/${R}`;u[y]=h}}}let l=Object.values(n).reduce((p,f)=>(p.totalFiles+=f.files.length,p.totalFolders+=f.folders.length,p),{totalFiles:0,totalFolders:0}),d=e,m={structure:a,...Object.keys(u).length>0&&{fileSizes:u},...d.languages?{languages:d.languages,dominantLanguage:d.dominantLanguage}:{},...d.contributors?{contributors:d.contributors,totalContributors:d.contributors.length}:{},...d.branches?{branches:d.branches,totalBranches:d.branches.length}:{},...d.tags?{tags:d.tags,totalTags:d.tags.length}:{},summary:{totalFiles:l.totalFiles,totalFolders:l.totalFolders}};return i&&(m.resolvedBranch=i),s&&(m.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(m.pagination=e.pagination),m}function Xo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function vC(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:Xo(t.status),retryAfterSeconds:Xo(t.retryAfter),rateLimitRemaining:Xo(t.rateLimitRemaining),rateLimitReset:Xo(t.rateLimitReset)}}return{message:"Provider error"}}function qo(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=vC(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 Jo(e,t,n){let r=t,o=e.results;if(Array.isArray(o)){let s=o,a=mn(s);a&&(e.base=a);let c=fn(s);c&&(e.shared=c),(a||c)&&(r=[...a?["base"]:[],...c?["shared"]:[],...t])}let i=Bt(e,[...r]);return{structuredContent:Qe(Ht(e)??{}),text:i,isError:n}}import{z as $}from"zod";var DC=$.object({currentPage:$.number(),totalPages:$.number(),hasMore:$.boolean(),nextPage:$.number().optional(),pageSize:$.number().optional(),totalItems:$.number().optional(),perPage:$.number().optional(),totalFound:$.number().optional(),returned:$.number().optional(),totalMatches:$.number().optional(),reportedTotalMatches:$.number().optional().describe("Provider-reported raw total (e.g. GitHub's match count) \u2014 may exceed what pagination can actually reach."),reachableTotalMatches:$.number().optional().describe("Matches reachable by walking pages (bounded by the provider's result window, e.g. GitHub caps at 1000); totalPages is computed from this, not from reportedTotalMatches."),totalMatchesKind:$.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:$.boolean().optional(),totalResults:$.number().optional(),itemsPerPage:$.number().optional()}),HN=$.object({charOffset:$.number(),charLength:$.number(),totalChars:$.number(),hasMore:$.boolean(),nextCharOffset:$.number().optional(),currentPage:$.number().optional(),totalPages:$.number().optional(),chunkMode:$.enum(["semantic","char-limit"]).optional()}),BN=$.object({tool:$.string(),query:$.record($.string(),$.unknown()),why:$.string().optional(),confidence:$.enum(["exact","high","medium","low"]).optional()}),UN=DC.extend({filesPerPage:$.number().optional(),entriesPerPage:$.number().optional(),matchesPerPage:$.number().optional(),totalFiles:$.number().optional(),totalEntries:$.number().optional(),totalMatches:$.number().optional(),totalFilesFound:$.number().optional(),nextMatchPage:$.number().optional()}),MC=["id","mainResearchGoal","researchGoal","reasoning"];function NC(e){let t;for(let n of MC)n in e&&(t??={...e},delete t[n]);return t??e}function Rn(e,t,n="Continue to the next page of results."){return{tool:e,query:NC(t),why:n,confidence:"exact"}}function Zo(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 GC=["package.json",".yarnrc.yml","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","turbo.json","lerna.json","nx.json","babel.config.js","vite.config.ts","vite.config.js","webpack.config.js","rollup.config.js","jest.config.js","vitest.config.ts","commitlint.config.js","deno.json","deno.jsonc",".npmrc",".nvmrc",".node-version",".prettierrc",".prettierignore",".eslintignore",".stylelintrc",".editorconfig",".tool-versions","requirements.txt","pyproject.toml","setup.py","setup.cfg","Pipfile","tox.ini","environment.yml",".python-version","Gemfile",".ruby-version","composer.json","Cargo.toml","go.mod","go.work","mix.exs","rebar.config","pubspec.yaml","build.sbt","deps.edn","project.clj","Package.swift","CMakeLists.txt","Makefile.am","configure.ac","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","global.json","Directory.Build.props","Directory.Build.targets","packages.config","nuget.config","Dockerfile","docker-compose.yml","docker-compose.yaml",".dockerignore","Makefile","Vagrantfile","Chart.yaml","Procfile","Brewfile","serverless.yml","netlify.toml","vercel.json","renovate.json",".gitlab-ci.yml",".travis.yml","Jenkinsfile",".gitignore",".gitattributes",".gitmodules",".env",".env.example"],HC=new Set(GC),BC=["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","deno.lock","Pipfile.lock","poetry.lock","uv.lock","pdm.lock","pixi.lock","Gemfile.lock","composer.lock","Cargo.lock","Cargo.toml.orig","go.sum","Gopkg.lock","glide.lock","Package.resolved","pubspec.lock","flake.lock","MODULE.bazel.lock",".terraform.lock.hcl","mise.lock"],UC=new Set(BC),QC=[/\.lock$/],$C=[/^\.eslintrc(\..+)?$/,/^\.prettierrc(\..+)?$/,/^\.babelrc(\..+)?$/,/^eslint\.config\.(c|m)?js$/,/^\.env(\..+)?$/,/^tsconfig\..+\.json$/,/^\.stylelintrc(\..+)?$/,/^\.renovaterc(\..+)?$/,/\.csproj$/,/\.fsproj$/,/\.vbproj$/,/\.sln$/,/\.gemspec$/,/\.tf(vars)?$/],jC=[".toml",".ini",".cfg",".conf",".properties"],Gp=new Set(jC),zC=new Set(".md .mdx .markdown .rst .adoc .asciidoc .txt .text .rtf .org .textile .rdoc .pod .creole .wiki".split(" ")),Np=new Set(["readme","license","licence","copying","notice","changelog","changes","history","authors","contributors","contributing","code_of_conduct","codeowners","install","citation"]),Hp=new Set(".js .jsx .mjs .cjs .ts .tsx .mts .cts .py .pyi .pyx .rb .rake .php .go .rs .java .kt .kts .scala .groovy .clj .cljs .cljc .c .h .cc .cpp .cxx .hpp .hh .m .mm .cs .fs .vb .swift .dart .sh .bash .zsh .fish .ps1 .bat .cmd .vue .svelte .css .scss .sass .less .html .htm .sql .graphql .gql .proto .ex .exs .erl .lua .hs .pl .pm .r .jl".split(" "));function Pa(e){let t=e.replace(/\\/g,"/"),n=t.lastIndexOf("/");return n===-1?t:t.slice(n+1)}function xa(e){let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""}function WC(e){if(!e)return!1;let t=Pa(e);if(!t)return!1;if(HC.has(t))return!0;for(let r of $C)if(r.test(t))return!0;let n=xa(t);return!!(n&&Gp.has(n))}function VC(e){if(!e)return!1;let t=Pa(e);if(!t)return!1;if(UC.has(t))return!0;for(let n of QC)if(n.test(t))return!0;return!1}function KC(e){let t=xa(e);if(t&&zC.has(t))return!0;if(t&&(Hp.has(t)||Gp.has(t)))return!1;let n=(t?e.slice(0,e.length-t.length):e).toLowerCase().replace(/\..*$/,""),r=n.split(/[-_.]/)[0]??n;return Np.has(n)||Np.has(r)}function YC(e){let t=xa(e);return t!==""&&Hp.has(t)}function ei(e){if(!e)return;let t=Pa(e);if(t){if(VC(t))return"lock";if(WC(t))return"config";if(KC(t))return"doc";if(YC(t))return"code"}}function ti(e){return typeof e=="object"&&e!==null}function Me(e){return typeof e=="string"&&e.length>0?e:void 0}function je(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Bp(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function $e(e,t){return je(e[t])??0}function XC(e){if(ti(e))return{nonFile:$e(e,"nonFile"),missingDownloadUrl:$e(e,"missingDownloadUrl"),oversized:$e(e,"oversized"),binary:$e(e,"binary"),fileLimit:$e(e,"fileLimit"),fetchFailed:$e(e,"fetchFailed"),totalSizeLimit:$e(e,"totalSizeLimit"),pathTraversal:$e(e,"pathTraversal")}}function qC(e){if(ti(e))return{maxDirectoryFiles:$e(e,"maxDirectoryFiles"),maxTotalSize:$e(e,"maxTotalSize"),maxFileSize:$e(e,"maxFileSize")}}var JC=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function ZC(e){if(!ti(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 JC){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function eP(e,t){return Zo("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 tP(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 Up(e,t){let n=ZC(e.pagination),r=!1;try{r=Il()}catch{r=!1}let o={...eP(n,t),...r?{cloneForSemantics:tP(t)}:{}},i=Me(e.path)??String(t.path??""),s=i?ei(i):void 0;return{path:i,content:typeof e.content=="string"?e.content:"",...s?{fileType:s}:{},localPath:Me(e.localPath),repoRoot:Me(e.repoRoot),contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:je(e.totalLines),sourceChars:je(e.sourceChars),resolvedBranch:Me(e.resolvedBranch),pagination:n,...Object.keys(o).length>0?{next:o}:{},...e.isPartial===!0||n?.hasMore===!0?{isPartial:!0}:{},startLine:je(e.startLine),endLine:je(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},...Array.isArray(e.matchedLines)&&e.matchedLines.length>0?{matchedLines:e.matchedLines}:{},lastModified:Me(e.lastModified),lastModifiedBy:Me(e.lastModifiedBy),warnings:Bp(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Me(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function Qp(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(ti).map(c=>({path:Me(c.path)??"",size:je(c.size)??0,type:Me(c.type)??"file"})),o=XC(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:Me(e.localPath)??"",repoRoot:Me(e.repoRoot),fileCount:je(e.fileCount)??r.length,totalSize:je(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:je(e.directoryEntryCount),eligibleFileCount:je(e.eligibleFileCount),savedFileCount:je(e.savedFileCount),skipped:o,limits:qC(e.limits),warnings:Bp(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Me(e.resolvedBranch)}}function nP(e,t){return`${e}/${t}`}function rP(e,t,n){let r=nP(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 oP(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=rP(n,i,s),c=r.data;if(o.type==="directory"){let l=a.directories??[];l.push(Qp(c,o)),a.directories=l;return}let u=a.files??[];u.push(Up(c,o)),a.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function iP(e,t){return qo(e).map(r=>{let o=t.get(r.id),s=/\b404\b|not found/i.test(r.error)&&o?.owner&&o?.repo?`${r.error} \u2014 verify the path (exact case, no leading slash) and the branch (a bad ref also 404s); list the tree with ghViewRepoStructure(owner:"${o.owner}", repo:"${o.repo}")`:r.error;return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:s}})}function $p(){return({queries:e,results:t})=>{let n=new Map,r=Lr(e);e.forEach((a,c)=>{n.set(r[c],a)});let o=oP(t,n),i=iP(t,n),s={results:o};return i&&i.length>0&&(s.errors=i),Jo(s,["results","id","owner","repo","files","directories","path","content","fileType","totalLines","startLine","endLine","isPartial","pagination","errors"],o.length===0&&!!(i&&i.length>0))}}async function jp(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{let s=xe(Lt,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=a.minify??(a.fullContent===!0?"none":"standard"),u={...a,minify:c},l=r();return u.type==="directory"?sP(u,n,l):aP(u,n,l)}catch(s){return ye(s,o,void 0,P.GITHUB_FETCH_CONTENT)}},{toolName:P.GITHUB_FETCH_CONTENT,finalize:$p()},e)}async function sP(e,t,n){if(!Go(n,"fetchDirectoryToDisk"))return ye(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",P.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return O("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await Pe(e.owner,e.repo,t),o=await Sa(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,l])=>l>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,...s&&Object.keys(s).length>0?{skipped:o.skipped}:{},limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return oe(e,u,!0,P.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??N(o)})}async function aP(e,t,n){let r=await ct(e,()=>n.provider.getFileContent(vp(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await cP(e,t):void 0,i={...Dp(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 oe(e,i,s,P.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function cP(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Pe(e.owner,e.repo,t);return ba(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function Mr(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function zp(e,t){let n=Mr(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function Wp(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 uP(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function lP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dP(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${lP(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function pP(e,t){return{...e,matches:t}}function wa(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?uP(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:dP(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:pP(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function Kp(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 Vp(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 Yp(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:Vp(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:Vp(r.get(i)),...s?{pagination:s}:{}}}})}function Xp(e,t,n){let r=Mr(t),o={};for(let i of e){let s=i.data.files[0];if(!s)continue;let a=r.get(i.id),u=(Array.isArray(a?.keywords)?a.keywords.filter(d=>typeof d=="string"):[])[0]??n[0];if(!u)continue;let l=e.length===1?"getLines":`getLines:${i.id}`;o[l]={tool:"ghGetFileContent",query:{owner:s.owner,repo:s.repo,path:s.path,matchString:u},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"low"}}return Object.keys(o).length>0?o:void 0}function Ta(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1,s=[],a=Mr(e);t.forEach((S,C)=>{if(S.status==="error")return;let x=Wp(S);x.repoState&&s.push({id:S.id,state:x.repoState,query:a.get(S.id)}),x.incompleteResults&&(i=!0),x.results.reduce((k,w)=>k+w.matches.length,0)===0&&o.push({id:S.id,...x.nonExistentScope?{nonExistentScope:!0}:{},...x.incompleteResults?{incompleteResults:!0}:{}});let L=x.results;n.push({id:S.id,groups:L}),x.pagination&&r.set(S.id,x.pagination)});let c=Array.from(new Set(e.flatMap(S=>{let C=S.keywords;return Array.isArray(C)?C.filter(x=>typeof x=="string"):[]}))),u=wa(Kp(n),c),l=qo(t),d=e.some(S=>S.concise===!0),m=Yp(e,u,r),p=Xp(m,e,c);if(d)for(let S of m)S.data.files=S.data.files.map(C=>`${C.owner}/${C.repo}:${C.path}`);let f={results:m,...p?{next:p}:{}};o.length>0&&(f.emptyQueries=o.map(({id:S,nonExistentScope:C,incompleteResults:x})=>({id:S,...C?{nonExistentScope:C}:{},...x?{incompleteResults:x}:{}}))),l.length>0&&(f.errors=l);let g=[],R=(S,C)=>{g.push(C)};i&&R("ghIncompleteResults","GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."),o.length>0&&zp(o,e)&&R("ghScopedZeroUnproven","GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding.");let h=8,y=o.filter(({id:S,nonExistentScope:C,incompleteResults:x})=>{if(C||x)return!1;let T=a.get(S)?.keywords;return Array.isArray(T)&&T.length>h});y.length>0&&R("ghQueryPossiblyTooComplex",`Quer${y.length>1?"ies":"y"} ${y.map(S=>S.id).join(", ")} used more than ${h} keywords and returned zero results. GitHub code search can silently under-match an overly long/complex query instead of erroring \u2014 narrow to fewer, more specific keywords before concluding absence.`);for(let{id:S,state:C,query:x}of s)if(C.kind==="renamed"){let[T,L]=C.fullName.split("/");R("ghRepoRenamed",`Query ${S}: the repository was RENAMED to ${C.fullName} \u2014 searches against the old name silently miss. Retry with the new name (see next.retryRenamed).`);let k=x?.keywords;f.next={...f.next??{},[`retryRenamed:${S}`]:{tool:"ghSearchCode",query:{owner:T,repo:L,...Array.isArray(k)?{keywords:k}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"}}}else C.kind==="archived"?R("ghRepoArchived",`Query ${S}: the repository is ARCHIVED \u2014 the code-search index may lag or exclude it; zero matches is not proof of absence. Materialize the repo and search locally to verify.`):R("ghRepoNotFound",`Query ${S}: the repository was NOT FOUND \u2014 it does not exist (or is private to this token). Check the owner/repo spelling.`);return Jo(f,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","emptyQueries","nonExistentScope","incompleteResults","errors"],u.length===0&&l.length>0)}}function mP(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function fP(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 hP(e,t,n){try{let r=await U(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 qp(e){let{queries:t}=e,n=De(e.authInfo);return ee(t,async(r,o)=>{try{let i=fP(r);if(i)return O(i.error,r);if(!mP(r))return O("At least one search term or scope filter is required.",r);let s=n(),a=await ct(r,()=>s.provider.searchCode(Ap(r)));if(a.ok===!1)return a.result;let c=kp(a.response.data,r);if(c.results.length===0&&r.owner&&r.repo){let u=await hP(String(r.owner),String(r.repo),e.authInfo);u&&(c.repoState=u)}return oe(r,c,c.results.length>0,P.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ye(i,r,void 0,P.GITHUB_SEARCH_CODE)}},{toolName:P.GITHUB_SEARCH_CODE,finalize:Ta()},e)}var gP=/^(\d+)\s*([hdwmy])$/i;function Ea(e){let t=e.trim(),n=gP.exec(t);if(n){let r=Number(n[1]),o=n[2].toLowerCase(),i=new Date;switch(o){case"h":i.setUTCHours(i.getUTCHours()-r);break;case"d":i.setUTCDate(i.getUTCDate()-r);break;case"w":i.setUTCDate(i.getUTCDate()-r*7);break;case"m":i.setUTCMonth(i.getUTCMonth()-r);break;case"y":i.setUTCFullYear(i.getUTCFullYear()-r);break}return{value:i.toISOString()}}return Number.isNaN(Date.parse(t))?{warning:`"${e}" is not a valid date or relative window \u2014 use e.g. "30d", "2w", "6m", "1y", or an ISO date like "2026-01-01". Filter skipped.`}:{value:t}}function La(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Nr(e,t){let n=e.map(l=>{let d=l.patch!==void 0?La(l.patch,t.charOffset,t.charLength):void 0;return{filename:l.filename,status:l.status,additions:l.additions,deletions:l.deletions,...d!==void 0?{patch:d.patch,...d.patchPagination?{patchPagination:d.patchPagination}:{}}:{},...l.previous_filename?{previousFilename:l.previous_filename}:{}}}),r=Math.max(1,t.filePage??1),o=Math.max(1,t.itemsPerPage??20),i=n.length,s=Math.max(1,Math.ceil(i/o)),a=Math.min(r,s),c=(a-1)*o;return{files:n.slice(c,c+o),filesPagination:{currentPage:a,totalPages:s,itemsPerPage:o,totalFiles:i,hasMore:a<s,...a<s?{nextFilePage:a+1}:{}}}}var yP=5;function Sn(e){return e?e.includes('rel="next"'):!1}async function RP(e,t,n){if(e.length===0)return[];let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let s=o++;if(s>=e.length)return;r[s]=await n(e[s],s)}});return await Promise.all(i),r}async function Jp(e,t,n){let r=await pe(t),o=se("gh-api-history",{type:e.type,owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,since:e.since,until:e.until,author:e.author,committer:e.committer,page:e.page,perPage:e.perPage,filePage:e.filePage,itemsPerPage:e.itemsPerPage,includeDiff:e.includeDiff,charOffset:e.charOffset,charLength:e.charLength,auth:r},n);return fe(o,()=>SP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function SP(e,t){try{let n=await U(t),r=[],o=e.since?Ea(e.since):void 0,i=e.until?Ea(e.until):void 0;o?.warning&&r.push(`since ${o.warning}`),i?.warning&&r.push(`until ${i.warning}`);let s={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...o?.value?{since:o.value}:{},...i?.value?{until:i.value}:{},...e.author?{author:e.author}:{},...e.committer?{committer:e.committer}:{}},a=await n.rest.repos.listCommits(s),c=a.headers.link,u=Sn(c),l=a.data.map(h=>{let y=h.commit.author,S=h.commit.committer,C=S?.date??y?.date??"",x=h.commit.message,T=x.split(`
|
|
27
|
+
`)[0]??x,L=x.slice(T.length).trim(),k=L.length>500,w=L.length===0?T:`${T}
|
|
28
|
+
${k?`${L.slice(0,500)}\u2026`:L}`,b=S?.name===y?.name&&S?.email===y?.email||h.committer?.login==="web-flow";return{sha:h.sha,date:C,...w===T?{}:{message:w},...k?{messageTruncated:!0}:{},messageHeadline:T,author:{name:y?.name??"unknown",email:y?.email??"",...h.author?.login?{login:h.author.login}:{}},...S&&!b?{committer:{name:S.name??"unknown",email:S.email??"",...h.committer?.login?{login:h.committer.login}:{}}}:{}}});l.length===0&&(o?.value!==void 0||i?.value!==void 0)&&r.push("no commits matched the since/until window \u2014 GitHub filters by committer date (not author date; rebases and squash-merges reset it), and a path-scoped walk does not follow renames. Widen or drop since/until and inspect commit dates directly.");let d={currentPage:e.page,perPage:e.perPage,hasMore:u,...u?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:d,...r.length?{warnings:r}:{}},status:200};let m=!1,p=!1,f=await RP(l,yP,async(h,y)=>{try{let S=a.data[y]?.sha??h.sha,C=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:S});if(e.type==="file"&&e.path){let x=e.path,T=C.data.files?.find(w=>w.filename===x||w.previous_filename===x);if(T){let w=T.patch!==void 0?La(T.patch,e.charOffset,e.charLength):void 0;return{...h,additions:T.additions,deletions:T.deletions,status:T.status,...w!==void 0?{patch:w.patch,...w.patchPagination?{patchPagination:w.patchPagination}:{}}:{},...T.previous_filename?{previousFilename:T.previous_filename}:{}}}let L=x.endsWith("/")?x:`${x}/`,k=(C.data.files??[]).filter(w=>w.filename.startsWith(L));return k.length>0?(m=!0,{...h,...Nr(k,e)}):(p=!0,h)}else{let x=e.path,T=(C.data.files??[]).filter(L=>!x||L.filename.startsWith(x));return{...h,...Nr(T,e)}}}catch{}return h}),g=[];m&&g.push(`path '${e.path}' matched no single file in these commits but matches files under it \u2014 treated as a directory filter and returned per-commit changed files (append '/' to select directory mode explicitly).`),p&&g.push(`includeDiff: some commits contain no file matching '${e.path}' (rename or shallow diff?) \u2014 those commits are listed without a diff.`);let R=[...r,...g];return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:f,pagination:d,...R.length?{warnings:R}:{}},status:200}}catch(n){return W(n)}}async function Zp(e,t,n){let r=await pe(t),o=se("gh-api-releases",{owner:e.owner,repo:e.repo,page:e.page,perPage:e.perPage,includeAssets:e.includeAssets===!0,auth:r},n);return fe(o,()=>bP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function bP(e,t){try{let n=await U(t),[r,o]=await Promise.all([n.rest.repos.listReleases({owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page}),n.rest.repos.getLatestRelease({owner:e.owner,repo:e.repo}).catch(()=>{})]),i=o?.data,s=r.data.map(c=>({tagName:c.tag_name,...c.name&&c.name!==c.tag_name?{name:c.name}:{},...c.published_at?{publishedAt:c.published_at}:{},...c.prerelease?{prerelease:!0}:{},...c.draft?{draft:!0}:{},...i!==void 0&&c.id===i.id?{latest:!0}:{},...e.includeAssets&&c.assets&&c.assets.length>0?{assets:c.assets.map(u=>({name:u.name,size:u.size,downloadCount:u.download_count,url:u.browser_download_url}))}:{}})),a=Sn(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 W(n)}}var CP=30;async function em(e,t,n){let r=t;if(!r.owner||!r.repo)return O("owner and repo are required for releases mode.",e);let o=e.limit,i=Number(typeof o=="number"?o:r.itemsPerPage)||CP,s=await Zp({owner:r.owner,repo:r.repo,page:Number(r.page)||1,perPage:i,includeAssets:r.includeAssets===!0},n);if(Ie(s))return O(s,e,{toolName:P.GITHUB_RELEASES});let a=s.data.releases.length>0||s.data.latest!==void 0,c=s.data.pagination?.nextPage,u={...s.data,...c!==void 0?{next:{nextPage:{tool:"ghListReleases",query:{owner:r.owner,repo:r.repo,page:c,itemsPerPage:i},why:"Fetch the next page of releases",confidence:"exact"}}}:{}};return oe(e,u,a,P.GITHUB_RELEASES,{rawResponse:s.rawResponseChars})}function Ye(e){if(typeof e=="string")return e;if(Array.isArray(e)&&typeof e[0]=="string")return e[0]}function Aa(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Yo),n=e.query?.trim()??"";return[...t,...n?[n]:[]].join(" ")||void 0}function tm(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 ni(e){return e.pull_request!=null}function PP(e){return e?e.map(t=>typeof t=="string"?t:t.name??"").filter(Boolean):[]}function ri(e){return{number:e.number,title:e.title??"",state:e.state??"open",author:e.user?.login??"unknown",labels:PP(e.labels),createdAt:e.created_at??"",updatedAt:e.updated_at??"",...e.closed_at?{closedAt:e.closed_at}:{}}}function bn(e,t=[]){return{error:e,type:"http",...t.length>0?{hints:t}:{}}}function ka(e,t,n="anon"){return se("gh-api-issues",{owner:e.owner,repo:e.repo,issueNumber:e.issueNumber,query:Aa(e),state:e.state,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,label:e.label,milestone:e.milestone,created:e.created,updated:e.updated,closed:e.closed,comments:e.comments,reactions:e.reactions,locked:e.locked,visibility:e.visibility,archived:e.archived,match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,charOffset:e.charOffset,charLength:e.charLength,commentPage:e.commentPage,itemsPerPage:e.itemsPerPage,concise:e.concise,auth:n},t)}import{ContentSanitizer as nm}from"@octocodeai/octocode-engine/contentSanitizer";async function oi(e,t,n){try{let r=await e.rest.repos.get({owner:t,repo:n}),[o,i]=r.data.full_name?.split("/")??[];return!o||!i?{owner:t,repo:n,renamed:!1}:{owner:o,repo:i,renamed:o!==t||i!==n}}catch{return{owner:t,repo:n,renamed:!1}}}async function rm(e,t){let n=Ye(e.owner),r=Ye(e.repo),o=e.issueNumber;if(!n||!r||o==null)return bn("owner, repo, and issueNumber are required for issue detail mode.");let i=await U(t),s=await i.rest.issues.get({owner:n,repo:r,issue_number:o});if(ni(s.data))return bn(`Issue #${o} is a pull request; use type:"prs" with prNumber:${o}.`,[`Retry with { type: "prs", owner: "${n}", repo: "${r}", prNumber: ${o} }.`]);let a=e.content?.body!==!1,c=e.content?.comments?.discussion===!0,u=e.content?.comments?.includeBots===!0,l=ri(s.data),d={};if(a){let m=nm.sanitizeContent(s.data.body??"").content,p=tm(m,e.charOffset,e.charLength);l.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),f=await i.rest.issues.listComments({owner:n,repo:r,issue_number:o,per_page:p,page:m}),g=u?f.data:f.data.filter(h=>!Gt(h.user?.login??""));l.comments=g.map(h=>({id:String(h.id),user:h.user?.login??"unknown",body:nm.sanitizeContent(h.body??"").content,createdAt:h.created_at??"",updatedAt:h.updated_at??"",commentType:"discussion"}));let R=Sn(f.headers.link);d.comments={currentPage:m,itemsPerPage:p,totalComments:l.comments.length,hasMore:R,...R?{nextCommentPage:m+1}:{}}}return Object.keys(d).length>0&&(l.contentPagination=d),{data:{type:"issues",owner:n,repo:r,issues:[l],totalCount:1},status:200}}async function om(e,t,n){let r=Ye(t.owner)??"",o=Ye(t.repo)??"",i=await U(n),s=[],a=e;if(r&&o){let h=await oi(i,r,o);h.renamed&&(s.push(`Repository ${r}/${o} was renamed to ${h.owner}/${h.repo} \u2014 GitHub search does not follow renames, so the canonical name was searched instead.`),a={...e,owner:h.owner,repo:h.repo})}let c=xs(a),u=Math.min(t.limit??30,100),l=t.page??1,d=t.sort&&t.sort!=="best-match"?t.sort:void 0,m=await i.rest.search.issuesAndPullRequests({q:c,sort:d,order:t.order||"desc",per_page:u,page:l}),p=Kl(m.headers);p&&s.push(p);let f=(m.data.items??[]).filter(h=>!ni(h)).map(h=>ri(h)),g=m.data.total_count??f.length,R=l*u<g&&f.length===u;return{data:{type:"issues",owner:r,repo:o,issues:t.concise?f.map(h=>`#${h.number} ${h.title}`):f,totalCount:g,effectiveQuery:c,...s.length?{warnings:s}:{},...m.data.incomplete_results?{incompleteResults:!0}:{},pagination:{currentPage:l,perPage:u,hasMore:R,...R?{nextPage:l+1}:{},...g>1e3?{totalMatchesCapped:!0}:{}}},status:200}}async function im(e,t){let n=Ye(e.owner),r=Ye(e.repo);if(!n||!r)return bn("owner and repo are required for issues mode.");let o=await U(t),i=Math.min(e.limit??30,100),s=e.page??1,a=e.state==="open"||e.state==="closed"?e.state:"all",c=await o.rest.issues.listForRepo({owner:n,repo:r,state:a,per_page:i,page:s,...e.assignee?{assignee:e.assignee}:{},...e.author?{creator:e.author}:{},...e.mentions?{mentioned:e.mentions}:{},...e.milestone?{milestone:e.milestone}:{},...e.sort==="created"||e.sort==="updated"||e.sort==="comments"?{sort:e.sort}:{},...e.order?{direction:e.order}:{},...typeof e.label=="string"?{labels:e.label}:Array.isArray(e.label)?{labels:e.label.join(",")}:{}}),u=c.data.filter(p=>!ni(p)).map(p=>ri(p)),l=Sn(c.headers.link),d=!l&&s===1,m=[];return u.length===0&&l&&m.push("This page contained only pull requests (the GitHub issues endpoint returns both; PRs are filtered out) \u2014 follow pagination.nextPage, later pages may contain issues."),{data:{type:"issues",owner:n,repo:r,issues:e.concise?u.map(p=>`#${p.number} ${p.title}`):u,...d?{totalCount:u.length}:{},...m.length?{warnings:m}:{},pagination:{currentPage:s,perPage:i,hasMore:l,...l?{nextPage:s+1}:{}}},status:200}}async function _a(e,t,n){let r=await pe(t),o=ka(e,n,r);return fe(o,()=>xP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function xP(e,t){try{if(e.state==="merged")return bn('state:"merged" is not valid for type:"issues" \u2014 use "open" or "closed".',['For merged PRs use type:"prs" with state:"merged".']);if(e.issueNumber!=null)return await rm(e,t);let n={...e,query:Aa(e)};return ws(n)?await om(n,e,t):await im(e,t)}catch(n){return We(n)?{data:{type:"issues",owner:Ye(e.owner)??"",repo:Ye(e.repo)??"",issues:[],totalCount:0,pagination:{currentPage:e.page??1,perPage:Math.min(e.limit??30,100),hasMore:!1}},status:200}:W(n)}}async function sm(e,t,n){let r=t;if(!r.owner||!r.repo)return O("owner and repo are required for issues mode.",e);let o=r.issueNumber??r.prNumber,i=await _a({owner:r.owner,repo:r.repo,...o!=null?{issueNumber:o}:{},keywordsToSearch:r.keywordsToSearch,query:r.query,state:r.state,author:r.author,assignee:r.assignee,mentions:r.mentions,commenter:r.commenter,label:r.label,milestone:r.milestone,created:r.created,updated:r.updated,closed:r.closed,comments:r.comments,reactions:r.reactions,locked:r.locked,visibility:r.visibility,match:r.match,archived:r.archived,sort:r.sort,order:r.order,limit:r.limit,page:Number(r.page)||1,concise:r.concise,content:r.content,charOffset:r.charOffset,charLength:r.charLength,commentPage:r.commentPage,itemsPerPage:r.itemsPerPage},n);if(Ie(i))return O(i,e,{toolName:P.GITHUB_ISSUES});let s=Array.isArray(i.data.issues)?i.data.issues.length>0:!1,a=i.data.issues,c=(()=>{if(!Array.isArray(a)||a.length===0)return;let l=a[0];if(typeof l=="number")return l;if(typeof l=="string"){let d=l.match(/^#(\d+)\b/);return d?Number(d[1]):void 0}if(l&&typeof l=="object"&&typeof l.number=="number")return l.number})(),u={};return o==null&&c!=null&&(u.readIssue={tool:"ghSearchIssues",query:{owner:r.owner,repo:r.repo,issueNumber:c,content:{body:!0}},why:`Read issue #${c} body/discussion from this list`,confidence:"low"}),u.searchCode={tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Search code in this repository for symbols mentioned in the issue(s)",confidence:"low"},oe(e,{...i.data,next:u},s,P.GITHUB_ISSUES,{rawResponse:i.rawResponseChars})}async function am(e,t){try{let o=(await(await U(t)).rest.repos.compareCommitsWithBasehead({owner:e.owner,repo:e.repo,basehead:`${e.base}...${e.head}`})).data,i=(o.commits??[]).map(u=>({sha:u.sha,messageHeadline:(u.commit.message??"").split(`
|
|
29
|
+
`)[0]??"",author:u.commit.author?.name??u.author?.login??"unknown",date:u.commit.author?.date??""})),s=o.files??[],a=e.path?s.filter(u=>u.filename===e.path):s,c;if(e.includeDiff){let u=Nr(a,{filePage:e.filePage,itemsPerPage:e.itemsPerPage,charOffset:e.charOffset,charLength:e.charLength});c={files:u.files,filesPagination:u.filesPagination}}else c={changedFiles:a.length};return{data:{type:"compare",owner:e.owner,repo:e.repo,base:e.base,head:e.head,status:o.status,aheadBy:o.ahead_by,behindBy:o.behind_by,totalCommits:o.total_commits,commits:i,...c},status:200}}catch(n){return W(n)}}async function cm(e,t,n){let r=t;if(!r.owner||!r.repo)return O("owner and repo are required for commits mode.",e);if(r.base&&r.head){let f=e.limit,g=await am({owner:r.owner,repo:r.repo,base:r.base,head:r.head,includeDiff:!!r.includeDiff,path:r.path,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof f=="number"?f:r.itemsPerPage,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);return Ie(g)?O(g,e,{toolName:P.GITHUB_COMMITS}):oe(e,g.data,g.data.totalCommits>0||g.data.status!=="identical",P.GITHUB_COMMITS)}let o=r.path,i=o&&!o.endsWith("/")?"file":"repo";if(i==="file"&&!o)return O("path is required when querying a specific file in commits mode.",e);let s=e.limit,a=typeof s=="number"?s:r.itemsPerPage,c=await Jp({type:i,owner:r.owner,repo:r.repo,path:o,branch:r.branch,since:r.since,until:r.until,author:r.author,committer:r.committer,page:Number(r.page)||1,perPage:Number(a)||30,filePage:typeof r.filePage=="number"?r.filePage:void 0,itemsPerPage:typeof a=="number"?a:void 0,includeDiff:!!r.includeDiff,charOffset:typeof r.charOffset=="number"?r.charOffset:void 0,charLength:typeof r.charLength=="number"?r.charLength:void 0},n);if(Ie(c))return O(c,e,{toolName:P.GITHUB_COMMITS});let{commits:u}=c.data,l=u.length>0,d=u.map(f=>f.messageHeadline?.match(/\(#(\d+)\)/)?.[1]).find(Boolean),m=!l&&c.data.warnings?.length?{hints:c.data.warnings}:{},p={...c.data,...m,...d?{next:{prDetail:{tool:"ghSearchPullRequests",query:{owner:r.owner,repo:r.repo,prNumber:Number(d)},why:`Open PR #${d} referenced by the first commit for review context`,confidence:"low"}}}:{}};return oe(e,p,l,P.GITHUB_COMMITS,{rawResponse:c.rawResponseChars})}function wP(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 TP(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 EP(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function um(e){let{content:t,reviewMode:n}=e,r=wP(t,n),o=TP(t,n),i=EP(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}function Gr(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Cn(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Hr(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 Qt(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 ii(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Ia(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function LP(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Br(e,t,n){return LP({...Ia(e,t),...n})}function Oa(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Br(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function si(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Br(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function Pn(e){return typeof e=="object"&&e!==null}function ai(e){if(Pn(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function ci(e){if(Pn(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function AP(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function lm(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=AP(r,n.comments),i=Gr(t),s=i?o.filter(u=>Cn(u.body,i)):o,{items:a,pagination:c}=Hr(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(u=>{let l=Qt(typeof u.body=="string"?u.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:u.id,author:u.author,commentType:u.commentType??"discussion",path:u.path,line:u.line,...u.in_reply_to_id!=null?{in_reply_to_id:u.in_reply_to_id}:{},...l?{body:l.content,bodyPagination:l.pagination}:{bodyPreview:ii(typeof u.body=="string"?u.body:"")},createdAt:u.createdAt,updatedAt:u.updatedAt}}),commentPagination:c}}function dm(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Gr(t);return{reviews:(o?r.filter(s=>Cn(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Qt(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function pm(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Hr(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function ui(e){return String(e.path??e.filename??"")}function kP(e,t){return{path:ui(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function mm(e,t,n){let r=Array.isArray(e.fileChanges)?e.fileChanges:[],o=n.patches.files,i=o&&o.length>0?r.filter(m=>o.includes(ui(m))):r,s=Gr(t),a=s?i.filter(m=>Cn(ui(m),s)||Cn(m.patch,s)):i,{items:c,pagination:u}=Hr(a,t.filePage??t.page??1,t.itemsPerPage??20),l=n.patches.mode!=="none",d=c.map(m=>{let p=kP(m,!1);if(!l||typeof m.patch!="string")return p;let f=Qt(m.patch,t.charOffset??0,t.charLength??12e3);return{...p,patch:f?.content??"",...f?{patchPagination:f.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:d,filePagination:u}:r.length===0?{}:{filePathsPreview:r.slice(0,20).map(ui).filter(Boolean),filePathsPagination:{totalFiles:r.length,filesPerPage:20,hasMore:r.length>20,...r.length>20?{nextFilePage:2}:{}}}}function $t(e,t){return{...e,content:t}}function _P(e,t){return{...e,...t}}function fm(e,t,n,r){let o=Ia(e,t);return{target:o,...n.body?{}:{getBody:$t(o,{body:!0})},...n.changedFiles?{}:{getChangedFiles:$t(o,{changedFiles:!0})},...n.patches.mode!=="none"?{}:{getSelectedPatches:$t(o,{patches:{mode:"selected",files:[r??"path/from/changedFiles"]}}),getAllPatches:$t(o,{patches:{mode:"all"}})},...n.comments?{}:{getComments:$t(o,{comments:{discussion:!0,reviewInline:!0}})},...n.reviews?{}:{getReviews:$t(o,{reviews:!0})},...n.commits?{}:{getCommits:$t(o,{commits:{list:!0}})},...n.reviewMode==="full"?{}:{fullReview:_P(o,{reviewMode:"full"})}}}function IP(e){return e.replace(/\n{3,}/g,`
|
|
32
30
|
|
|
33
|
-
`)}function
|
|
31
|
+
`)}function OP(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function FP(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!Pn(n))continue;let r=ci(n.patchPagination);if(r?.hasMore)return r}}function vP(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!Pn(n))continue;let r=ci(n.bodyPagination);if(r?.hasMore)return r}}function DP(e,t,n,r){let o={},i=ci(e.bodyPagination),s=ai(e.filePagination),a=ai(e.commentPagination),c=ai(e.commitPagination),u=FP(e),l=vP(e),d=OP(n);i&&(o.body={...i,nextQuery:Oa(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:si(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:si(t,r,{comments:n.comments},"commentPage",a)}),l?.hasMore&&l.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...l,nextQuery:Br(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:l.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:si(t,r,{commits:n.commits},"commitPage",c)}),u&&n.patches.mode!=="none"&&(o.patches={...u,nextQuery:Oa(t,r,{patches:n.patches},u,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return Pn(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Br(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function MP(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function hm(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?IP(s):s,c=n.body?Qt(a,t.charOffset??0,t.charLength??12e3):void 0,u=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,l=o!==void 0?o:u,m=t.prNumber!==void 0||t.verbose===!0,p=mm(e,t,n),f=Array.isArray(p.changedFiles)?p.changedFiles.find(y=>y.path)?.path:void 0,R={...{number:e.number,title:e.title,state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:ii(typeof e.body=="string"?e.body:void 0)}:{},...l?{next:fm(t,i,n,f)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...p,...lm(e,t,n),...dm(e,t,n),...pm(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},h=DP(R,t,n,i);return MP(R),h&&(R.contentPagination=h),R}async function gm(e,t,n){let r=n(),o={...t},i=um(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 O("At least one valid search parameter, filter, or PR number is required.",e);let c=await ct(o,()=>r.provider.searchPullRequests(Op(o)));if(c.ok===!1)return c.result;let u=s?i.changedFiles||i.patches.mode!=="none":!1,{pullRequests:l,resultData:d}=Fp(c.response.data,{includeFileChanges:u});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},f=o.minify==="standard",g=s,R=l.map(y=>hm(y,o,m?p:i,f,g));d.pullRequests=R,!s&&o.concise===!0&&(d.pullRequests=R.map(y=>{let S=y;return`#${S.number} ${S.title}`}));let h=R.length>0;if(!s&&h){let y=R[0].number,S=o.owner,C=o.repo;y!=null&&S&&C&&(d.next={readPr:{tool:"ghSearchPullRequests",query:{owner:S,repo:C,prNumber:y,content:{body:!0,changedFiles:!0,comments:{discussion:!0}}},why:"Read any PR from this list \u2014 swap prNumber for the # you want.",confidence:"low"}})}return oe(o,d,h,P.GITHUB_PULL_REQUESTS,{rawResponse:c.response.rawResponseChars})}async function Ur(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{let s=xe(Gi,o);if(s.ok===!1)return s.error;let a=s.data.type;return a==="releases"?await em(o,s.data,n):a==="issues"?await sm(o,s.data,n):a==="commits"?await cm(o,s.data,n):await gm(o,s.data,r)}catch(s){return ye(s,o,void 0,P.GITHUB_PULL_REQUESTS)}},{toolName:P.GITHUB_PULL_REQUESTS,keysPriority:["pullRequests","issues","releases","latest","tagName","publishedAt","prerelease","pagination","totalCount","error"]},e)}function li(e,t){return{...e,queries:e.queries.map(n=>({...n,type:t}))}}function ym(e){return Ur(li(e,"prs"))}function Rm(e){return Ur(li(e,"issues"))}function Sm(e){return Ur(li(e,"commits"))}function bm(e){return Ur(li(e,"releases"))}var NP=`
|
|
34
32
|
query($q: String!, $first: Int!, $after: String, $owner: String!, $repo: String!) {
|
|
35
33
|
search(query: $q, type: DISCUSSION, first: $first, after: $after) {
|
|
36
34
|
discussionCount
|
|
@@ -53,13 +51,13 @@ query($q: String!, $first: Int!, $after: String, $owner: String!, $repo: String!
|
|
|
53
51
|
repository(owner: $owner, name: $repo) {
|
|
54
52
|
hasDiscussionsEnabled
|
|
55
53
|
}
|
|
56
|
-
}`;async function gm(e,t,n){let r=await pe(t),o=se("gh-api-discussions",{owner:e.owner,repo:e.repo,keywords:(e.keywords??[]).join(" "),perPage:e.perPage,after:e.after??"",auth:r},n);return fe(o,()=>wP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function wP(e,t){try{let n=await U(t),r=(e.keywords??[]).map(l=>l.trim()).filter(Boolean).join(" "),o=`repo:${e.owner}/${e.repo}${r?` ${r}`:""}`,i=await n.graphql(xP,{q:o,first:e.perPage,owner:e.owner,repo:e.repo,...e.after?{after:e.after}:{}}),a=(i.search.nodes??[]).filter(l=>typeof l.number=="number").map(l=>({number:l.number,title:l.title,url:l.url,...l.author?.login?{author:l.author.login}:{},...l.category?.name?{category:l.category.name}:{},...l.createdAt?{createdAt:l.createdAt}:{},...l.updatedAt?{updatedAt:l.updatedAt}:{},...l.answerChosenAt?{answered:!0}:{},...typeof l.upvoteCount=="number"?{upvotes:l.upvoteCount}:{},...typeof l.comments?.totalCount=="number"?{comments:l.comments.totalCount}:{}})),c=i.search.pageInfo.hasNextPage===!0,u=i.search.pageInfo.endCursor??void 0;return{data:{type:"discussions",owner:e.owner,repo:e.repo,totalCount:i.search.discussionCount,discussions:a,pagination:{perPage:e.perPage,hasMore:c,...c&&u?{nextCursor:u}:{}},...typeof i.repository?.hasDiscussionsEnabled=="boolean"?{hasDiscussionsEnabled:i.repository.hasDiscussionsEnabled}:{}},status:200}}catch(n){return W(n)}}var TP=30;async function ym(e){let{queries:t,authInfo:n,sessionId:r}=e;return ee(t,async(o,i)=>{try{if(!o.owner||!o.repo)return O("owner and repo are required to search discussions.",o);let s=Number(o.limit??o.itemsPerPage)||TP,a=await gm({owner:o.owner,repo:o.repo,keywords:o.keywordsToSearch,perPage:s,...o.after?{after:o.after}:{}},n,r);if(Ie(a))return O(a,o,{toolName:P.GITHUB_DISCUSSIONS});let c=a.data.discussions.length>0,u=!c&&a.data.hasDiscussionsEnabled===!1?["This repository has Discussions disabled \u2014 an empty result here means the feature is off, not that no matching discussions exist."]:[],l=a.data.pagination.nextCursor,d={...a.data,...u.length>0?{warnings:u}:{},...l?{next:{nextPage:{tool:"ghSearchDiscussions",query:{owner:o.owner,repo:o.repo,...o.keywordsToSearch?{keywordsToSearch:o.keywordsToSearch}:{},itemsPerPage:s,after:l},why:"Fetch the next page of discussions",confidence:"exact"}}}:{}};return oe(o,d,c,P.GITHUB_DISCUSSIONS,{rawResponse:a.rawResponseChars})}catch(s){return ye(s,o,"Failed to search repository discussions",P.GITHUB_DISCUSSIONS)}},{toolName:P.GITHUB_DISCUSSIONS,keysPriority:["totalCount","discussions","pagination","error"]},e)}function Sm(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function ui(e){return!!(e.keywords&&e.keywords.length>0)}function bm(e){return!!(ui(e)||Sm(e)||e.owner||e.language||e.stars||e.updated||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function Rm(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Cm(e){let t=Sm(e),n=ui(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:Rm(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:Rm(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function Pm(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}function wm(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 Tm(e,t){return[...e].sort((n,r)=>{let o=EP(n,r,t.sort);if(o!==0)return o;let i=xm(r,t)-xm(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:ka(n).localeCompare(ka(r))})}function EP(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 Pm(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function xm(e,t){let n=LP(t),r=ka(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(l=>l.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((l,d)=>o===d||r===d?l+80:o.includes(d)||r.includes(d)?l+40:s.includes(d)?l+35:i.includes(d)?l+10:l,0)+(c&&a===c?20:0)}function LP(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function ka(e){return`${e.owner}/${e.repo}`}function Ia(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 Oa(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 Fa(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 Em(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??N(n.response.data??n.response)),0)}function AP(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 _P(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"low"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"low"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(AP),...o?{next:o}:{}}}}async function Lm(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{if(!bm(o))return O("At least one repository search term or filter is required.",o);let s=r(),a=Cm(o),{successes:c,failures:u}=await Kd(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(Ap(w.query))}))),l=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=u.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(l.length===0){let w=d[0];return w?Mo(w.response,o):ye(new Error("Repository search produced no provider results"),o,void 0,P.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=Tm(wm(l.flatMap(w=>_p(w.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,g=l.length===1?l[0]:void 0,h=l.length>1?Fa(l,p.length):g?.response.data.pagination,y=h?Ia(h):void 0,S=f.length>0,C=_P({repositories:f,pagination:y},o),x=Oa(d),T;if(o.owner&&ui(o)){let w=(Array.isArray(o.keywords)?o.keywords:[o.keywords]).filter(A=>typeof A=="string"&&A.trim().length>0).slice(0,3),b=w.some(A=>f.some(M=>M.repo?.toLowerCase()===A.toLowerCase()));if(w.length>0&&!b)try{let A=await U(n);for(let M of w){let H=await ni(A,String(o.owner),M);if(H.renamed){T={warning:`No repositories matched under owner "${o.owner}", but "${o.owner}/${M}" now resolves to "${H.owner}/${H.repo}" \u2014 the repository may have been transferred. Retry scoped to owner:"${H.owner}" (see next.retryUnderCanonicalOwner).`,next:{retryUnderCanonicalOwner:{tool:"ghSearchRepos",query:{...o,owner:H.owner,keywords:[H.repo]},why:"Re-run scoped to the repository's current owner after a detected transfer.",confidence:"exact"}}};break}}}catch{}}let L=[...x??[],...T?[T.warning]:[],...!S&&!T?['No repositories matched. Keywords are ANDed \u2014 try fewer or broader keywords, drop a topic/filter (topics are sparse), or add match:"readme" for full-text search.']:[]],_={...C.data,...L.length>0?{warnings:L}:{},...T?{next:T.next}:{}};return oe(o,_,S,P.GITHUB_SEARCH_REPOSITORIES,{rawResponse:Em([...l,...d])})}catch(s){return ye(s,o,void 0,P.GITHUB_SEARCH_REPOSITORIES)}},{toolName:P.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}function kP(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0,o=typeof r?.status=="number"?r.status:void 0,i=typeof t.path=="string"?t.path.replace(/\/+$/,""):"",s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):"",a=i.split("/").pop()||t.repo,c=o===404?{retryParent:{tool:"ghViewRepoStructure",query:{owner:t.owner,repo:t.repo,...s?{path:s}:{},...t.branch?{branch:t.branch}:{}},why:"Retry at the parent directory \u2014 the path or branch may be wrong.",confidence:"low"},searchPath:{tool:"ghSearchCode",query:{owner:t.owner,repo:t.repo,match:"path",keywords:[a]},why:"Locate the path by name in case it moved or was renamed.",confidence:"low"}}:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...c?{next:c}:{}}}function IP(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&yr(o))continue;let i=r.files.filter(a=>!cn(a)),s=r.folders.filter(a=>!yr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function Am(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,u=c??await s.provider.resolveDefaultBranch(a),l=await ct(o,()=>s.provider.getRepoStructure(Sa(o,u))),d=u,m;if(l.ok===!1&&c){let C=l.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let T=await s.provider.resolveDefaultBranch(a);if(T!==c){let L=await ct(o,()=>s.provider.getRepoStructure(Sa(o,T)));L.ok!==!1&&(l=L,d=T,m=`Branch/ref '${c}' was not found. Showing '${T}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(l.ok===!1)return kP(l.result,o);let p=IP(l.response.data.structure),f=Object.keys(p).length>0,g=vp(l.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let h=g.structure?.find(C=>(C.files?.length??0)>0),y=String(o.path??"").replace(/\/+$/,""),S=h?(()=>{let C=h.dir==="."?h.files[0]:`${h.dir}/${h.files[0]}`;return y?`${y}/${C}`:C})():void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...d?{branch:d}:{}},why:"Read the first listed file",confidence:"low"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...d?{branch:d}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},oe(o,g,f,P.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return ye(s,o,"Failed to explore repository structure",P.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:P.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}import{existsSync as _m}from"fs";import{delimiter as OP,dirname as FP,join as km}from"path";function Im(){return process.platform==="win32"?"npm.cmd":"npm"}function vP(){let e=FP(process.execPath);return km(e,Im())}function DP(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function MP(){let e=(process.env.PATH??"").split(OP).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...DP()])]}function NP(){let e=vP();if(_m(e))return{command:process.execPath,argsPrefix:[e]};let t=Im();for(let n of MP()){let r=km(n,t);if(_m(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var GP=["view","search","ping","config","whoami"],HP=[...Ar,...Yd];async function jt(e,t,n={}){if(!GP.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=qd(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=NP(),c=await _r(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:HP});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var xn="https://registry.npmjs.org",li=null;async function di(){if(li)return li;try{let e=await jt("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 li=t,t}}catch{}return li=xn,xn}var Ur=new Map,BP=5,va=3e4;function Qr(e){try{return new URL(e).host||e}catch{return e}}var Da=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}};function Om(e,t=Date.now()){let n=Ur.get(Qr(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<va)throw new Da(Qr(e),va-r);n.state="half-open"}}function Ma(e){let t=Ur.get(Qr(e));t&&(t.failures=0,t.state="closed")}function Fm(e,t=Date.now()){let n=Qr(e),r=Ur.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=BP&&(r.state="open",r.openedAt=t)),Ur.set(n,r)}function vm(e,t=Date.now()){let n=Ur.get(Qr(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<va:!1}import{z as E}from"zod";var pi=E.looseObject({name:E.string(),version:E.string(),repository:E.union([E.string(),E.object({url:E.string().optional(),type:E.string().optional(),directory:E.string().optional()})]).optional(),main:E.string().optional(),module:E.string().optional(),type:E.string().optional(),exports:E.unknown().optional(),types:E.string().optional(),typings:E.string().optional(),description:E.string().optional(),keywords:E.array(E.string()).optional(),license:E.union([E.string(),E.object({type:E.string().optional()})]).optional(),homepage:E.string().optional(),author:E.union([E.string(),E.object({name:E.string().optional(),email:E.string().optional(),url:E.string().optional()})]).optional(),maintainers:E.array(E.object({name:E.string().optional(),email:E.string().optional()})).optional(),engines:E.record(E.string(),E.string()).optional(),dependencies:E.record(E.string(),E.string()).optional(),devDependencies:E.record(E.string(),E.string()).optional(),peerDependencies:E.record(E.string(),E.string()).optional(),time:E.record(E.string(),E.string().optional()).optional()}),UP=E.looseObject({package:E.looseObject({name:E.string().nullish(),version:E.string().nullish(),description:E.string().nullish(),links:E.looseObject({npm:E.string().nullish(),homepage:E.string().nullish(),repository:E.string().nullish()}).nullish()}),score:E.looseObject({final:E.number().nullish(),detail:E.looseObject({quality:E.number().nullish(),popularity:E.number().nullish(),maintenance:E.number().nullish()}).nullish()}).nullish()}),Dm=E.looseObject({objects:E.array(UP),total:E.union([E.number(),E.string()]).optional()}),QP=E.union([E.string(),E.boolean(),E.number(),E.null(),E.record(E.string(),E.unknown())]);var $P=6e4;function Mm(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function jP(e,t,n,r){e&&St({limit_type:"primary",retry_after_seconds:Mm(r),api_method:t,api_url:n,provider:e})}function zP(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(cr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Il(r),e.status===429&&jP(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function WP(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=Mm(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Xe(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=$P,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:u,packageRegistry:l}=t,d=e;if(a){let R=e.includes("?")?"&":"?";d=`${e}${R}version=${encodeURIComponent(Mt)}`}let m={"User-Agent":`Octocode-MCP/${Mt}`,...i},p=globalThis.fetch;if(!p)throw new Error(cr.FETCH_NOT_AVAILABLE.message);Om(d);let f,g=n+1;for(let R=1;R<=g;R++){if(c?.aborted)throw new Error("Request aborted");try{let h=await p(d,{method:s,headers:m,signal:c});if(!h.ok)throw zP(h,s,d,l,u);if(h.status===204)return Ma(d),null;let y=await h.json();return Ma(d),y}catch(h){let y=h;if(c?.aborted||h instanceof Error&&h.name==="AbortError")throw new Error("Request aborted");if(y&&y.retryable===!1)throw h;if(f=h instanceof Error?h:new Error(String(h)),R===g)break;let S=WP(R,r,o,y);await new Promise(C=>setTimeout(C,S))}}throw Fm(d),new Error(cr.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}function xt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var VP="https://api.npmjs.org/downloads/point/last-week";function we(e){return e===void 0?0:N(e)}async function mi(e){try{let t=`${VP}/${encodeURIComponent(e)}`,n=await Xe(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:we(n)}}catch{return{rawResponseChars:0}}}function Nm(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 Gm(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 KP(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function fi(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=xt(e.repository):(e.repository.url&&(r=xt(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:KP(e),...o?{repositoryDirectory:o}:{},...Nm(e.exports)?{exports:Nm(e.exports)}:{},...Gm(e.bin,e.name)?{bin:Gm(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 YP(e){return typeof e.links?.repository=="string"?xt(e.links.repository):typeof e.repository=="string"?xt(e.repository):typeof e.repository?.url=="string"?xt(e.repository.url):null}function Hm(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:YP(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 Na(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function Bm(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 XP=3e3;function Ga(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 Ha(e){try{let t=await di(),n=Na(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Xe(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=we(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Xe(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:we(i)}}catch{return{rawResponseChars:0}}}async function gi(e,t,n){let[r,o]=await Promise.all([mi(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Ha(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 hi(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function qP(e,t){try{let n=await jt("view",[e,"--json"],{timeout:XP});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,...hi(c)?{}:{errorDetail:c},rawResponseChars:we(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=we(o),s=pi.safeParse(o);return s.success?{pkg:fi(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,...hi(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function JP(e,t){try{let n=await di(),r=Na(e),o=`${n}/${r}/latest`,i;try{i=await Xe(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(u){let l=u instanceof Error?u.message:String(u);return l.includes("404")||l.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:l,rawResponseChars:0}}let s=we(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=pi.safeParse(i);return a.success?{pkg:fi(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,...hi(r)?{}:{errorDetail:r},rawResponseChars:0}}}function ZP(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Ba(e,t){let n=0,r;for(let o of ZP(e)){let i;try{i=await Xe(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);hi(u)||(r=u);continue}if(n+=we(i),!i||typeof i!="object")continue;let s=pi.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:fi(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function yi(e,t=!1){let[n,r]=await Promise.allSettled([qP(e,t),JP(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?gi(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function Um(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await yi(e,t);if(!r){if(o){let s=Ga(o);if(s&&n){let a=await Ba(e,t);if(a.pkg){let c=await gi(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function ex(e,t,n,r=0){let o=Math.max(t+r,t),i=await jt("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:we(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=we(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let l=[...a].sort((f,g)=>{let R=f?.score?.final??0;return(g?.score?.final??0)-R}).slice(r,r+t),d=await Promise.all(l.map(async f=>{if(!f||typeof f!="object")return null;let g=f;if(!g.name)return null;if(n){let R=await yi(g.name,!0);if(R.pkg)return R}return{pkg:Hm(g),rawResponseChars:0}})),m=d.map(f=>f?.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function tx(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${xn}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Xe(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`Could not reach the npm search API (${f instanceof Error?f.message:String(f)}). The package may not exist, or the registry search endpoint is unavailable.`,hints:['Verify the exact package name / scope (e.g. "@scope/name")',"For an exact known name, query it directly instead of a keyword search","Ensure the npm registry is accessible from this environment"]}}let a=we(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Dm.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let l=[...c.data.objects].sort((f,g)=>{let R=f.score?.final??0;return(g.score?.final??0)-R}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),d=await Promise.all(l.map(async f=>{if(n){let g=await yi(f.name,!0);if(g.pkg)return g}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?xt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=d.map(f=>f.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+g.rawResponseChars,0);return{packages:m,totalFound:Bm(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 Ua(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 Xe(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:we(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:we(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"?xt(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:we(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function Qa(e,t,n,r=0){try{let o=await ex(e,t,n,r);if(!("error"in o))return o}catch{}return tx(e,t,n,r)}async function $a(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}):mi(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Ha(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}function zt(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Qm(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function ja(e,t,n,r=0){let o=se("npm-search",{name:e,limit:t,metadata:n,from:r});return fe(o,async()=>{if(vm(xn)){if(r===0&&t===1&&zt(e)){let l=await Ba(e,n);if(l.pkg){let d=await gi(e,l.pkg,l.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let u=await Ua(e,t);return!("error"in u)&&u.packages.length>0?u:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&zt(e)){let u=await Um(e,n,t===1);if("error"in u){if(!Ga(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await Qa(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return $a(s);let a=Qm(e);if(a!==e){let u=await Qa(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return $a(u)}let c=await Ua(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function $m(e){let t=zt(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return ja(e.name,n,!0,r)}function za(e){if(e===void 0)return;let n=(Array.isArray(e)?e.join(" "):e).trim();return n.length>0?n:void 0}var rx=/\b(?:404|e404)\b|not\s+found|no\s+such\s+package|does\s+not\s+exist/i;function Wa(e){return rx.test(e)}function ox(e){return"error"in e}function Ri(e){return"npmUrl"in e}function ix(e){return Ri(e)&&e.path?e.path:e.name}function sx(e){return Ri(e)?e.repoUrl:e.repository}function ax(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}var cx={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function ux(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=s=>s.replace(/\.git$/,""),r=t.match(/^(github|gitlab|bitbucket):(.+)$/i);if(r&&r[1]&&r[2]){let s=cx[r[1].toLowerCase()];return n(`https://${s}/${r[2]}`)}let o=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(o&&o[1]&&o[2])return n(`https://${o[1]}/${o[2]}`);let i=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(i&&i[1]){let s=i[1].replace(/^[^@/]+@/,"");return n(`https://${s}`)}return n(t)}function Va(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 jm(e,t){let n=Va(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghListReleases",query:{owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags (requires ENABLE_RELEASES)"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function lx(e){let t=ix(e),n=ux(sx(e)),r={name:t};Ri(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=ax(Ri(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=jm(n,o);return i&&(r.next=i),r.version&&Va(n)&&(r.warnings=[`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`]),r}function dx(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=Va(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:jm(i.repository,i.repositoryDirectory)});let{repository:u,repositoryDirectory:l,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function px(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,u=s&&o>=a?o+1:a;return{currentPage:o,totalPages:u,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function zm(e){return ee(e.queries,async t=>{try{let n=t.packageName??za(t.keywords);if(!n)return O("Provide a packageName or keywords for package search",t);let r=await $m({name:n,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(ox(r)){if(Wa(r.error)){let d=zt(n);return oe(t,{packages:[],hints:[d?`No package published under the exact name "${n}". Check the spelling, and try the scoped (@scope/name) vs unscoped form.`:`No packages matched "${n}". Try different or fewer keywords, or search by an exact package name.`]},!1,P.PACKAGE_SEARCH,{rawResponse:r})}return O(r.error,t,{rawResponse:r})}let o=r.packages,i=o.map(lx),s=i.length>0,a=o.length>1||r.totalFound>1,c=px(t,r.totalFound,i.length,a),l={...dx(i),pagination:c};return oe(t,l,s,P.PACKAGE_SEARCH,{rawResponse:r.rawResponseChars??r})}catch(n){return O(n,t,{toolName:P.PACKAGE_SEARCH})}},{toolName:P.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{ContentSanitizer as Cx}from"@octocodeai/octocode-engine/contentSanitizer";import Wm from"path";import{pathValidator as Vm}from"@octocodeai/octocode-engine/pathValidator";import{redactPath as $r}from"@octocodeai/octocode-engine/pathUtils";var Ee={pathValidationFailed:(e,t,n)=>new Se(G.PATH_VALIDATION_FAILED,t||`Path validation failed: ${$r(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=$r(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 Se(G.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Se(G.FILE_READ_FAILED,`Failed to read file: ${$r(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Se(G.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)}). Use startLine/endLine, matchString, or charOffset/charLength to read a bounded slice.`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Se(G.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${$r(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Se(G.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Se(G.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 Se(G.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Se(G.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{getConfigSync as Km}from"@octocodeai/config";function mx(e=Km().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&Vm.addAllowedRoot(t)}function Le(e,t){if(!e.path?.trim()){let s=Ee.pathValidationFailed("","path is required");return{isValid:!1,errorResult:O(s,e,{toolName:t})}}mx();let n=process.env.WORKSPACE_ROOT?.trim()||Km().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Wm.isAbsolute(r)?r:Wm.resolve(n,r),i=Vm.validate(o);if(!i.isValid){let s=Ee.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:O(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}import{open as fx,readFile as hx,stat as gx}from"fs/promises";var wt={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 Ym(e,t){return n=>t}function Ka(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ya(e,t,n){return{...e,...Ka(t,n)}}function Xm(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 qm(e,t){try{return{fileStats:await gx(t)}}catch(n){let r=Ee.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:O(r,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Jm(e){let t=e.startLine!==void 0&&e.endLine!==void 0;return e.minify??(e.fullContent===!0||t?"none":"standard")}function Zm(e,t,n){return n!=="none"?!1:t>wt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.charLength}function ef(e,t,n){let r=Ee.fileTooLarge(e.path,n,wt.LARGE_FILE_THRESHOLD_KB);return O(r,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function tf(e,t){let n=Ee.binaryFileUnsupported(e.path);return O(n,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function nf(e){let n=Buffer.alloc(8192),r;try{r=await fx(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let u=i[c];if(u===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let l=u===9||u===10||u===13;u<32&&!l&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(Ym("binary sample handle close",void 0))}}async function rf(e,t){try{return{content:await hx(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?Ee.fileAccessFailed(e.path,r):Ee.fileReadFailed(e.path,r);return{errorResult:O(i,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function of(e,t){return{status:"empty",errorCode:G.NO_MATCHES,totalLines:t}}function yx(e,t,n){let r=bo(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:of(e,n)};let o=r.lines.join(`
|
|
57
|
-
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,u,l,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(u=m.start,l=p.end,d=r.matchRanges)}return{resultContent:o,isPartial:!0,actualStartLine:u,actualEndLine:l,matchRanges:d,matchedLines:r.matchingLines,warnings:[c]}}function
|
|
58
|
-
`)}function
|
|
59
|
-
`),o=Ve(t);return e.matchString?
|
|
54
|
+
}`;async function Cm(e,t,n){let r=await pe(t),o=se("gh-api-discussions",{owner:e.owner,repo:e.repo,keywords:(e.keywords??[]).join(" "),perPage:e.perPage,after:e.after??"",auth:r},n);return fe(o,()=>GP(e,t),{shouldCache:i=>"data"in i&&!("error"in i)})}async function GP(e,t){try{let n=await U(t),r=(e.keywords??[]).map(l=>l.trim()).filter(Boolean).join(" "),o=`repo:${e.owner}/${e.repo}${r?` ${r}`:""}`,i=await n.graphql(NP,{q:o,first:e.perPage,owner:e.owner,repo:e.repo,...e.after?{after:e.after}:{}}),a=(i.search.nodes??[]).filter(l=>typeof l.number=="number").map(l=>({number:l.number,title:l.title,url:l.url,...l.author?.login?{author:l.author.login}:{},...l.category?.name?{category:l.category.name}:{},...l.createdAt?{createdAt:l.createdAt}:{},...l.updatedAt?{updatedAt:l.updatedAt}:{},...l.answerChosenAt?{answered:!0}:{},...typeof l.upvoteCount=="number"?{upvotes:l.upvoteCount}:{},...typeof l.comments?.totalCount=="number"?{comments:l.comments.totalCount}:{}})),c=i.search.pageInfo.hasNextPage===!0,u=i.search.pageInfo.endCursor??void 0;return{data:{type:"discussions",owner:e.owner,repo:e.repo,totalCount:i.search.discussionCount,discussions:a,pagination:{perPage:e.perPage,hasMore:c,...c&&u?{nextCursor:u}:{}},...typeof i.repository?.hasDiscussionsEnabled=="boolean"?{hasDiscussionsEnabled:i.repository.hasDiscussionsEnabled}:{}},status:200}}catch(n){return W(n)}}var HP=30;async function Pm(e){let{queries:t,authInfo:n,sessionId:r}=e;return ee(t,async(o,i)=>{try{if(!o.owner||!o.repo)return O("owner and repo are required to search discussions.",o);let s=Number(o.limit??o.itemsPerPage)||HP,a=await Cm({owner:o.owner,repo:o.repo,keywords:o.keywordsToSearch,perPage:s,...o.after?{after:o.after}:{}},n,r);if(Ie(a))return O(a,o,{toolName:P.GITHUB_DISCUSSIONS});let c=a.data.discussions.length>0,u=!c&&a.data.hasDiscussionsEnabled===!1?["This repository has Discussions disabled \u2014 an empty result here means the feature is off, not that no matching discussions exist."]:[],l=a.data.pagination.nextCursor,d={...a.data,...u.length>0?{warnings:u}:{},...l?{next:{nextPage:{tool:"ghSearchDiscussions",query:{owner:o.owner,repo:o.repo,...o.keywordsToSearch?{keywordsToSearch:o.keywordsToSearch}:{},itemsPerPage:s,after:l},why:"Fetch the next page of discussions",confidence:"exact"}}}:{}};return oe(o,d,c,P.GITHUB_DISCUSSIONS,{rawResponse:a.rawResponseChars})}catch(s){return ye(s,o,"Failed to search repository discussions",P.GITHUB_DISCUSSIONS)}},{toolName:P.GITHUB_DISCUSSIONS,keysPriority:["totalCount","discussions","pagination","error"]},e)}function wm(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function di(e){return!!(e.keywords&&e.keywords.length>0)}function Tm(e){return!!(di(e)||wm(e)||e.owner||e.language||e.stars||e.updated||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function xm(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Em(e){let t=wm(e),n=di(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:xm(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:xm(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function Lm(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}function km(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 _m(e,t){return[...e].sort((n,r)=>{let o=BP(n,r,t.sort);if(o!==0)return o;let i=Am(r,t)-Am(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Fa(n).localeCompare(Fa(r))})}function BP(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 Lm(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function Am(e,t){let n=UP(t),r=Fa(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(l=>l.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((l,d)=>o===d||r===d?l+80:o.includes(d)||r.includes(d)?l+40:s.includes(d)?l+35:i.includes(d)?l+10:l,0)+(c&&a===c?20:0)}function UP(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Fa(e){return`${e.owner}/${e.repo}`}function va(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 Da(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 Ma(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 Im(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??N(n.response.data??n.response)),0)}function QP(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 $P(e,t){let n=t.concise===!0,r=e.repositories[0],o=r?.owner&&r?.repo?{viewStructure:{tool:"ghViewRepoStructure",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"low"},searchCode:{tool:"ghSearchCode",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"low"}}:void 0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(i=>`${i.owner?`${i.owner}/`:""}${i.repo}`):e.repositories.map(QP),...o?{next:o}:{}}}}async function Om(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{if(!Tm(o))return O("At least one repository search term or filter is required.",o);let s=r(),a=Em(o),{successes:c,failures:u}=await Xd(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(_p(w.query))}))),l=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=u.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(l.length===0){let w=d[0];return w?No(w.response,o):ye(new Error("Repository search produced no provider results"),o,void 0,P.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=_m(km(l.flatMap(w=>Ip(w.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,g=l.length===1?l[0]:void 0,h=l.length>1?Ma(l,p.length):g?.response.data.pagination,y=h?va(h):void 0,S=f.length>0,C=$P({repositories:f,pagination:y},o),x=Da(d),T;if(o.owner&&di(o)){let w=(Array.isArray(o.keywords)?o.keywords:[o.keywords]).filter(A=>typeof A=="string"&&A.trim().length>0).slice(0,3),b=w.some(A=>f.some(M=>M.repo?.toLowerCase()===A.toLowerCase()));if(w.length>0&&!b)try{let A=await U(n);for(let M of w){let H=await oi(A,String(o.owner),M);if(H.renamed){T={warning:`No repositories matched under owner "${o.owner}", but "${o.owner}/${M}" now resolves to "${H.owner}/${H.repo}" \u2014 the repository may have been transferred. Retry scoped to owner:"${H.owner}" (see next.retryUnderCanonicalOwner).`,next:{retryUnderCanonicalOwner:{tool:"ghSearchRepos",query:{...o,owner:H.owner,keywords:[H.repo]},why:"Re-run scoped to the repository's current owner after a detected transfer.",confidence:"exact"}}};break}}}catch{}}let L=[...x??[],...T?[T.warning]:[],...!S&&!T?['No repositories matched. Keywords are ANDed \u2014 try fewer or broader keywords, drop a topic/filter (topics are sparse), or add match:"readme" for full-text search.']:[]],k={...C.data,...L.length>0?{warnings:L}:{},...T?{next:T.next}:{}};return oe(o,k,S,P.GITHUB_SEARCH_REPOSITORIES,{rawResponse:Im([...l,...d])})}catch(s){return ye(s,o,void 0,P.GITHUB_SEARCH_REPOSITORIES)}},{toolName:P.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}function jP(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0,o=typeof r?.status=="number"?r.status:void 0,i=typeof t.path=="string"?t.path.replace(/\/+$/,""):"",s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):"",a=i.split("/").pop()||t.repo,c=o===404?{retryParent:{tool:"ghViewRepoStructure",query:{owner:t.owner,repo:t.repo,...s?{path:s}:{},...t.branch?{branch:t.branch}:{}},why:"Retry at the parent directory \u2014 the path or branch may be wrong.",confidence:"low"},searchPath:{tool:"ghSearchCode",query:{owner:t.owner,repo:t.repo,match:"path",keywords:[a]},why:"Locate the path by name in case it moved or was renamed.",confidence:"low"}}:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...c?{next:c}:{}}}function zP(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&yr(o))continue;let i=r.files.filter(a=>!cn(a)),s=r.folders.filter(a=>!yr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function Fm(e){let{queries:t,authInfo:n}=e,r=De(n);return ee(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch,u=c??await s.provider.resolveDefaultBranch(a),l=await ct(o,()=>s.provider.getRepoStructure(Ca(o,u))),d=u,m;if(l.ok===!1&&c){let C=l.result.error;if((typeof C=="object"&&C!==null?C.status:void 0)===404){let T=await s.provider.resolveDefaultBranch(a);if(T!==c){let L=await ct(o,()=>s.provider.getRepoStructure(Ca(o,T)));L.ok!==!1&&(l=L,d=T,m=`Branch/ref '${c}' was not found. Showing '${T}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(l.ok===!1)return jP(l.result,o);let p=zP(l.response.data.structure),f=Object.keys(p).length>0,g=Mp(l.response.data,o,p,d);m&&(g.branchFallback={requestedBranch:c,actualBranch:d,warning:m});let h=g.structure?.find(C=>(C.files?.length??0)>0),y=String(o.path??"").replace(/\/+$/,""),S=h?(()=>{let C=h.dir==="."?h.files[0]:`${h.dir}/${h.files[0]}`;return y?`${y}/${C}`:C})():void 0;return g.next={...S?{fetchFile:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:S,...d?{branch:d}:{}},why:"Read the first listed file",confidence:"low"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:o.owner,repo:o.repo,path:String(o.path??""),type:"directory",...d?{branch:d}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},oe(o,g,f,P.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return ye(s,o,"Failed to explore repository structure",P.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:P.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}import{existsSync as vm}from"fs";import{delimiter as WP,dirname as VP,join as Dm}from"path";function Mm(){return process.platform==="win32"?"npm.cmd":"npm"}function KP(){let e=VP(process.execPath);return Dm(e,Mm())}function YP(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function XP(){let e=(process.env.PATH??"").split(WP).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...YP()])]}function qP(){let e=KP();if(vm(e))return{command:process.execPath,argsPrefix:[e]};let t=Mm();for(let n of XP()){let r=Dm(n,t);if(vm(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var JP=["view","search","ping","config","whoami"],ZP=[...Ar,...qd];async function jt(e,t,n={}){if(!JP.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Zd(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=qP(),c=await kr(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:ZP});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var xn="https://registry.npmjs.org",pi=null;async function mi(){if(pi)return pi;try{let e=await jt("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 pi=t,t}}catch{}return pi=xn,xn}var Qr=new Map,ex=5,Na=3e4;function $r(e){try{return new URL(e).host||e}catch{return e}}var Ga=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}};function Nm(e,t=Date.now()){let n=Qr.get($r(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Na)throw new Ga($r(e),Na-r);n.state="half-open"}}function Ha(e){let t=Qr.get($r(e));t&&(t.failures=0,t.state="closed")}function Gm(e,t=Date.now()){let n=$r(e),r=Qr.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=ex&&(r.state="open",r.openedAt=t)),Qr.set(n,r)}function Hm(e,t=Date.now()){let n=Qr.get($r(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Na:!1}import{z as E}from"zod";var fi=E.looseObject({name:E.string(),version:E.string(),repository:E.union([E.string(),E.object({url:E.string().optional(),type:E.string().optional(),directory:E.string().optional()})]).optional(),main:E.string().optional(),module:E.string().optional(),type:E.string().optional(),exports:E.unknown().optional(),types:E.string().optional(),typings:E.string().optional(),description:E.string().optional(),keywords:E.array(E.string()).optional(),license:E.union([E.string(),E.object({type:E.string().optional()})]).optional(),homepage:E.string().optional(),author:E.union([E.string(),E.object({name:E.string().optional(),email:E.string().optional(),url:E.string().optional()})]).optional(),maintainers:E.array(E.object({name:E.string().optional(),email:E.string().optional()})).optional(),engines:E.record(E.string(),E.string()).optional(),dependencies:E.record(E.string(),E.string()).optional(),devDependencies:E.record(E.string(),E.string()).optional(),peerDependencies:E.record(E.string(),E.string()).optional(),time:E.record(E.string(),E.string().optional()).optional()}),tx=E.looseObject({package:E.looseObject({name:E.string().nullish(),version:E.string().nullish(),description:E.string().nullish(),links:E.looseObject({npm:E.string().nullish(),homepage:E.string().nullish(),repository:E.string().nullish()}).nullish()}),score:E.looseObject({final:E.number().nullish(),detail:E.looseObject({quality:E.number().nullish(),popularity:E.number().nullish(),maintenance:E.number().nullish()}).nullish()}).nullish()}),Bm=E.looseObject({objects:E.array(tx),total:E.union([E.number(),E.string()]).optional()}),nx=E.union([E.string(),E.boolean(),E.number(),E.null(),E.record(E.string(),E.unknown())]);var rx=6e4;function Um(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function ox(e,t,n,r){e&&St({limit_type:"primary",retry_after_seconds:Um(r),api_method:t,api_url:n,provider:e})}function ix(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(cr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Fl(r),e.status===429&&ox(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function sx(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=Um(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Xe(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=rx,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:u,packageRegistry:l}=t,d=e;if(a){let R=e.includes("?")?"&":"?";d=`${e}${R}version=${encodeURIComponent(Mt)}`}let m={"User-Agent":`Octocode-MCP/${Mt}`,...i},p=globalThis.fetch;if(!p)throw new Error(cr.FETCH_NOT_AVAILABLE.message);Nm(d);let f,g=n+1;for(let R=1;R<=g;R++){if(c?.aborted)throw new Error("Request aborted");try{let h=await p(d,{method:s,headers:m,signal:c});if(!h.ok)throw ix(h,s,d,l,u);if(h.status===204)return Ha(d),null;let y=await h.json();return Ha(d),y}catch(h){let y=h;if(c?.aborted||h instanceof Error&&h.name==="AbortError")throw new Error("Request aborted");if(y&&y.retryable===!1)throw h;if(f=h instanceof Error?h:new Error(String(h)),R===g)break;let S=sx(R,r,o,y);await new Promise(C=>setTimeout(C,S))}}throw Gm(d),new Error(cr.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}function xt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var ax="https://api.npmjs.org/downloads/point/last-week";function we(e){return e===void 0?0:N(e)}async function hi(e){try{let t=`${ax}/${encodeURIComponent(e)}`,n=await Xe(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:we(n)}}catch{return{rawResponseChars:0}}}function Qm(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 $m(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 cx(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function gi(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=xt(e.repository):(e.repository.url&&(r=xt(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:cx(e),...o?{repositoryDirectory:o}:{},...Qm(e.exports)?{exports:Qm(e.exports)}:{},...$m(e.bin,e.name)?{bin:$m(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 ux(e){return typeof e.links?.repository=="string"?xt(e.links.repository):typeof e.repository=="string"?xt(e.repository):typeof e.repository?.url=="string"?xt(e.repository.url):null}function jm(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:ux(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 Ba(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function zm(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 lx=3e3;function Ua(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 Qa(e){try{let t=await mi(),n=Ba(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Xe(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=we(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Xe(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:we(i)}}catch{return{rawResponseChars:0}}}async function Ri(e,t,n){let[r,o]=await Promise.all([hi(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Qa(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 yi(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function dx(e,t){try{let n=await jt("view",[e,"--json"],{timeout:lx});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,...yi(c)?{}:{errorDetail:c},rawResponseChars:we(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=we(o),s=fi.safeParse(o);return s.success?{pkg:gi(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,...yi(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function px(e,t){try{let n=await mi(),r=Ba(e),o=`${n}/${r}/latest`,i;try{i=await Xe(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(u){let l=u instanceof Error?u.message:String(u);return l.includes("404")||l.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:l,rawResponseChars:0}}let s=we(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=fi.safeParse(i);return a.success?{pkg:gi(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,...yi(r)?{}:{errorDetail:r},rawResponseChars:0}}}function mx(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function $a(e,t){let n=0,r;for(let o of mx(e)){let i;try{i=await Xe(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);yi(u)||(r=u);continue}if(n+=we(i),!i||typeof i!="object")continue;let s=fi.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:gi(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Si(e,t=!1){let[n,r]=await Promise.allSettled([dx(e,t),px(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?Ri(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function Wm(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Si(e,t);if(!r){if(o){let s=Ua(o);if(s&&n){let a=await $a(e,t);if(a.pkg){let c=await Ri(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function fx(e,t,n,r=0){let o=Math.max(t+r,t),i=await jt("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:we(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=we(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let l=[...a].sort((f,g)=>{let R=f?.score?.final??0;return(g?.score?.final??0)-R}).slice(r,r+t),d=await Promise.all(l.map(async f=>{if(!f||typeof f!="object")return null;let g=f;if(!g.name)return null;if(n){let R=await Si(g.name,!0);if(R.pkg)return R}return{pkg:jm(g),rawResponseChars:0}})),m=d.map(f=>f?.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function hx(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${xn}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Xe(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`Could not reach the npm search API (${f instanceof Error?f.message:String(f)}). The package may not exist, or the registry search endpoint is unavailable.`,hints:['Verify the exact package name / scope (e.g. "@scope/name")',"For an exact known name, query it directly instead of a keyword search","Ensure the npm registry is accessible from this environment"]}}let a=we(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Bm.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let l=[...c.data.objects].sort((f,g)=>{let R=f.score?.final??0;return(g.score?.final??0)-R}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),d=await Promise.all(l.map(async f=>{if(n){let g=await Si(f.name,!0);if(g.pkg)return g}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?xt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=d.map(f=>f.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+g.rawResponseChars,0);return{packages:m,totalFound:zm(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 ja(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 Xe(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:we(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:we(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"?xt(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:we(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function za(e,t,n,r=0){try{let o=await fx(e,t,n,r);if(!("error"in o))return o}catch{}return hx(e,t,n,r)}async function Wa(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}):hi(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Qa(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}function zt(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function Vm(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}async function Va(e,t,n,r=0){let o=se("npm-search",{name:e,limit:t,metadata:n,from:r});return fe(o,async()=>{if(Hm(xn)){if(r===0&&t===1&&zt(e)){let l=await $a(e,n);if(l.pkg){let d=await Ri(e,l.pkg,l.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let u=await ja(e,t);return!("error"in u)&&u.packages.length>0?u:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&zt(e)){let u=await Wm(e,n,t===1);if("error"in u){if(!Ua(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await za(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Wa(s);let a=Vm(e);if(a!==e){let u=await za(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return Wa(u)}let c=await ja(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function Km(e){let t=zt(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Va(e.name,n,!0,r)}function Ka(e){if(e===void 0)return;let n=(Array.isArray(e)?e.join(" "):e).trim();return n.length>0?n:void 0}var yx=/\b(?:404|e404)\b|not\s+found|no\s+such\s+package|does\s+not\s+exist/i;function Ya(e){return yx.test(e)}function Rx(e){return"error"in e}function bi(e){return"npmUrl"in e}function Sx(e){return bi(e)&&e.path?e.path:e.name}function bx(e){return bi(e)?e.repoUrl:e.repository}function Cx(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}var Px={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function xx(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=s=>s.replace(/\.git$/,""),r=t.match(/^(github|gitlab|bitbucket):(.+)$/i);if(r&&r[1]&&r[2]){let s=Px[r[1].toLowerCase()];return n(`https://${s}/${r[2]}`)}let o=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(o&&o[1]&&o[2])return n(`https://${o[1]}/${o[2]}`);let i=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(i&&i[1]){let s=i[1].replace(/^[^@/]+@/,"");return n(`https://${s}`)}return n(t)}function Xa(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 Ym(e,t){let n=Xa(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},latestRelease:{tool:"ghListReleases",query:{owner:r,repo:o},why:"npm latest can diverge from the repo release line \u2014 verify against the repo releases/tags (requires ENABLE_RELEASES)"},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function wx(e){let t=Sx(e),n=xx(bx(e)),r={name:t};bi(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=Cx(bi(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=Ym(n,o);return i&&(r.next=i),r.version&&Xa(n)&&(r.warnings=[`npm version ${r.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`]),r}function Tx(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=Xa(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:Ym(i.repository,i.repositoryDirectory)});let{repository:u,repositoryDirectory:l,next:d,...m}=i;return{...m,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function Ex(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,u=s&&o>=a?o+1:a;return{currentPage:o,totalPages:u,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function Xm(e){return ee(e.queries,async t=>{try{let n=t.packageName??Ka(t.keywords);if(!n)return O("Provide a packageName or keywords for package search",t);let r=await Km({name:n,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(Rx(r)){if(Ya(r.error)){let d=zt(n);return oe(t,{packages:[],hints:[d?`No package published under the exact name "${n}". Check the spelling, and try the scoped (@scope/name) vs unscoped form.`:`No packages matched "${n}". Try different or fewer keywords, or search by an exact package name.`]},!1,P.PACKAGE_SEARCH,{rawResponse:r})}return O(r.error,t,{rawResponse:r})}let o=r.packages,i=o.map(wx),s=i.length>0,a=o.length>1||r.totalFound>1,c=Ex(t,r.totalFound,i.length,a),l={...Tx(i),pagination:c};return oe(t,l,s,P.PACKAGE_SEARCH,{rawResponse:r.rawResponseChars??r})}catch(n){return O(n,t,{toolName:P.PACKAGE_SEARCH})}},{toolName:P.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{ContentSanitizer as Dx}from"@octocodeai/octocode-engine/contentSanitizer";import qm from"path";import{pathValidator as Jm}from"@octocodeai/octocode-engine/pathValidator";import{redactPath as jr}from"@octocodeai/octocode-engine/pathUtils";var Ee={pathValidationFailed:(e,t,n)=>new Se(G.PATH_VALIDATION_FAILED,t||`Path validation failed: ${jr(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=jr(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 Se(G.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Se(G.FILE_READ_FAILED,`Failed to read file: ${jr(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Se(G.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)}). Use startLine/endLine, matchString, or charOffset/charLength to read a bounded slice.`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Se(G.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${jr(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Se(G.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Se(G.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 Se(G.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Se(G.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{getConfigSync as Zm}from"@octocodeai/config";function Lx(e=Zm().local.allowedPaths){for(let t of e)typeof t=="string"&&t.trim()!==""&&Jm.addAllowedRoot(t)}function Le(e,t){if(!e.path?.trim()){let s=Ee.pathValidationFailed("","path is required");return{isValid:!1,errorResult:O(s,e,{toolName:t})}}Lx();let n=process.env.WORKSPACE_ROOT?.trim()||Zm().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=qm.isAbsolute(r)?r:qm.resolve(n,r),i=Jm.validate(o);if(!i.isValid){let s=Ee.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:O(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}import{open as Ax,readFile as kx,stat as _x}from"fs/promises";var wt={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 ef(e,t){return n=>t}function qa(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ja(e,t,n){return{...e,...qa(t,n)}}function tf(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 nf(e,t){try{return{fileStats:await _x(t)}}catch(n){let r=Ee.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:O(r,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function rf(e){let t=e.startLine!==void 0&&e.endLine!==void 0;return e.minify??(e.fullContent===!0||t?"none":"standard")}function of(e,t,n){return n!=="none"?!1:t>wt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.charLength}function sf(e,t,n){let r=Ee.fileTooLarge(e.path,n,wt.LARGE_FILE_THRESHOLD_KB);return O(r,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function af(e,t){let n=Ee.binaryFileUnsupported(e.path);return O(n,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function cf(e){let n=Buffer.alloc(8192),r;try{r=await Ax(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let u=i[c];if(u===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let l=u===9||u===10||u===13;u<32&&!l&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(ef("binary sample handle close",void 0))}}async function uf(e,t){try{return{content:await kx(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?Ee.fileAccessFailed(e.path,r):Ee.fileReadFailed(e.path,r);return{errorResult:O(i,e,{toolName:P.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function lf(e,t){return{status:"empty",errorCode:G.NO_MATCHES,totalLines:t}}function Ix(e,t,n){let r=Co(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:lf(e,n)};let o=r.lines.join(`
|
|
55
|
+
`),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,u,l,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(u=m.start,l=p.end,d=r.matchRanges)}return{resultContent:o,isPartial:!0,actualStartLine:u,actualEndLine:l,matchRanges:d,matchedLines:r.matchingLines,warnings:[c]}}function Ox(e){return e.startLine!==void 0&&e.endLine!==void 0}function Fx(e,t,n){let r=String(n).length;return e.slice(t-1,n).map((o,i)=>`${String(t+i).padStart(r," ")}\u2192 ${o}`).join(`
|
|
56
|
+
`)}function vx(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:G.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:G.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:Fx(t,i,s),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function df(e,t,n){let r=t.split(`
|
|
57
|
+
`),o=Ve(t);return e.matchString?Ix(e,r,o):Ox(e)?vx(e,r,o):{resultContent:t,isPartial:!1}}async function pf(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,u=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let l="char-limit",d=s;if(s!==void 0){let g=await Eo(e,u,s,r);l=g.chunkMode,d=g.length}let m=xo(e,u,d,s!==void 0?{pageSize:s}:void 0),p;if(m.hasMore&&l==="char-limit"&&wo(m.paginatedContent)){let g=m.charOffset+m.charLength;p=await To(e,g,r)}let f=Zo("localGetFileContent",{path:r,charLength:s??m.charLength,minify:t.minify},m);return{windowedContent:m.paginatedContent,pagination:m,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:l,nextBlockChar:p,next:f,showPagination:s!==void 0||i>0||a}}async function mf(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),u=i?F.applyContentViewMinification(t.resultContent,c):t.resultContent,l=await pf(u,e,o);l.autoPaginateWarning&&a.push(l.autoPaginateWarning);let d=t.isPartial||l.pagination.hasMore;return{path:c,content:l.windowedContent,contentView:s,returnedChars:l.windowedContent.length,...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},...t.matchedLines!==void 0&&{matchedLines:t.matchedLines}},...n.mtime&&{modified:n.mtime.toISOString()},...l.showPagination&&{pagination:{...Ms(l.pagination),chunkMode:l.chunkMode,...l.nextBlockChar!==void 0&&{nextBlockChar:l.nextBlockChar}}},...l.next?{next:l.next}:{},...a.length>0&&{warnings:a}}}async function Za(e,t,n,r,o,i,s){let a=await pf(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",returnedChars:a.windowedContent.length,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...qa(r,o),...a.showPagination&&{pagination:{...Ms(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function ff(e,t){return typeof e.content!="string"?e:{...e,contentView:t}}function ec(e,t){let n=Dx.sanitizeContent(e,t);return{text:n.content,warning:n.hasSecrets?`Secrets detected and redacted: ${n.secretsDetected.join(", ")}`:void 0}}async function hf(e){let t=Nt();try{let n=Le(e,P.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=tf(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await nf(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,u=c/1024;if(await cf(o))return Q(af(e,o),c);let l=rf(e);if(of(e,u,l))return Q(sf(e,o,u),c);let{content:d,errorResult:m}=await uf(e,o);if(m||d===void 0)return m;let p=d.length,f=Buffer.byteLength(d,"utf-8"),g=d,R=e.matchString!==void 0&&l!=="none",h=R?"none":l,y=R&&e.minify!==void 0?`minify:"${e.minify}" is not applied to matchString extractions \u2014 matched slices are returned verbatim so the content always contains the matched text.`:void 0,S=h==="standard"||h==="symbols",C=S?"standard":"none",x;if(h==="symbols"){let b=F.extractSignatures(g,i);if(b===null){let A=Po(g,i);if(A!==null){let M=ec(A,i);return Q(await Za(e,M.text,Ve(g),p,f,M.warning,t),p)}x=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(b!==null){let A=Ve(g),M=F.applyContentViewMinification(b,i),H=ec(M,i);return Q(await Za(e,H.text,A,p,f,H.warning,t),p)}}let T=Ve(g),L=df(e,g,t),k=b=>{let A=b.content;if(typeof A!="string")return b;let M=ec(A,i),H=[...x?[x]:[],...y?[y]:[],...M.warning?[M.warning]:[]],I=b.warnings??[];return{...b,content:M.text,...H.length>0&&{warnings:[...I,...H]}}};if(L.earlyResult){let b=L.earlyResult.content,A=S&&typeof b=="string"?{...L.earlyResult,content:F.applyContentViewMinification(b,i)}:L.earlyResult;return Q(Ja(k(ff(A,C)),p,f),p)}let w=await mf(e,L,s,T,t,S,C);return Q(Ja(k(w),p,f),p)}catch(n){return O(n,e,{toolName:P.LOCAL_FETCH_CONTENT})}}async function gf(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=xe(kt,n);return r.ok===!1?r.error:await hf(r.data)}}),{toolName:P.LOCAL_FETCH_CONTENT,finalize:Mx()},e)}function Mx(){return({results:e})=>{let t={results:Nx(e)},n=mn(t.results);n&&(t.base=n);let r=fn(t.results);return r&&(t.shared=r),{structuredContent:Qe(t),text:Gx(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function Nx(e){return e.map(t=>{let n=structuredClone(t.data),r=typeof n.path=="string"?n.path:void 0;if(t.status!=="error"&&r){let o=ei(r);o&&(n.fileType=o)}return{...t,data:n}})}function Gx(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=Bt({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","returnedChars","fileType","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Bt({shared:e.shared},["shared"]).trimEnd()),t.join(`
|
|
60
58
|
`).trimEnd()+`
|
|
61
|
-
`}function wn(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 jr(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}function Ja(e){let t=e.indexOf("{");if(t===-1)return[e];let n=e.indexOf("}",t);if(n===-1)return[e];let r=e.slice(0,t),o=e.slice(t+1,n).split(","),i=e.slice(n+1);return o.flatMap(s=>Ja(`${r}${s}${i}`))}function pf(e){let t=new Map,n=0,r=!1,o=0,i=0,s=new Set;for(let a of e){for(let c of a.entries)t.has(c.path)||t.set(c.path,c);n+=a.totalDiscovered,r=r||a.wasCapped,o+=a.skipped,i+=a.permissionDenied;for(let c of a.warnings)s.add(c)}return{entries:[...t.values()],totalDiscovered:n,wasCapped:r,skipped:o,permissionDenied:i,warnings:[...s]}}function mf(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+jr(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${wn(r)})`}function ff(e,t){let n=e.length,r=t.itemsPerPage||20,o=Math.max(1,Math.ceil(n/r)),i=t.page||1,s=Math.min(i,o),a=i>o,c=(s-1)*r,u=Math.min(c+r,n),l=s<o;return{paginatedEntries:e.slice(c,u),endIdx:u,pagination:{currentPage:s,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:l,...l?{nextPage:s+1}:{},...a?{outOfRange:!0}:{}}}}function Si(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}function hf(e){let t=e.find(r=>r.type==="file");if(t)return{fetch:{tool:"localGetFileContent",query:{path:t.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"}};let n=e.find(r=>r.type==="directory");if(n)return{viewStructure:{tool:"localViewStructure",query:{path:n.path},why:"Orient inside the first matched directory before reading files.",confidence:"exact"}}}var Tx=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function Ex(e,t){let n=t??Tx,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function gf(e){let t=e.detail==="full",n=e.detail==="modified"||t,r=n||(e.sortBy||"modified")==="modified";try{let o=Le(e,P.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:Ex(i.path,i.excludeDir)},{warnings:a,query:c}=Ix(s),u=e.limit??1e4,l={path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,extensions:c.extensions,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.time?.modifiedWithin,modifiedBefore:c.time?.modifiedBefore,accessedWithin:c.time?.accessedWithin,sizeGreater:c.size?.greater,sizeLess:c.size?.less,permissions:c.permissions,executable:c.access==="executable",readable:c.access==="readable",writable:c.access==="writable",excludeDir:c.excludeDir,limit:1e4},d=c.pathPattern?Ja(c.pathPattern):void 0,m=d&&d.length>1?pf(d.map(Y=>F.queryFileSystem({...l,pathPattern:Y}))):F.queryFileSystem({...l,pathPattern:c.pathPattern}),p=m.totalDiscovered,f=m.wasCapped,g=m.entries.map(Y=>Lx(Y,r)),R=e.sortBy||"modified";Ax(g,R,r);let h=g.slice(0,u),y=_x(h,t,n),S=y.length,C=e.itemsPerPage||20,x=e.page||1,T=Math.max(1,Math.ceil(S/C)),L=(x-1)*C,_=Math.min(L+C,S),w=y.slice(L,_),b=S>0&&L>=S,A=w,M=[...m.warnings,...Si(m),...f?[`results capped at ${1e4} during the walk before sorting \u2014 sortBy:"${R}" only orders that partial set, not the true top-N across the whole tree`]:[],...b?[`page:${x} is out of range (only ${T} page(s), ${S} total file(s)) \u2014 returned 0 files. Use page:1..${T}.`]:[]],H=[...a,...M],k=x<T,Z={...hf(A)??{},...k?{nextPage:Rn(P.LOCAL_FIND_FILES,{...i,page:x+1},"Continue to the next page of matched files.")}:{}},v={...S===0?{status:"empty"}:{},path:i.path,files:A,pagination:{currentPage:x,totalPages:T,filesPerPage:C,totalFiles:S,hasMore:k,...k?{nextPage:x+1}:{},...f||p>S?{totalFilesFound:p}:{},...b?{outOfRange:!0}:{}},...Object.keys(Z).length>0?{next:Z}:{},...H.length>0&&{warnings:H}};return Q(v,m.entries.reduce((Y,ae)=>Y+ae.path.length,0))}catch(o){return O(o,e,{toolName:P.LOCAL_FIND_FILES})}}function Lx(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 Ax(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 _x(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=wn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var kx=/^\d+[hdwm]$/;function Ix(e){let t=[],n=e.time;if(!n)return{warnings:t,query:e};let r={...n},o=[{key:"modifiedBefore",value:n.modifiedBefore},{key:"modifiedWithin",value:n.modifiedWithin},{key:"accessedWithin",value:n.accessedWithin}];for(let{key:i,value:s}of o)s&&!kx.test(s)&&(t.push(`time.${i}="${s}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete r[i]);return{warnings:t,query:{...e,time:r}}}async function yf(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=xe(kt,n);return r.ok===!1?r.error:await gf(r.data)}}),{toolName:P.LOCAL_FIND_FILES},e)}import{readFileSync as vx}from"node:fs";import{posix as Sf}from"node:path";var Ox=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","async","await"]);function bi(e){return e?!Ox.has(e):!1}import{posix as Ci}from"node:path";var ec=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],Fx={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function Rf(e){return e.split("\\").join("/")}function Wt(e,t,n){let r=Rf(e);if(!r.startsWith(".")&&!r.startsWith("/"))return null;let o=Ci.dirname(Rf(t)),i=r.startsWith("/")?r.slice(1):Ci.normalize(Ci.join(o,r)),s=[];if(ec.some(c=>i.endsWith(c))){s.push(i);for(let[c,u]of Object.entries(Fx))if(i.endsWith(c)){s.push(i.slice(0,-c.length)+u);break}}else{s.push(i);for(let c of ec)s.push(`${i}${c}`);for(let c of ec)s.push(Ci.join(i,`index${c}`))}for(let c of s)if(n.has(c))return c;return null}var Dx=1e6,bf=["node_modules","dist","build","out","coverage",".git","target",".next",".cache"];function Mx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nx(e,t){let n=e.match(new RegExp(`\\b${Mx(t)}\\b`,"g"));return n?n.length:0}function Cf(e,t,n){let r=F.getSupportedGraphFactExtensions(),i=F.queryFileSystem({path:e,recursive:!0,showHidden:!1,entryType:"f",extensions:r,excludeDir:t,stopAtLimit:!0,limit:n}).entries,s=i.length>=n,a=new Set(i.map(f=>Sf.normalize(f.relativePath.split("\\").join("/")))),c=new Map,u=new Map,l=new Set,d=new Set,m=new Map,p=0;for(let f of i){let g=Sf.normalize(f.relativePath.split("\\").join("/"));if((f.size??0)>Dx){p++;continue}let R;try{R=vx(f.path,"utf-8")}catch{p++;continue}let h=F.extractGraphFacts(R,g);if(!h){p++;continue}let y;try{y=JSON.parse(h)}catch{p++;continue}let S=(y.declarations??[]).filter(b=>bi(b.name)).map(b=>({id:b.id,name:b.name,kind:b.kind,line:b.line,exported:b.exported??!1})),C=new Map;for(let b of S)!b.exported||C.has(b.name)||C.set(b.name,Nx(R,b.name));let x=(y.exports??[]).filter(b=>b.source&&b.name!=="*").map(b=>({specifier:b.source,localName:b.localName??b.name,importedName:b.name,line:b.line})),T=(y.calls??[]).filter(b=>b.kind==="dynamic-import").map(b=>b.callee),L={relativePath:g,declarations:S,imports:(y.imports??[]).map(b=>({specifier:b.specifier,localName:b.localName,importedName:b.importedName,line:b.line})),namedReexports:x,calls:(y.calls??[]).filter(b=>b.kind!=="dynamic-import").map(b=>({caller:b.caller,callee:b.callee})),referenceCounts:C};c.set(g,L);let _=new Set,w=new Set;for(let b of[...L.imports,...L.namedReexports]){let A=Wt(b.specifier,g,a);A&&A!==g&&_.add(A)}for(let b of T){let A=Wt(b,g,a);A&&A!==g&&(_.add(A),w.add(A),d.add(A))}for(let b of y.exports??[]){if(!b.source||b.name!=="*")continue;let A=Wt(b.source,g,a);if(A&&A!==g){_.add(A),l.add(A);let M=m.get(A)??[];M.push(g),m.set(A,M)}}u.set(g,{relativePath:g,importsFiles:_,dynamicImportsFiles:w})}return{facts:c,fileGraph:u,filesScanned:c.size,filesSkipped:p,truncated:s,starReexportTargets:l,dynamicImportTargets:d,starReexporters:m}}import{readFileSync as Gx}from"node:fs";import{posix as tc}from"node:path";var Hx=/(\.(test|spec)\.[^/]+$)|(^|\/)(__tests__|tests?)\//i,Bx=/\.(mjs|cjs|jsx?|tsx?)$/i;function Ux(e){let t=[];for(let n of e.split(/\s+/)){let r=n.includes("=")?[n,n.slice(n.indexOf("=")+1)]:[n];for(let o of r){let i=o.replace(/^["']|["']$/g,"");Bx.test(i)&&!i.startsWith("-")&&t.push(i)}}return t}function nc(e){return e.split("\\").join("/")}function Pf(e){return e.replace(/^\.\//,"")}var Qx=["dist","build","out"],$x={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function xf(e){for(let[t,n]of Object.entries($x))if(e.endsWith(t))return e.slice(0,-t.length)+n}function jx(e,t){let n=[],r=xf(e);r&&n.push(r);for(let o of Qx){let i=`${o}/`;if(!e.startsWith(i))continue;let a=`src/${e.slice(i.length)}`;n.push(a);let c=xf(a);c&&n.push(c)}return n.find(o=>t.has(o))}function zr(e,t){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let n of e)zr(n,t);return}if(e&&typeof e=="object")for(let n of Object.values(e))zr(n,t)}function wf(e,t,n,r){let o=[],i=new Set,s=!1;if(t&&t.length>0){let a=nc(e).replace(/\/$/,"");for(let c of t){let u=Pf(nc(c));u.startsWith(a+"/")&&(u=u.slice(a.length+1)),u=tc.normalize(u),r.has(u)?i.add(u):o.push(`entrypoint not found in scan: ${c} \u2014 pass it relative to the scanned path (e.g. "src/index.ts"), or as an absolute path under it`)}}else{let a;try{let c=tc.join(e,"package.json");a=JSON.parse(Gx(c,"utf-8"))}catch{}if(a){let c=[];if(zr(a.main,c),zr(a.exports,c),zr(a.bin,c),a.scripts&&typeof a.scripts=="object")for(let u of Object.values(a.scripts))typeof u=="string"&&c.push(...Ux(u));for(let u of c){let l=tc.normalize(Pf(nc(u))),d=r.has(l)?l:jx(l,r);d&&i.add(d)}}i.size===0&&(o.push("no entrypoints resolved from package.json \u2014 pass `entrypoints` explicitly, or every export in a reachable file will read as unreachable"),s=!0)}if(n)for(let a of r)Hx.test(a)&&i.add(a);return{entrypoints:[...i],warnings:o,lowConfidence:s}}function rc(e,t){let n=new Set,r=[];for(let o of t)n.has(o)||(n.add(o),r.push(o));for(;r.length>0;){let o=r.pop(),i=e.get(o);if(i)for(let s of i.importsFiles)n.has(s)||(n.add(s),r.push(s))}return n}function Tf(e){let t=0,n=new Map,r=new Map,o=new Set,i=[],s=[],a=[];for(let c of e.keys())if(!n.has(c))for(a.push({node:c,iterator:(e.get(c)?.importsFiles??new Set).values()}),n.set(c,t),r.set(c,t),t++,i.push(c),o.add(c);a.length>0;){let u=a[a.length-1],l=u.iterator.next();if(!l.done){let d=l.value;if(!n.has(d))n.set(d,t),r.set(d,t),t++,i.push(d),o.add(d),a.push({node:d,iterator:(e.get(d)?.importsFiles??new Set).values()});else if(o.has(d)){let m=r.get(u.node),p=n.get(d);r.set(u.node,Math.min(m,p))}continue}if(a.pop(),a.length>0){let d=a[a.length-1],m=r.get(d.node),p=r.get(u.node);r.set(d.node,Math.min(m,p))}if(r.get(u.node)===n.get(u.node)){let d=[],m;do m=i.pop(),o.delete(m),d.push(m);while(m!==u.node);(d.length>1||(e.get(d[0])?.importsFiles.has(d[0])??!1))&&s.push({files:d})}}return s}function Wr(e,t){return`${e}::${t}`}function oc(e,t,n,r,o,i,s){let a=Wr(e,t);if(s.has(a))return!1;if(n.has(e)||r.has(a))return!0;s.add(a);for(let c of o.get(a)??[])if(oc(c.file,c.localName,n,r,o,i,s))return!0;for(let c of i.get(e)??[])if(oc(c,t,n,r,o,i,s))return!0;return!1}function Ef(e,t,n,r,o,i){let s=new Set(t.declarations.filter(l=>l.exported).map(l=>l.name)),a=new Set;for(let l of s)oc(e,l,n,r,o,i,new Set)&&a.add(l);let c=l=>!s.has(l)||a.has(l),u=!0;for(;u;){u=!1;for(let l of s){if(a.has(l))continue;let d=t.calls.filter(f=>f.callee===l);if(d.some(f=>f.caller!==l&&c(f.caller))){a.add(l),u=!0;continue}let m=d.filter(f=>f.caller===l||!c(f.caller)).length;(t.referenceCounts.get(l)??0)-m>1&&(a.add(l),u=!0)}}return a}function Lf(e,t){let n=t.excludeDir&&t.excludeDir.length>0?t.excludeDir:bf,r=t.maxFiles??2e4,{facts:o,fileGraph:i,filesScanned:s,filesSkipped:a,truncated:c,dynamicImportTargets:u,starReexporters:l}=Cf(e,n,r),d=new Set(o.keys()),{entrypoints:m,warnings:p,lowConfidence:f}=wf(e,t.entrypoints,t.includeTests??!0,d);c&&p.push(`scan stopped at maxFiles (${r}) \u2014 results are partial, not a full-repo verdict`);let g=m.filter(v=>{let Y=o.get(v);return(i.get(v)?.importsFiles.size??0)===0&&(Y?.declarations.length??0)===0&&(Y?.namedReexports.length??0)===0}),R=g.length>0;R&&p.push(`${g.length} entrypoint file(s) parsed to no imports/exports (likely an extractor parse failure on that file) \u2014 reachability from them is unreliable, so "unreachable-file" results here are low-confidence and may be false positives: ${g.join(", ")}`);let h=rc(i,m),y=new Set(m),S=new Map([...i].map(([v,Y])=>[v,{relativePath:Y.relativePath,importsFiles:new Set([...Y.importsFiles].filter(ae=>!Y.dynamicImportsFiles.has(ae))),dynamicImportsFiles:new Set}])),C=rc(S,m),x=[...h].filter(v=>!C.has(v)).sort();x.length>0&&p.push(`${x.length} file(s) reachable only through a dynamic import() \u2014 lower confidence than static analysis, verify with lspGetSemantics before treating as proof: ${x.join(", ")}`);let T=new Map;for(let[v,Y]of o){let ae=new Map;for(let ie of Y.imports){let ce=Wt(ie.specifier,v,d);ce&&ae.set(ie.localName,ce)}T.set(v,ae)}let L=new Set,_=new Map;for(let v of h){let Y=o.get(v);if(!Y)continue;let ae=T.get(v);for(let ie of Y.imports){let ce=ae?.get(ie.localName);ce&&L.add(Wr(ce,ie.importedName))}for(let ie of Y.namedReexports){let ce=Wt(ie.specifier,v,d);if(!ce)continue;let _e=Wr(ce,ie.importedName),Et=_.get(_e)??[];Et.push({file:v,localName:ie.localName}),_.set(_e,Et)}}let w=new Map;for(let[v,Y]of l){let ae=Y.filter(ie=>h.has(ie));ae.length>0&&w.set(v,ae)}let b=new Set(w.keys()),A=[],M=Tf(i),H=new Map,k=[],B=0;for(let v of M){if(!v.files.every(ie=>!h.has(ie)))continue;let ae=B++;for(let ie of v.files)H.set(ie,ae);k.push({id:ae,files:v.files,reason:"mutually-referencing cluster with no path from any entrypoint \u2014 each file looks locally referenced by the others, but the cluster as a whole is unreachable"})}let Z=new Map;for(let[v,Y]of o){let ae=y.has(v),ie=h.has(v);for(let ce of Y.declarations){if(!ce.exported)continue;if(!ie){let Et=H.get(v);A.push({file:v,name:ce.name,kind:ce.kind,line:ce.line,reason:Et!==void 0?"dead-cluster":"unreachable-file",...Et!==void 0?{clusterId:Et}:{}});continue}if(ae||b.has(v)||u.has(v))continue;let _e=Z.get(v);_e||(_e=Ef(v,Y,y,L,_,w),Z.set(v,_e)),_e.has(ce.name)||A.push({file:v,name:ce.name,kind:ce.kind,line:ce.line,reason:"unreferenced-export",viaHeuristic:_.has(Wr(v,ce.name))?"reexport-chain":"lexical-count"})}}return{filesScanned:s,filesSkipped:a,entrypointsResolved:m,deadExports:A,deadClusters:k,warnings:p,...f||R?{confidence:"low"}:{}}}var zx=100;function Wx(e,t,n){let r=Math.max(1,Math.ceil(e.length/n)),o=Math.min(Math.max(1,t),r),i=(o-1)*n;return{pageItems:e.slice(i,i+n),currentPage:o,totalPages:r,hasMore:o<r,outOfRange:t>r}}async function Af(e){try{let t=Le(e,P.LOCAL_FIND_DEAD_CODE);if(!t.isValid)return t.errorResult;let n=Lf(t.sanitizedPath,e),r=e.itemsPerPage??zx,o=e.page??1,{pageItems:i,currentPage:s,totalPages:a,hasMore:c,outOfRange:u}=Wx(n.deadExports,o,r),l=[...n.warnings,...u?[`page:${o} is out of range (only ${a} page(s), ${n.deadExports.length} total candidates) \u2014 returned page ${s} instead.`]:[]],d={path:e.path,filesScanned:n.filesScanned,filesSkipped:n.filesSkipped,entrypointsResolved:n.entrypointsResolved,deadExports:i,deadClusters:n.deadClusters,pagination:{currentPage:s,totalPages:a,entriesPerPage:r,totalEntries:n.deadExports.length,hasMore:c,...u?{outOfRange:!0}:{}},...l.length>0?{warnings:l}:{},...n.confidence?{confidence:n.confidence}:{}};c&&(d.next={nextPage:Rn(P.LOCAL_FIND_DEAD_CODE,{...e,page:s+1},"Continue to the next page of dead-export candidates.")});let m=i[0];if(m){let p=t.sanitizedPath.replace(/\/+$/,"");d.next={...d.next,verifyReferences:{tool:le,query:{type:"references",uri:`${p}/${m.file}`,symbolName:m.name,lineHint:m.line,includeDeclaration:!1,groupByFile:!0},why:`Verify candidate "${m.name}" before any delete claim \u2014 zero references = confirmed dead. Repeat per candidate using each entry's file/name/line; start with viaHeuristic:"reexport-chain" candidates (most fragile).`,confidence:"high"}}}return d}catch(t){let n=Ee.toolExecutionFailed(P.LOCAL_FIND_DEAD_CODE,t instanceof Error?t:new Error(String(t)));return O(n,e,{toolName:P.LOCAL_FIND_DEAD_CODE})}}async function _f(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_FIND_DEAD_CODE,query:n,contextMessage:"localFindDeadCode execution failed",execute:async()=>{let r=xe(It,n);return r.ok===!1?r.error:await Af(r.data)}}),{toolName:P.LOCAL_FIND_DEAD_CODE},e)}import{validateRipgrepQuery as Pw}from"@octocodeai/octocode-core/schemas/runtime";var ic=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],ne={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,testPathPenalty:-3.5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},sc=2e3,ac=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,kf={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+['"]/]},Vr={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...kf},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...kf},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/]}},cc=/^\s*#{1,6}\s/,Kr=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,Vx=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,Kx=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,Yx=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,Xx=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,qx=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,Jx=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,Zx=new Set(["typescript","javascript","rust","python","go","java","scala"]),Pi=/\.([a-z0-9]+)$/i;function Yr(e){return Pi.exec(e)?.[1]?.toLowerCase()??""}function ew(e){let t=Yr(e);if(!t)return!1;for(let n of Zx)if(Vr[n].extensions.includes(t))return!0;return!1}function uc(e,t,n){if(n&&n!=="auto")return Vr[n];let r=Yr(e),o=(t??"").toLowerCase();for(let i of ic){let s=Vr[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of ic){let s=Vr[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Vr.generic}function xi(e){return Vx.test(e)?"generated":Yx.test(e)?"fixture":Kx.test(e)?"test":qx.test(e)?"config":Xx.test(e)?"docs":!Kr.test(e)&&(Jx.test(e)||ew(e))?"source":"unknown"}function lc(e){if(!e)return!1;if(Kr.test(e))return!0;let t=xi(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}function dc(e,t,n,r={}){if(t==="matchCount"){let m=[...e].sort(If);return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="path"){let m=[...e].sort((p,f)=>p.path.localeCompare(f.path));return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??sc,i=e,s=[],a=0;if(e.length>o){let m=[...e].sort(If);i=m.slice(0,o),s=m.slice(o),a=s.length}let c=hc(i,n),u=i.map(m=>{try{return{file:m,s:gc(m,n,c)}}catch{return{file:m,s:tw()}}});u.sort((m,p)=>{if(p.s.score!==m.s.score)return p.s.score-m.s.score;let f=(p.file.matchCount??0)-(m.file.matchCount??0);return f!==0?f:m.file.path.localeCompare(p.file.path)});let l=[...u.map(m=>m.file),...s],d={files:r.sortReverse?l.reverse():l,cappedCandidates:a};return r.debug&&(d.debug=new Map(u.map(m=>[m.file.path,m.s]))),d}function tw(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function If(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function Xr(e,t){for(let n of e)if(n.test(t))return!0;return!1}function wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pc(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function mc(e,t,n){if(e.indexOf(`
|
|
59
|
+
`}function wn(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 zr(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}function tc(e){let t=e.indexOf("{");if(t===-1)return[e];let n=e.indexOf("}",t);if(n===-1)return[e];let r=e.slice(0,t),o=e.slice(t+1,n).split(","),i=e.slice(n+1);return o.flatMap(s=>tc(`${r}${s}${i}`))}function yf(e){let t=new Map,n=0,r=!1,o=0,i=0,s=new Set;for(let a of e){for(let c of a.entries)t.has(c.path)||t.set(c.path,c);n+=a.totalDiscovered,r=r||a.wasCapped,o+=a.skipped,i+=a.permissionDenied;for(let c of a.warnings)s.add(c)}return{entries:[...t.values()],totalDiscovered:n,wasCapped:r,skipped:o,permissionDenied:i,warnings:[...s]}}function Rf(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+zr(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${wn(r)})`}function Sf(e,t){let n=e.length,r=t.itemsPerPage||20,o=Math.max(1,Math.ceil(n/r)),i=t.page||1,s=Math.min(i,o),a=i>o,c=(s-1)*r,u=Math.min(c+r,n),l=s<o;return{paginatedEntries:e.slice(c,u),endIdx:u,pagination:{currentPage:s,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:l,...l?{nextPage:s+1}:{},...a?{outOfRange:!0}:{}}}}function Ci(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}function bf(e){let t=e.find(r=>r.type==="file");if(t)return{fetch:{tool:"localGetFileContent",query:{path:t.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"}};let n=e.find(r=>r.type==="directory");if(n)return{viewStructure:{tool:"localViewStructure",query:{path:n.path},why:"Orient inside the first matched directory before reading files.",confidence:"exact"}}}var Hx=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function Bx(e,t){let n=t??Hx,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Cf(e){let t=e.detail==="full",n=e.detail==="modified"||t,r=n||(e.sortBy||"modified")==="modified";try{let o=Le(e,P.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:Bx(i.path,i.excludeDir)},{warnings:a,query:c}=zx(s),u=e.limit??1e4,l={path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,extensions:c.extensions,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.time?.modifiedWithin,modifiedBefore:c.time?.modifiedBefore,accessedWithin:c.time?.accessedWithin,sizeGreater:c.size?.greater,sizeLess:c.size?.less,permissions:c.permissions,executable:c.access==="executable",readable:c.access==="readable",writable:c.access==="writable",excludeDir:c.excludeDir,limit:1e4},d=c.pathPattern?tc(c.pathPattern):void 0,m=d&&d.length>1?yf(d.map(X=>F.queryFileSystem({...l,pathPattern:X}))):F.queryFileSystem({...l,pathPattern:c.pathPattern}),p=m.totalDiscovered,f=m.wasCapped,g=m.entries.map(X=>Ux(X,r)),R=e.sortBy||"modified";Qx(g,R,r);let h=g.slice(0,u),y=$x(h,t,n),S=y.length,C=e.itemsPerPage||20,x=e.page||1,T=Math.max(1,Math.ceil(S/C)),L=(x-1)*C,k=Math.min(L+C,S),w=y.slice(L,k),b=S>0&&L>=S,A=w,M=[...m.warnings,...Ci(m),...f?[`results capped at ${1e4} during the walk before sorting \u2014 sortBy:"${R}" only orders that partial set, not the true top-N across the whole tree`]:[],...b?[`page:${x} is out of range (only ${T} page(s), ${S} total file(s)) \u2014 returned 0 files. Use page:1..${T}.`]:[]],H=[...a,...M],I=x<T,Z={...bf(A)??{},...I?{nextPage:Rn(P.LOCAL_FIND_FILES,{...i,page:x+1},"Continue to the next page of matched files.")}:{}},v={...S===0?{status:"empty"}:{},path:i.path,files:A,pagination:{currentPage:x,totalPages:T,filesPerPage:C,totalFiles:S,hasMore:I,...I?{nextPage:x+1}:{},...f||p>S?{totalFilesFound:p}:{},...b?{outOfRange:!0}:{}},...Object.keys(Z).length>0?{next:Z}:{},...H.length>0&&{warnings:H}};return Q(v,m.entries.reduce((X,ae)=>X+ae.path.length,0))}catch(o){return O(o,e,{toolName:P.LOCAL_FIND_FILES})}}function Ux(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 Qx(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 $x(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=wn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var jx=/^\d+[hdwm]$/;function zx(e){let t=[],n=e.time;if(!n)return{warnings:t,query:e};let r={...n},o=[{key:"modifiedBefore",value:n.modifiedBefore},{key:"modifiedWithin",value:n.modifiedWithin},{key:"accessedWithin",value:n.accessedWithin}];for(let{key:i,value:s}of o)s&&!jx.test(s)&&(t.push(`time.${i}="${s}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete r[i]);return{warnings:t,query:{...e,time:r}}}async function Pf(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=xe(_t,n);return r.ok===!1?r.error:await Cf(r.data)}}),{toolName:P.LOCAL_FIND_FILES},e)}import{readFileSync as Kx}from"node:fs";import{posix as wf}from"node:path";var Wx=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","async","await"]);function Pi(e){return e?!Wx.has(e):!1}import{posix as xi}from"node:path";var rc=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],Vx={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function xf(e){return e.split("\\").join("/")}function Wt(e,t,n){let r=xf(e);if(!r.startsWith(".")&&!r.startsWith("/"))return null;let o=xi.dirname(xf(t)),i=r.startsWith("/")?r.slice(1):xi.normalize(xi.join(o,r)),s=[];if(rc.some(c=>i.endsWith(c))){s.push(i);for(let[c,u]of Object.entries(Vx))if(i.endsWith(c)){s.push(i.slice(0,-c.length)+u);break}}else{s.push(i);for(let c of rc)s.push(`${i}${c}`);for(let c of rc)s.push(xi.join(i,`index${c}`))}for(let c of s)if(n.has(c))return c;return null}var Yx=1e6,Tf=["node_modules","dist","build","out","coverage",".git","target",".next",".cache"];function Xx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qx(e,t){let n=e.match(new RegExp(`\\b${Xx(t)}\\b`,"g"));return n?n.length:0}function Ef(e,t,n){let r=F.getSupportedGraphFactExtensions(),i=F.queryFileSystem({path:e,recursive:!0,showHidden:!1,entryType:"f",extensions:r,excludeDir:t,stopAtLimit:!0,limit:n}).entries,s=i.length>=n,a=new Set(i.map(f=>wf.normalize(f.relativePath.split("\\").join("/")))),c=new Map,u=new Map,l=new Set,d=new Set,m=new Map,p=0;for(let f of i){let g=wf.normalize(f.relativePath.split("\\").join("/"));if((f.size??0)>Yx){p++;continue}let R;try{R=Kx(f.path,"utf-8")}catch{p++;continue}let h=F.extractGraphFacts(R,g);if(!h){p++;continue}let y;try{y=JSON.parse(h)}catch{p++;continue}let S=(y.declarations??[]).filter(b=>Pi(b.name)).map(b=>({id:b.id,name:b.name,kind:b.kind,line:b.line,exported:b.exported??!1})),C=new Map;for(let b of S)!b.exported||C.has(b.name)||C.set(b.name,qx(R,b.name));let x=(y.exports??[]).filter(b=>b.source&&b.name!=="*").map(b=>({specifier:b.source,localName:b.localName??b.name,importedName:b.name,line:b.line})),T=(y.calls??[]).filter(b=>b.kind==="dynamic-import").map(b=>b.callee),L={relativePath:g,declarations:S,imports:(y.imports??[]).map(b=>({specifier:b.specifier,localName:b.localName,importedName:b.importedName,line:b.line})),namedReexports:x,calls:(y.calls??[]).filter(b=>b.kind!=="dynamic-import").map(b=>({caller:b.caller,callee:b.callee})),referenceCounts:C};c.set(g,L);let k=new Set,w=new Set;for(let b of[...L.imports,...L.namedReexports]){let A=Wt(b.specifier,g,a);A&&A!==g&&k.add(A)}for(let b of T){let A=Wt(b,g,a);A&&A!==g&&(k.add(A),w.add(A),d.add(A))}for(let b of y.exports??[]){if(!b.source||b.name!=="*")continue;let A=Wt(b.source,g,a);if(A&&A!==g){k.add(A),l.add(A);let M=m.get(A)??[];M.push(g),m.set(A,M)}}u.set(g,{relativePath:g,importsFiles:k,dynamicImportsFiles:w})}return{facts:c,fileGraph:u,filesScanned:c.size,filesSkipped:p,truncated:s,starReexportTargets:l,dynamicImportTargets:d,starReexporters:m}}import{readFileSync as Jx}from"node:fs";import{posix as oc}from"node:path";var Zx=/(\.(test|spec)\.[^/]+$)|(^|\/)(__tests__|tests?)\//i,ew=/\.(mjs|cjs|jsx?|tsx?)$/i;function tw(e){let t=[];for(let n of e.split(/\s+/)){let r=n.includes("=")?[n,n.slice(n.indexOf("=")+1)]:[n];for(let o of r){let i=o.replace(/^["']|["']$/g,"");ew.test(i)&&!i.startsWith("-")&&t.push(i)}}return t}function ic(e){return e.split("\\").join("/")}function Lf(e){return e.replace(/^\.\//,"")}var nw=["dist","build","out"],rw={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function Af(e){for(let[t,n]of Object.entries(rw))if(e.endsWith(t))return e.slice(0,-t.length)+n}function ow(e,t){let n=[],r=Af(e);r&&n.push(r);for(let o of nw){let i=`${o}/`;if(!e.startsWith(i))continue;let a=`src/${e.slice(i.length)}`;n.push(a);let c=Af(a);c&&n.push(c)}return n.find(o=>t.has(o))}function Wr(e,t){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let n of e)Wr(n,t);return}if(e&&typeof e=="object")for(let n of Object.values(e))Wr(n,t)}function kf(e,t,n,r){let o=[],i=new Set,s=!1;if(t&&t.length>0){let a=ic(e).replace(/\/$/,"");for(let c of t){let u=Lf(ic(c));u.startsWith(a+"/")&&(u=u.slice(a.length+1)),u=oc.normalize(u),r.has(u)?i.add(u):o.push(`entrypoint not found in scan: ${c} \u2014 pass it relative to the scanned path (e.g. "src/index.ts"), or as an absolute path under it`)}}else{let a;try{let c=oc.join(e,"package.json");a=JSON.parse(Jx(c,"utf-8"))}catch{}if(a){let c=[];if(Wr(a.main,c),Wr(a.exports,c),Wr(a.bin,c),a.scripts&&typeof a.scripts=="object")for(let u of Object.values(a.scripts))typeof u=="string"&&c.push(...tw(u));for(let u of c){let l=oc.normalize(Lf(ic(u))),d=r.has(l)?l:ow(l,r);d&&i.add(d)}}i.size===0&&(o.push("no entrypoints resolved from package.json \u2014 pass `entrypoints` explicitly, or every export in a reachable file will read as unreachable"),s=!0)}if(n)for(let a of r)Zx.test(a)&&i.add(a);return{entrypoints:[...i],warnings:o,lowConfidence:s}}function sc(e,t){let n=new Set,r=[];for(let o of t)n.has(o)||(n.add(o),r.push(o));for(;r.length>0;){let o=r.pop(),i=e.get(o);if(i)for(let s of i.importsFiles)n.has(s)||(n.add(s),r.push(s))}return n}function _f(e){let t=0,n=new Map,r=new Map,o=new Set,i=[],s=[],a=[];for(let c of e.keys())if(!n.has(c))for(a.push({node:c,iterator:(e.get(c)?.importsFiles??new Set).values()}),n.set(c,t),r.set(c,t),t++,i.push(c),o.add(c);a.length>0;){let u=a[a.length-1],l=u.iterator.next();if(!l.done){let d=l.value;if(!n.has(d))n.set(d,t),r.set(d,t),t++,i.push(d),o.add(d),a.push({node:d,iterator:(e.get(d)?.importsFiles??new Set).values()});else if(o.has(d)){let m=r.get(u.node),p=n.get(d);r.set(u.node,Math.min(m,p))}continue}if(a.pop(),a.length>0){let d=a[a.length-1],m=r.get(d.node),p=r.get(u.node);r.set(d.node,Math.min(m,p))}if(r.get(u.node)===n.get(u.node)){let d=[],m;do m=i.pop(),o.delete(m),d.push(m);while(m!==u.node);(d.length>1||(e.get(d[0])?.importsFiles.has(d[0])??!1))&&s.push({files:d})}}return s}function Vr(e,t){return`${e}::${t}`}function ac(e,t,n,r,o,i,s){let a=Vr(e,t);if(s.has(a))return!1;if(n.has(e)||r.has(a))return!0;s.add(a);for(let c of o.get(a)??[])if(ac(c.file,c.localName,n,r,o,i,s))return!0;for(let c of i.get(e)??[])if(ac(c,t,n,r,o,i,s))return!0;return!1}function If(e,t,n,r,o,i){let s=new Set(t.declarations.filter(l=>l.exported).map(l=>l.name)),a=new Set;for(let l of s)ac(e,l,n,r,o,i,new Set)&&a.add(l);let c=l=>!s.has(l)||a.has(l),u=!0;for(;u;){u=!1;for(let l of s){if(a.has(l))continue;let d=t.calls.filter(f=>f.callee===l);if(d.some(f=>f.caller!==l&&c(f.caller))){a.add(l),u=!0;continue}let m=d.filter(f=>f.caller===l||!c(f.caller)).length;(t.referenceCounts.get(l)??0)-m>1&&(a.add(l),u=!0)}}return a}function Of(e,t){let n=t.excludeDir&&t.excludeDir.length>0?t.excludeDir:Tf,r=t.maxFiles??2e4,{facts:o,fileGraph:i,filesScanned:s,filesSkipped:a,truncated:c,dynamicImportTargets:u,starReexporters:l}=Ef(e,n,r),d=new Set(o.keys()),{entrypoints:m,warnings:p,lowConfidence:f}=kf(e,t.entrypoints,t.includeTests??!0,d);c&&p.push(`scan stopped at maxFiles (${r}) \u2014 results are partial, not a full-repo verdict`);let g=m.filter(v=>{let X=o.get(v);return(i.get(v)?.importsFiles.size??0)===0&&(X?.declarations.length??0)===0&&(X?.namedReexports.length??0)===0}),R=g.length>0;R&&p.push(`${g.length} entrypoint file(s) parsed to no imports/exports (likely an extractor parse failure on that file) \u2014 reachability from them is unreliable, so "unreachable-file" results here are low-confidence and may be false positives: ${g.join(", ")}`);let h=sc(i,m),y=new Set(m),S=new Map([...i].map(([v,X])=>[v,{relativePath:X.relativePath,importsFiles:new Set([...X.importsFiles].filter(ae=>!X.dynamicImportsFiles.has(ae))),dynamicImportsFiles:new Set}])),C=sc(S,m),x=[...h].filter(v=>!C.has(v)).sort();x.length>0&&p.push(`${x.length} file(s) reachable only through a dynamic import() \u2014 lower confidence than static analysis, verify with lspGetSemantics before treating as proof: ${x.join(", ")}`);let T=new Map;for(let[v,X]of o){let ae=new Map;for(let ie of X.imports){let ce=Wt(ie.specifier,v,d);ce&&ae.set(ie.localName,ce)}T.set(v,ae)}let L=new Set,k=new Map;for(let v of h){let X=o.get(v);if(!X)continue;let ae=T.get(v);for(let ie of X.imports){let ce=ae?.get(ie.localName);ce&&L.add(Vr(ce,ie.importedName))}for(let ie of X.namedReexports){let ce=Wt(ie.specifier,v,d);if(!ce)continue;let ke=Vr(ce,ie.importedName),Et=k.get(ke)??[];Et.push({file:v,localName:ie.localName}),k.set(ke,Et)}}let w=new Map;for(let[v,X]of l){let ae=X.filter(ie=>h.has(ie));ae.length>0&&w.set(v,ae)}let b=new Set(w.keys()),A=[],M=_f(i),H=new Map,I=[],B=0;for(let v of M){if(!v.files.every(ie=>!h.has(ie)))continue;let ae=B++;for(let ie of v.files)H.set(ie,ae);I.push({id:ae,files:v.files,reason:"mutually-referencing cluster with no path from any entrypoint \u2014 each file looks locally referenced by the others, but the cluster as a whole is unreachable"})}let Z=new Map;for(let[v,X]of o){let ae=y.has(v),ie=h.has(v);for(let ce of X.declarations){if(!ce.exported)continue;if(!ie){let Et=H.get(v);A.push({file:v,name:ce.name,kind:ce.kind,line:ce.line,reason:Et!==void 0?"dead-cluster":"unreachable-file",...Et!==void 0?{clusterId:Et}:{}});continue}if(ae||b.has(v)||u.has(v))continue;let ke=Z.get(v);ke||(ke=If(v,X,y,L,k,w),Z.set(v,ke)),ke.has(ce.name)||A.push({file:v,name:ce.name,kind:ce.kind,line:ce.line,reason:"unreferenced-export",viaHeuristic:k.has(Vr(v,ce.name))?"reexport-chain":"lexical-count"})}}return{filesScanned:s,filesSkipped:a,entrypointsResolved:m,deadExports:A,deadClusters:I,warnings:p,...f||R?{confidence:"low"}:{}}}var iw=100;function sw(e,t,n){let r=Math.max(1,Math.ceil(e.length/n)),o=Math.min(Math.max(1,t),r),i=(o-1)*n;return{pageItems:e.slice(i,i+n),currentPage:o,totalPages:r,hasMore:o<r,outOfRange:t>r}}async function Ff(e){try{let t=Le(e,P.LOCAL_FIND_DEAD_CODE);if(!t.isValid)return t.errorResult;let n=Of(t.sanitizedPath,e),r=e.itemsPerPage??iw,o=e.page??1,{pageItems:i,currentPage:s,totalPages:a,hasMore:c,outOfRange:u}=sw(n.deadExports,o,r),l=[...n.warnings,...u?[`page:${o} is out of range (only ${a} page(s), ${n.deadExports.length} total candidates) \u2014 returned page ${s} instead.`]:[]],d={path:e.path,filesScanned:n.filesScanned,filesSkipped:n.filesSkipped,entrypointsResolved:n.entrypointsResolved,deadExports:i,deadClusters:n.deadClusters,pagination:{currentPage:s,totalPages:a,entriesPerPage:r,totalEntries:n.deadExports.length,hasMore:c,...u?{outOfRange:!0}:{}},...l.length>0?{warnings:l}:{},...n.confidence?{confidence:n.confidence}:{}};c&&(d.next={nextPage:Rn(P.LOCAL_FIND_DEAD_CODE,{...e,page:s+1},"Continue to the next page of dead-export candidates.")});let m=i[0];if(m){let p=t.sanitizedPath.replace(/\/+$/,"");d.next={...d.next,verifyReferences:{tool:le,query:{type:"references",uri:`${p}/${m.file}`,symbolName:m.name,lineHint:m.line,includeDeclaration:!1,groupByFile:!0},why:`Verify candidate "${m.name}" before any delete claim \u2014 zero references = confirmed dead. Repeat per candidate using each entry's file/name/line; start with viaHeuristic:"reexport-chain" candidates (most fragile).`,confidence:"high"}}}return d}catch(t){let n=Ee.toolExecutionFailed(P.LOCAL_FIND_DEAD_CODE,t instanceof Error?t:new Error(String(t)));return O(n,e,{toolName:P.LOCAL_FIND_DEAD_CODE})}}async function vf(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_FIND_DEAD_CODE,query:n,contextMessage:"localFindDeadCode execution failed",execute:async()=>{let r=xe(It,n);return r.ok===!1?r.error:await Ff(r.data)}}),{toolName:P.LOCAL_FIND_DEAD_CODE},e)}import{validateRipgrepQuery as Mw}from"@octocodeai/octocode-core/schemas/runtime";var cc=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],ne={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,testPathPenalty:-3.5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},uc=2e3,lc=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Df={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+['"]/]},Kr={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Df},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Df},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/]}},dc=/^\s*#{1,6}\s/,Yr=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,aw=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,cw=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,uw=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,lw=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,dw=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,pw=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,mw=new Set(["typescript","javascript","rust","python","go","java","scala"]),wi=/\.([a-z0-9]+)$/i;function Xr(e){return wi.exec(e)?.[1]?.toLowerCase()??""}function fw(e){let t=Xr(e);if(!t)return!1;for(let n of mw)if(Kr[n].extensions.includes(t))return!0;return!1}function pc(e,t,n){if(n&&n!=="auto")return Kr[n];let r=Xr(e),o=(t??"").toLowerCase();for(let i of cc){let s=Kr[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of cc){let s=Kr[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Kr.generic}function Ti(e){return aw.test(e)?"generated":uw.test(e)?"fixture":cw.test(e)?"test":dw.test(e)?"config":lw.test(e)?"docs":!Yr.test(e)&&(pw.test(e)||fw(e))?"source":"unknown"}function mc(e){if(!e)return!1;if(Yr.test(e))return!0;let t=Ti(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}function fc(e,t,n,r={}){if(t==="matchCount"){let m=[...e].sort(Mf);return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="path"){let m=[...e].sort((p,f)=>p.path.localeCompare(f.path));return{files:r.sortReverse?m.reverse():m,cappedCandidates:0}}if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??uc,i=e,s=[],a=0;if(e.length>o){let m=[...e].sort(Mf);i=m.slice(0,o),s=m.slice(o),a=s.length}let c=Rc(i,n),u=i.map(m=>{try{return{file:m,s:Sc(m,n,c)}}catch{return{file:m,s:hw()}}});u.sort((m,p)=>{if(p.s.score!==m.s.score)return p.s.score-m.s.score;let f=(p.file.matchCount??0)-(m.file.matchCount??0);return f!==0?f:m.file.path.localeCompare(p.file.path)});let l=[...u.map(m=>m.file),...s],d={files:r.sortReverse?l.reverse():l,cappedCandidates:a};return r.debug&&(d.debug=new Map(u.map(m=>[m.file.path,m.s]))),d}function hw(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Mf(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function qr(e,t){for(let n of e)if(n.test(t))return!0;return!1}function Ei(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hc(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function gc(e,t,n){if(e.indexOf(`
|
|
62
60
|
`)<0)return e;let o=e.split(`
|
|
63
|
-
`);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 fc(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(ac.test(e))return"comment";let o=nw(e,t,r);if(o<0)return"code";let i=rw(e);return i>=0&&o>i?"comment":Of(e,o)?"string":"code"}function nw(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function rw(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 Of(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function ow(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function iw(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 sw(e,t,n,r,o){if(!e||e.length===0)return 0;let i=pc(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=mc(u,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${wi(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(d+=ne.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(d+=ne.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(d+=ne.substring,m.push("substring match")));let p=c.kind;if(p)d+=aw(p,m);else{let f=fc(l,r,t.id,n.caseSensitive);f!=="code"?(d+=ne.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(Xr(t.declaration,l)&&(d+=ne.declarationLine,m.push("declaration line")),Xr(t.export,l)&&(d+=ne.exportLine,m.push("export/public line")),Xr(t.import,l)&&(d+=ne.importLine,m.push("import line")),t.id==="markdown"&&cc.test(l)&&(d+=ne.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&cw(l,r)&&(d+=ne.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function aw(e,t){switch(e){case"declaration":return t.push("AST: declaration"),ne.declarationLine;case"export":return t.push("AST: export/public"),ne.exportLine;case"configKey":return t.push("AST: config key"),ne.configKeyLine;case"heading":return t.push("AST: heading"),ne.headingLine;case"import":return t.push("AST: import"),ne.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),ne.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function cw(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 uw(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(Pi,"").includes(u))&&(s+=ne.pathSegmentToken,i.push("query token in path"))}let a=Yr(e);return r.extensions.includes(a)&&t.langType&&(s+=ne.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=ne.sourceDir,i.push("source file")),s}function lw(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),ne.lowSignalPathPenalty):e==="test"?(n.push("test file (penalized)"),ne.testPathPenalty):0}function dw(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*ne.matchCountScale,r=Math.min(n,ne.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function hc(e,t){let n=iw(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=>pw(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 pw(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${wi(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function mw(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let u=Math.log2((t.candidateCount+1)/(c+1)),l=Math.min(u*ne.rareQueryTokenScale,ne.rareQueryTokenCap);l>i&&(i=l,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function gc(e,t,n){let r=uc(e.path,t.langType,t.profileOverride),o=xi(e.path),i=ow(t.keyword),s=[],a=0;return a+=sw(e.matches,r,t,i,s),a+=uw(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=ne.pathUnderQuery,s.push("under requested subtree")),a+=lw(o,t,s),Kr.test(e.path)&&!t.explicitLowSignal&&(a+=ne.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=dw(e.matchCount??0,s),a+=mw(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var fw=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"]),hw=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Ff(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=gw(i);s.fetch={tool:"localGetFileContent",query:yc({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"low":"exact"};let a=yw(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"low"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"low"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:yc({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:yc({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function gw(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 yw(e,t,n){if(t.output==="countLines"||t.output==="countMatches"||t.unique==="list"||t.unique==="count")return;if(n==="structural")return Rw(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.output==="matchOnly"){let o=Rc(e?.value);return o?{symbol:o}:void 0}let r=Rc(t.searchText);return r?{symbol:r}:void 0}function Rw(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=Rc(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function Rc(e){if(typeof e!="string")return;let t=e.trim();if(hw.test(t)&&!fw.has(t))return t}function yc(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Ti(e,t,n,r,o){let i=t.sort??"relevance",s=n==="structural"&&i==="relevance"?"path":i,a;try{a=dc(e,s,Sw(t),{debug:!1,sortReverse:t.sortReverse})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,u=a.debug,l=c.length,d=t.output==="files"||t.output==="filesWithout",m=t.output==="countLines"||t.output==="countMatches",p=d||m,f=c.reduce((H,k)=>H+(k.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??f:f,R=t,h=Math.min(R.itemsPerPage||wt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),y=R.page||1,S=Math.max(1,Math.ceil(l/h)),C=(y-1)*h,x=Math.min(C+h,l),T=c.slice(C,x),L=l>0&&C>=l;L&&r.push(`page:${y} is out of range (only ${S} page(s), ${l} total file(s)) \u2014 returned 0 files. Use page:1..${S}.`);let _=R.maxMatchesPerFile||wt.DEFAULT_MATCHES_PER_PAGE,w=T.map(H=>{let k=H.matches?.length??0,B=Math.max(1,Math.ceil(k/_)),Z=Math.max(1,R.matchPage||1),v=(Z-1)*_,Y=k>0&&v>=k,ae=Math.min(v+_,k),ie=p?void 0:H.matches?.slice(v,ae),ce=ie?.length;Y&&r.push(`${H.path}: matchPage:${Z} is out of range under maxMatchesPerFile:${_} (only ${B} page(s), ${k} total match(es) for this file) \u2014 returned 0 rows for this file. Use matchPage:1..${B}, or drop matchPage to re-derive it from the current maxMatchesPerFile.`);let _e=u?.get(H.path);return{path:H.path,...d?{}:t.output==="countLines"?{totalMatchedLines:H.matchCount||1}:t.output==="countMatches"?{totalOccurrences:H.matchCount||1}:{totalMatchRows:k,...ce!==void 0?{returnedMatchRows:ce}:{}},...ie!==void 0&&{matches:ie},..._e?{ranking:{score:_e.score,profile:_e.profile,pathRole:_e.pathRole,reasons:_e.reasons}}:{},pagination:!p&&(k>_||Y)?{currentPage:Z,totalPages:B,matchesPerPage:_,totalMatches:k,hasMore:Z<B,...Z<B?{nextMatchPage:Z+1}:{},...Y?{outOfRange:!0}:{}}:void 0}}),b=w.filter(H=>H.pagination?.hasMore),A=Ff(w,t,n,{isFileListMode:p,currentPage:y,totalFilePages:S,matchPage:R.matchPage||1,matchesPerPage:_,hasFileWithMoreMatches:b.length>0}),M={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:y,totalPages:S,filesPerPage:h,totalFiles:l,...d?{}:{totalMatches:g},hasMore:y<S,...y<S?{nextPage:y+1}:{},...L?{outOfRange:!0}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return vf(M,t,{totalMatches:g,totalFiles:l})}function vf(e,t,n){return e}function Sw(e){let t=e.rankingProfile,n=!!(e.include?.length||lc(e.path));return{queryPath:e.path,keyword:e.searchText,langType:e.langType,caseSensitive:e.caseMode==="sensitive",wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function Df(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=F.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&bw(r)&&n.push(`pattern '${r}' looks literal \u2014 set regex:"fixed" to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&Cw(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function bw(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function Cw(e){return/\(\?[=!<]/.test(e)}import Tn from"node:path";function xw(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function ww(e){return{path:e.path,pattern:e.searchText??"",fixedString:e.regex==="fixed",perlRegex:e.regex==="perl",caseSensitive:e.caseMode==="sensitive",caseInsensitive:e.caseMode==="insensitive",wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline==="on"||e.multiline==="dotall",multilineDotall:e.multiline==="dotall",filesOnly:e.output==="files",filesWithoutMatch:e.output==="filesWithout",countLinesPerFile:e.output==="countLines",countMatchesPerFile:e.output==="countMatches",contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:xw(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.output==="matchOnly",unique:e.unique==="list"||e.unique==="count",countUnique:e.unique==="count",matchWindow:e.matchWindow,maxCollectedFiles:1e4}}function Tw(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}function Ew(e,t){let n=Tn.isAbsolute(e)?e:Tn.join(t,e),r=Tn.relative(t,n);if(!r||r.startsWith("..")||Tn.isAbsolute(r))return 0;let o=Tn.dirname(r);return o==="."?0:o.split(Tn.sep).filter(Boolean).length}async function Mf(e){let t=[],n=Pw(e);if(!n.isValid)return O(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:P.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=tt.safeParse(e);if(!r.success){let h=r.error.issues.map(y=>y.message);return O(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:P.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return O(new Error("Path is required for search"),o,{toolName:P.LOCAL_RIPGREP,extra:{warnings:t}});let s=Le(o,P.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Df({pattern:a.searchText??"",fixedString:a.regex==="fixed",perlRegex:a.regex==="perl"});if(!c.isValid)return O(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:P.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await F.searchRipgrep(ww(a))}catch(h){return O(h instanceof Error?h:new Error(String(h)),o,{toolName:P.LOCAL_RIPGREP})}let d=l.files.map(h=>({path:h.path,matchCount:h.matchCount,matches:h.matches.map(y=>{let S={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(S.count=y.count),y.kind!==void 0&&(S.kind=y.kind),y.scoreHint!==void 0&&(S.scoreHint=y.scoreHint),S})})),m=a.maxDepth,p=m===void 0?d:d.filter(h=>Ew(h.path,a.path)<=m);m!==void 0&&p.length!==d.length&&u.push(`Applied maxDepth:${m} after native text search; filtered ${d.length-p.length} deeper file(s).`);let f=Tw(p),g={totalOccurrences:l.stats.matchCount,matchedLines:l.stats.matchedLines,filesMatched:p.length,filesSearched:l.stats.filesSearched,bytesSearched:l.stats.bytesSearched??void 0,searchTime:l.stats.searchTime,capped:l.stats.capped??void 0,capReason:l.stats.capReason??void 0};if(l.stats.capped&&u.push(`Search hit native collection cap (${l.stats.capReason??"resource limit"}); narrow path/include/keywords for exhaustive results.`),p.length===0){let h=['No matches \u2014 broaden the search: try caseMode:"insensitive", a shorter/partial term, or regex:"smart" instead of "fixed".',...a.include?.length||a.maxDepth!==void 0?["Filters are active (include/maxDepth) \u2014 drop them to search the wider tree."]:[],...a.wholeWord?["wholeWord:true excludes partial hits \u2014 drop it to match substrings."]:[]];return Q({status:"empty",searchEngine:"rg",stats:g,hints:h,warnings:[...t,...u]},f)}a.output!=="files"&&f>wt.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(f/1024)}KB).`);let R=await Ti(p,o,"rg",[...t,...u],g);return Q(R,f)}import{readFile as _w,stat as kw}from"node:fs/promises";var Nf={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"]}},Gf={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 Lw(e){return e.trim().replace(/^\./,"").toLowerCase()}function Hf(e){if(!e?.trim())return;let t=Lw(e),n=Nf[t]??Gf[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function Sc(e){let t=Hf(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}var Aw=/^\s*(\/\/|\/\*|\*|#)/;function Uf(e,t,n){let r=t&&Object.keys(t).length>0;if(n)return{...e?{metavars:e}:{},...r?{metavarRanges:t??void 0}:{}};let o;if(e){o={};for(let[s,a]of Object.entries(e))a.length<=1&&(o[s]=a.map(Bf));Object.keys(o).length===0&&(o=void 0)}let i;if(r&&t){i={};for(let[s,a]of Object.entries(t)){let u=(a.length>1?a.filter(l=>!Aw.test(l.text)):a).map(l=>({...l,text:Bf(l.text)}));u.length>0&&(i[s]=u)}Object.keys(i).length===0&&(i=void 0)}return{...o?{metavars:o}:{},...i?{metavarRanges:i}:{}}}function Bf(e){return e.length>120?`${e.slice(0,120)}\u2026`:e}var Qf=[],$f=2e3,Iw=1e6,Ow="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 zf(e){if(!e||!/\)\s*\{/.test(e))return;let t=e.replace(/\)\s*\{/,"): $R {");return t===e?void 0:t}function Fw(e){let t=zf(e);return t?` Try: \`${t}\`.`:""}function jf(e){return e.include?.length?e.include:Sc(e.langType)}async function vw(e){try{return(await kw(e)).isFile()}catch{return!1}}async function Dw(e,t,n){let r=await _w(e,"utf8"),o=await F.structuralSearch(r,e,n??t.pattern,t.rule);return{files:o.length>0?[{path:e,matches:o}]:[],totalMatches:o.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Wf(e){let t=Le(e,P.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=await vw(t.sanitizedPath),r=!!e.captureText,o=S=>({path:t.sanitizedPath,pattern:S??e.pattern,rule:e.rule,...jf(e)?{include:jf(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Qf.length?{excludeDir:Qf}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??$f,maxFileBytes:Iw}),i=S=>n?Dw(t.sanitizedPath,e,S):F.structuralSearchFiles(o(S)),s,a=!1,c;try{if(s=await i(),s.totalMatches===0&&e.pattern&&!e.rule&&!/[;}]\s*$/.test(e.pattern))try{let S=await i(`${e.pattern};`);S.totalMatches>0&&(s=S,a=!0)}catch{}if(s.totalMatches===0&&e.pattern&&!e.rule){let S=zf(e.pattern);if(S)try{let C=await i(S);C.totalMatches>0&&(s=C,c=S)}catch{}}}catch(S){let C=S instanceof Error?S.message:String(S),x=e.langType||"source";return O(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${C} \u2014 patterns must be valid ${x} 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:P.LOCAL_RIPGREP})}let u=s.files.map(S=>({path:S.path,matchCount:S.matches.length,matches:S.matches.map(C=>({line:C.startLine,endLine:C.endLine,value:C.text.replace(/\s+/g," ").trim().slice(0,300),column:C.startCol,endColumn:C.endCol,...Uf(C.metavars,C.metavarRanges,r)}))})),l=e.maxDepth,d=u,m=0;if(typeof l=="number"&&!n){let S=t.sanitizedPath.replace(/\/+$/,"");d=u.filter(C=>(C.path.startsWith(`${S}/`)?C.path.slice(S.length+1):C.path).split("/").length<=l+1),m=u.length-d.length}let p=d.reduce((S,C)=>S+(C.matchCount??C.matches?.length??0),0),f=e.maxFiles??$f,R=(s.parsedFiles??0)+(s.skippedUnreadable??0)+(s.skippedLarge??0)>=f,h={totalStructuralMatches:typeof l=="number"?p:s.totalMatches,...R?{capReached:!0}:{}},y=[...s.warnings];if(m>0&&y.push(`maxDepth ${l}: dropped ${m} deeper file(s) \u2014 raise maxDepth or omit it to include them.`),a&&y.push(`Matched after appending ';' \u2014 statement patterns must parse as complete statements; the bare pattern parsed as an expression fragment. Results are for "${e.pattern};".`),c&&y.push(`Matched after adding a return-type metavar \u2014 the bare pattern missed functions that declare a return type. Results are for "${c}".`),s.totalMatches===0&&!n)try{let S=F.structuralSearchFilesDetailed(o()),C=S.query;if(C){let x=[`query parsed as ${C.kind}`];C.literalAnchor&&x.push(`literal anchor "${C.literalAnchor}"`),x.push(`pre-filter: ${C.preFilter}`),C.unsafeReason&&x.push(`unsafe: ${C.unsafeReason}`),y.push(`Engine explanation: ${x.join(", ")}.`);for(let T of[...C.diagnostics??[],...S.diagnostics??[]].slice(0,3))y.push(`Engine ${T.severity} [${T.stage}/${T.code}]: ${T.message}${T.recovery?` \u2014 ${T.recovery}`:""}`)}}catch{}return(d.length===0||h.totalStructuralMatches===0)&&e.pattern&&!e.rule&&m===0&&y.push(Ow+Fw(e.pattern)),await Ti(d,e,"structural",y,h)}function Mw(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.output==="content"?n.output="files":t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Ei(e){let t=Mw(e);if(t.mode==="structural")return await Wf(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Mf(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:G.OUTPUT_TOO_LARGE}:O(n,t,{toolName:P.LOCAL_RIPGREP})}}async function Vf(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=xe(tt,n);return r.ok===!1?r.error:await Ei(r.data)}}),{toolName:P.LOCAL_RIPGREP},e)}var Nw=new Set(["+","*","?"]),Gw=1e3;function Hw(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Kf(e,t){let n=e[t];return n===void 0?!1:Nw.has(n)||n==="{"&&Qw(e,t)}function Bw(e,t,n){let r=n.pop()??!1,o=Kf(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?Xf(e,t+1):t+1})}function Uw(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Xf(e,t)})}function Yf(e){if(e.length>Gw)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=Hw(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=Bw(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Kf(e,r)){let i=Uw(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function Qw(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 Xf(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function qf(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(!Yf(s).safe)return n=n.filter(u=>(u.name.includes("/")?u.name.split("/").pop():u.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(u=>{let l=u.name.includes("/")?u.name.split("/").pop():u.name;return c.test(l)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return n}function Jf(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 Zf(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}function eh(e){let t={},n=e.find(o=>o.type==="file"&&o.path);n?.path&&(t.fetch={tool:"localGetFileContent",query:{path:n.path,minify:"standard"},why:'Read the first listed file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"});let r=e.find(o=>o.type==="directory"&&o.path);return r?.path&&(t.viewDeeper={tool:"localViewStructure",query:{path:r.path},why:"Descend into the first listed subdirectory.",confidence:"exact"}),t.fetch||t.viewDeeper?t:void 0}var $w=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function jw(e,t){let n=t??$w,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function th(e){try{let t=Le(e,P.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.detail==="modified"||e.detail==="full"||e.sortBy==="time";return zw(e,t.sanitizedPath,n)}catch(t){let n=Ee.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function zw(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=Vw(e),s=Ww(e,i),a=r&&s?1e4:1e4,c=jw(t,e.excludeDir),u;try{u=F.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:Kw(e),excludeDir:c,limit:a})}catch(L){return qw(L,e,t)}let l=u.entries.map(L=>Yw(L,n,e.detail==="full")),d=qf(l,e),m=e.sortBy??"name";d=d.sort((L,_)=>{let w=0;switch(m){case"size":{let b=L.sizeBytes??(L.size?jr(L.size):0),A=_.sizeBytes??(_.size?jr(_.size):0);w=b-A;break}case"time":n&&L.modified&&_.modified?w=L.modified.localeCompare(_.modified):w=L.name.localeCompare(_.name);break;case"extension":w=(L.extension||"").localeCompare(_.extension||"");break;default:w=L.name.localeCompare(_.name);break}return e.reverse?-w:w}),e.limit&&(d=d.slice(0,e.limit));let p=d.length,{paginatedEntries:f,pagination:g}=ff(d,e),h=e.detail==="full"||e.detail==="modified"?{path:t,entries:f.map(L=>({...Zf(L),path:L.path??`${t.replace(/\/$/,"")}/${L.name}`}))}:{path:t,...Jf(f)},y=[...u.warnings,...Si({skipped:u.skipped,permissionDenied:u.permissionDenied}),...u.wasCapped?[`Results capped at ${a} entries during the walk before sorting \u2014 sortBy:"${m}" only orders that partial set, not the true top-N across the whole tree. Add pattern/extensions/entryType/excludeDir or reduce depth to narrow the scope.`]:[],...g.outOfRange?[`page:${e.page} is out of range (only ${g.totalPages} page(s), ${g.totalEntries} total entries) \u2014 returned page ${g.currentPage} instead.`]:[]],S=p===0,C=mf(d),T={...eh(f)??{},...g.hasMore?{nextPage:Rn(P.LOCAL_VIEW_STRUCTURE,{...e,page:g.currentPage+1},"Continue to the next page of directory entries.")}:{}};return Q({...S?{status:"empty"}:{},...h,summary:C,...g.hasMore||g.totalPages>1||g.outOfRange?{pagination:g}:{},...Object.keys(T).length>0?{next:T}:{},...y.length>0&&{warnings:y}},u.entries.reduce((L,_)=>L+_.path.length,0))}function Ww(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function Vw(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function Kw(e){return e.entryType}function Yw(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:wn(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=Xw(e.permissions)),o}function Xw(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 qw(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=Ee.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return O(a,t,{toolName:P.LOCAL_VIEW_STRUCTURE})}async function nh(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=xe(Ot,n);return r.ok===!1?r.error:await th(r.data)}}),{toolName:P.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import{acquirePooledClientDetailed as HT,isLanguageServerAvailable as BT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as UT}from"@octocodeai/octocode-engine/lsp/workspaceRoot";var Jw=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"]);function Zw(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function rh(e,t){if(t===void 0||t==="progressIdle")return e;let n=Zw(e);if(!n||!Jw.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}import{readFile as eT,stat as tT}from"node:fs/promises";import{SymbolResolver as nT,SymbolResolutionError as rT}from"@octocodeai/octocode-engine/lsp/resolver";import{toUri as oT}from"@octocodeai/octocode-engine/lsp/uri";import{LSP_ERROR_CODES as Li}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function bc(e,t){let n=e.uri,r=Le({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await tT(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:Li.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:Li.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:oT(o),absolutePath:o,content:await eT(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:Li.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function oh(e,t){let n=await bc(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 nT({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=e.lineHint!==void 0?Math.abs(o.foundAtLine-e.lineHint):void 0,u=a>1&&c!==void 0&&c>0?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.uri,range:iT(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u},...c!==void 0&&c>0?{lineDeviation:c}:{}}}}}catch(o){if(o instanceof rT)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:Li.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 iT(e){return{start:e,end:{line:e.line,character:e.character}}}import Zr from"node:path";import{readFile as PT}from"node:fs/promises";import{resolveImportAliasDefinitions as xT}from"@octocodeai/octocode-engine/lsp/resolver";var Tt=40,Ai=40,Cc=10;function Pc(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 xc(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Pc(e.type,t),reason:t}}}function Ne(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Pc(e,n),reason:n}}}function Ge(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function qr(e,t,n,r,o){let i=o.length>0,s=o.map(Fi),{pageItems:a,pagination:c}=Ge(s,e.page??1,e.itemsPerPage??Ai);return{type:e.type,uri:t.uri,resolvedSymbol:Ze(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 wc(e,t,n,r){let o=n.map(d=>{let m=d.uri===t.uri&&d.range.start.line===t.resolvedSymbol.position.line&&d.range.start.character===t.resolvedSymbol.position.character;return{...d,...m?{isDefinition:!0}:{}}}),i=e.groupByFile?ih(o):void 0,s=i??o.map(Fi),{pageItems:a,pagination:c}=Ge(s,e.page??1,e.itemsPerPage??Ai),u=o.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0,l=r?.possiblyTruncated===!0?[`Reference warmup opened ${r.warmedFiles}/${r.candidates} candidate file(s) and may be incomplete because the candidate set hit the warmup cap; narrow workspaceRoot/path or confirm with localSearchCode before unused/safe-delete claims.`]:[];return{type:"references",uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...i?{byFile:a}:{locations:a},totalReferences:o.length,totalFiles:new Set(o.map(d=>d.uri)).size,...o.length>0&&o.every(d=>d.isDefinition)?{definitionOnly:!0}:{},...r?{warmup:r}:{},...u?{empty:u}:{}},pagination:c,...l.length>0?{warnings:l}:{}}}async function Tc(e,t,n){let r=sh(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function ih(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 sh(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=>ah(r)).join(`
|
|
64
|
-
`).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 ah(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}import{safeReadLineWindow as sT}from"@octocodeai/octocode-engine/lsp/validation";var aT={maxNodes:100,maxRequests:50},ch={truncatedByDepth:!1,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,cycleCount:0,failedRequestCount:0};function uh(e){return{...aT,...e,visitedNodeCount:0,requestCount:0,truncatedByBudget:!1}}function lh(e){return e.requestCount>=e.maxRequests?(e.truncatedByBudget=!0,!1):(e.requestCount+=1,!0)}function dh(e){return e.visitedNodeCount>=e.maxNodes?(e.truncatedByBudget=!0,!1):(e.visitedNodeCount+=1,!0)}function qe(e,t){return{...e,truncatedByBudget:t.truncatedByBudget,visitedNodeCount:t.visitedNodeCount,requestCount:t.requestCount}}function Jr(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function ph(e,t,n){if(t<=0)return e;let r=n?.[0]?.start.line??e.range.start.line,o=await sT(e.uri,r,t);if(!o)return e;let i=So(o).length,s=Math.max(0,r-t),a=s+Math.max(0,i-1);return{...e,content:o,displayRange:{startLine:s+1,endLine:a+1}}}async function cT(e,t){return Promise.all(e.map(async n=>({...n,from:await ph(n.from,t,n.fromRanges)})))}async function uT(e,t){return Promise.all(e.map(async n=>({...n,to:await ph(n.to,t)})))}async function Ec(e,t,n,r,o,i=uh(void 0)){if(n<=0||!e)return{calls:[],...ch};if(!lh(i))return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getIncomingCalls(t),a=o>0?await cT(s,o):s;if(n===1)return qe({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=Jr(u.from);if(r.has(l)){c.push(qe({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!dh(i)||(r.add(l),c.push(await Ec(e,u.from,n-1,r,o,i)),i.truncatedByBudget))break}return qe({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}async function Lc(e,t,n,r,o,i=uh(void 0)){if(n<=0||!e)return{calls:[],...ch};if(!lh(i))return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getOutgoingCalls(t),a=o>0?await uT(s,o):s;if(n===1)return qe({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=Jr(u.to);if(r.has(l)){c.push(qe({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!dh(i)||(r.add(l),c.push(await Lc(e,u.to,n-1,r,o,i)),i.truncatedByBudget))break}return qe({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}var lT=new Set(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),dT=new Set(["symbolNotFound","anchorFailed"]);function pT(e){if(e.kind==="empty"&&typeof e.category=="string")return{category:e.category,...typeof e.reason=="string"?{reason:e.reason}:{}};let t=e.empty;if(ut(t)&&typeof t.category=="string")return{category:t.category,...typeof t.reason=="string"?{reason:t.reason}:{}}}function mT(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"rs":return"^\\s*pub\\s";case"py":case"pyi":return"^\\s*(def|class)\\s";case"go":return"^(func|type|var|const)\\s";case"java":case"kt":case"scala":case"cs":return"^\\s*(public|protected|internal)\\s";case"rb":return"^\\s*(def|class|module)\\s";default:return"^\\s*export\\s"}}function fT(e,t){let n=e.symbolName;if(typeof n=="string"&&n.trim())return n.trim();let r=t.resolvedSymbol?.name;if(typeof r=="string"&&r.trim())return r.trim()}function Ac(e,t){if(!_c(t))return t;let n=t.payload,r=n.locations?.[0],o=r?.displayRange?.startLine;if(r?.uri&&typeof o=="number"){let c=r.uri.startsWith("file://")?decodeURIComponent(r.uri.slice(7)):r.uri;return{...t,next:{readSite:{tool:"localGetFileContent",query:{path:c,startLine:Math.max(1,o-3),endLine:(r.displayRange?.endLine??o)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}let i=pT(n);if(i?.category==="unsupportedOperation"&&t.type==="documentSymbols"&&t.uri){let c=t.uri.startsWith("file://")?decodeURIComponent(t.uri.slice(7)):t.uri;return{...t,next:{textSearch:{tool:"localSearchCode",query:{path:c,searchText:mT(c),regex:"perl"},why:"documentSymbols is unsupported for this file's language server \u2014 fall back to a regex search over top-level declarations for an outline.",confidence:"low"}}}}let s=fT(e,t);if(!i||!s||!lT.has(i.category))return t;let a={textSearch:{tool:"localSearchCode",query:{keywords:s},why:`Semantic ${t.type} returned no result (${i.category}) \u2014 fall back to a text search for "${s}"`,confidence:"low"}};return dT.has(i.category)&&t.uri&&(a.reAnchor={tool:"lspGetSemantics",query:{type:"documentSymbols",uri:t.uri},why:"Re-anchor: list this file's symbols to find the correct lineHint, then retry the semantic query",confidence:"medium"}),{...t,next:a}}var hT=8;function fh(e){return Q(e,N(e))}function hh(e,t){return e.format!=="compact"||!_c(t)?t:gT(t)}function _c(e){return ut(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&ut(e.payload)}function gT(e){return{...e,format:"compact",payload:yT(e.payload)}}function yT(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(mh)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(ST)}:{locations:(e.locations??[]).map(mh)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:gh(e.root)}:{},direction:e.direction,calls:e.calls.map(bT),...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(RT)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function RT(e){if(!ut(e))return String(e);let t=Ae(e,"line"),n=Ae(e,"character"),r=Ae(e,"endLine"),o=lt(e,"kind"),i=lt(e,"name"),s=Ae(e,"childCount"),a=lt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function mh(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Rh(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function ST(e){if(!ut(e))return String(e);let t=lt(e,"uri"),n=Ae(e,"firstLine"),r=Ae(e,"firstCharacter"),o=Ae(e,"count"),i=yh(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 bT(e){if(!ut(e))return String(e);let t=lt(e,"direction"),n=gh(e.item),r=yh(e,"ranges").map(CT).join(","),o=Ae(e,"rangeCount"),i=Ae(e,"rangeSampleCount"),s=lt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Rh(s,180)}`:""].filter(Boolean).join(" ")}function gh(e){if(!ut(e))return String(e);let t=lt(e,"name"),n=lt(e,"kind"),r=lt(e,"uri"),o=Ae(e,"line"),i=Ae(e,"endLine"),s=Ae(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function CT(e){return ut(e)?`${Ae(e,"line")}:${Ae(e,"character")}`:String(e)}function ut(e){return typeof e=="object"&&e!==null}function lt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ae(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function yh(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Rh(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 Sh(e,t){let n=Ch(e.fromRanges);return{direction:"incoming",item:_i(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Ph(e.from,t)}}function bh(e,t){let n=Ch(e.fromRanges);return{direction:"outgoing",item:_i(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Ph(e.to,t)}}function _i(e){return{name:e.name,kind:En(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 Ch(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>=hT))break}return n}function Ph(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function En(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}async function kc(e,t,n){let o=(await n.prepareCallHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Ne(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await Ec(n,o,i,new Set([Jr(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Lc(n,o,i,new Set([Jr(o)]),e.contextLines??0):s,u=y=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(y.to.uri),l=c.calls.filter(u).length,d=c.calls.filter(y=>!u(y)),m=[...a.calls.map(y=>({direction:"incoming",...y})),...d.map(y=>({direction:"outgoing",...y}))],p=m.map(y=>y.direction==="incoming"?Sh(y,e.contextLines??0):bh(y,e.contextLines??0)),{pageItems:f,pagination:g}=Ge(p,e.page??1,e.itemsPerPage??Cc),R=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",h=!a.truncatedByDepth&&!c.truncatedByDepth&&!a.truncatedByBudget&&!c.truncatedByBudget&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:_i(o),direction:R,calls:f,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:h,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,truncatedByBudget:a.truncatedByBudget||c.truncatedByBudget,visitedNodeCount:a.visitedNodeCount+c.visitedNodeCount,requestCount:a.requestCount+c.requestCount,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function Ic(e,t,n){let o=(await n.prepareTypeHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Ne(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}=Ge(s,e.page??1,e.itemsPerPage??Tt);return{type:e.type,uri:t.uri,resolvedSymbol:Ze(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 Th=new Set(["references","callers","callees","callHierarchy","implementation"]),xh=100,wT=512*1024,wh=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];async function Eh(e,t,n){let r={candidates:0,warmedFiles:0,skippedLarge:0,possiblyTruncated:!1};if(typeof e.openDocument!="function")return r;try{let o=Zr.extname(t.absolutePath).slice(1),i=wh.includes(o)?wh:[o],s=await Ei({path:n,searchText:t.resolvedSymbol.name,regex:"fixed",wholeWord:!0,output:"files",maxFiles:xh,include:i.filter(Boolean).map(c=>`*.${c}`)}),a={candidates:s.files?.length??0,warmedFiles:0,skippedLarge:0,possiblyTruncated:(s.files?.length??0)>=xh||!!s.stats?.capped};for(let c of s.files??[]){let u=typeof c.path=="string"?c.path:void 0;if(!u)continue;let l=Zr.isAbsolute(u)?u:Zr.join(n,u);if(Zr.resolve(l)!==Zr.resolve(t.absolutePath))try{let d=await PT(l,"utf-8");if(d.length>wT){a.skippedLarge+=1;continue}await e.openDocument(l,d),a.warmedFiles+=1}catch{}}return a}catch{return r}}async function Lh(e,t,n,r){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?qr(e,t,"definition","definitionProvider",await xT({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)})):Ne(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?qr(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):Ne(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?qr(e,t,"implementation","implementationProvider",await n.implementation(t.absolutePath,t.resolvedSymbol.position,t.content)):Ne(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?wc(e,t,await n.findReferences(t.absolutePath,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content),r):Ne(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?Tc(e,t,await n.hover(t.absolutePath,t.resolvedSymbol.position,t.content)):Ne(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?kc(e,t,n):Ne(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?Ic(e,t,n):Ne(e.type,t,"typeHierarchyProvider unsupported",!0)}}import Fc from"node:path";import{fileURLToPath as TT}from"node:url";import{unavailableHintFor as ET}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as LT}from"@octocodeai/octocode-engine/lsp/config";var Oc;function vc(e){return Oc||(Oc=new Set(F.getSupportedJsTsExtensions().map(t=>`.${t}`))),Oc.has(Fc.extname(e).toLowerCase())}function ze(e,t,n){let r=LT(e),o=ET(r,void 0),i=n?.message?` LSP startup detail (${n.kind??"startupFailed"}): ${n.message}.`:"";throw new Se(G.LSP_SERVER_UNAVAILABLE,`No ${r} language server is available for ${e}, so "${t}" cannot be answered semantically.${i} ${o} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}var AT=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];function Ah(e,t){let n=e.startsWith("file://")?TT(e):e;return Fc.isAbsolute(n)?n:Fc.resolve(t,n)}function Dc(){return[...F.getSupportedJsTsExtensions(),...AT]}function _h(){return Dc().map(e=>`**/*.${e}`)}var _T=[".git","node_modules","dist","out","coverage","target"];async function kh(e,t){let n=e.symbolName?.trim();if(n)try{return(await F.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:_h(),excludeDir:[..._T],maxSnippetChars:1})).files[0]?.path}catch{return}}async function Mc(e,t){if(e.uri)return Ah(e.uri,t);let n=await kh(e,t);if(n)return n;try{let o=F.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Dc(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function Nc(e){return e instanceof Error?e.message:String(e)}function Gc(e,t){if(!vc(e))return null;try{let n=F.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}function kT(e){if(!e||typeof e!="object")return!1;let t=e,n=r=>!!r&&typeof r=="object"&&typeof r.line=="number"&&typeof r.character=="number";return n(t.start)&&n(t.end)}function Ih(e,t){if(!vc(e))return null;try{let n=F.extractGraphFacts(t,e);if(!n)return null;let r=JSON.parse(n),i=(Array.isArray(r.declarations)?r.declarations:[]).filter(s=>typeof s.name=="string"&&bi(s.name)&&typeof s.kind=="string"&&kT(s.range)).map(s=>({name:s.name,kind:s.kind,range:s.range}));return i.length>0?i:null}catch{return null}}import{acquirePooledClient as IT,isLanguageServerAvailable as OT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as FT}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Uc(e){let t=await bc(e,le);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await FT(t.value.absolutePath),r=await OT(t.value.absolutePath,n),o=r?await IT(n,t.value.absolutePath):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Gc(t.value.uri,t.value.content),u=c?.length?null:Ih(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(u?.length)s=u,a="native-graph-facts";else if(i&&o){let h=await o.documentSymbols(t.value.absolutePath,t.value.content);s=Array.isArray(h)?h:[],a="lsp"}else{let h=od(t.value.content,t.value.uri);h&&(s=h,a="markdown")}let l=a!==void 0;!l&&!r&&ze(t.value.uri,"documentSymbols");let d=Oh(s),m=vh(s),{pageItems:p,pagination:f}=Ge(d,e.page??1,e.itemsPerPage??Tt),g=Dh(d,h=>h.kind),R=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:d.length,returnedSymbols:p.length,topLevelSymbols:m,kinds:g},payload:{kind:"documentSymbols",symbols:p,...R?{empty:R}:{}},pagination:f}}function Oh(e){let t=[];for(let n of e)Qc(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Qc(e,t,n){if(!e||typeof e!="object")return;let r=e,o=Fh(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:En(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)&&vT.has(En(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Qc(s,t,i)}}var vT=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"]);function Fh(e){if(Hc(e.range))return e.range;let t=e.location;return t&&Hc(t.range)?t.range:void 0}function Hc(e){if(!e||typeof e!="object")return!1;let t=e;return Bc(t.start)&&Bc(t.end)}function Bc(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function vh(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Dh(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}import Mh from"node:path";import{readFile as DT}from"node:fs/promises";import{acquirePooledClientDetailed as Nh,isLanguageServerAvailable as Gh}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as MT}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Hh}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function $c(e){let t=e.symbolName??"",n=Mh.resolve(e.workspaceRoot??(e.uri?await Hh(e.uri):process.cwd())),r=await Mc(e,n);await Gh(r,n)||ze(r,"workspaceSymbol");let i=await Nh(n,r);i.ok===!1&&ze(r,"workspaceSymbol",i);let s=i.client;if(!s.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let a;try{Mh.extname(r)&&await s.openDocument(r),a=await s.workspaceSymbol(t)}catch(d){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${Nc(d)}`}}}let c=await GT(s,Bh(a)),{pageItems:u,pagination:l}=Ge(c,e.page??1,e.itemsPerPage??Tt);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:c.length},payload:c.length>0?{kind:"workspaceSymbol",query:t,symbols:u,totalSymbols:c.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}var NT=10;async function GT(e,t){return t.length===0||t.length>NT?t:Promise.all(t.map(async n=>{try{if(!n.uri)return n;let r=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri,o=await DT(r,"utf8");await e.openDocument(r);let i=await MT({anchorUri:r,symbolName:n.name,locations:await e.gotoDefinition(r,{line:n.line-1,character:n.character},o)});if(!Array.isArray(i)||i.length!==1)return n;let s=i[0],a=(s.range?.start?.line??-1)+1;return!s.uri||a<1||s.uri===n.uri&&a===n.line?n:{...n,uri:s.uri,line:a,endLine:(s.range?.end?.line??s.range?.start?.line??a-1)+1,character:s.range?.start?.character??n.character}}catch{return n}}))}function Bh(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,u=(s?.end?.line??s?.start?.line??0)+1,l=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:En(o),line:c,character:s?.start?.character??0,endLine:u,childCount:0,...l?{containerName:l}:{},uri:a}]})}async function jc(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Hh(t):process.cwd());await Gh(t,n)||ze(t,"diagnostic");let o=await Nh(n,t);o.ok===!1&&ze(t,"diagnostic",o);let i=o.client;if(!i.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let s=await i.getDiagnostics(t),a=Uh(s),c=a.filter(m=>m.severity===1).length,u=a.filter(m=>m.severity===2).length,{pageItems:l,pagination:d}=Ge(a,e.page??1,e.itemsPerPage??Tt);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:a.length,errorCount:c,warningCount:u},payload:a.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:a.length,errorCount:c,warningCount:u}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:d}}function Uh(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>Qh(r))}return[]}function Qh(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}async function $h(e){return ee(e.queries||[],async t=>Te({toolName:le,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await QT(t);return fh(Ac(t,hh(t,n)))}}),{toolName:le,minQueryTimeoutMs:3e4},e)}async function QT(e){if(e.type==="documentSymbols")return Uc(e);if(e.type==="workspaceSymbol")return $c(e);if(e.type==="diagnostic")return jc(e);let t=await oh(e,le);if(t.ok===!1){let u=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return xc(e,u)}let n=e.workspaceRoot??await UT(t.value.absolutePath);await BT(t.value.absolutePath,n)||ze(t.value.uri,e.type);let o=await HT(n,t.value.absolutePath);o.ok===!1&&ze(t.value.uri,e.type,o);let i=o.client,s=Th.has(e.type)?await Eh(i,t.value,n):void 0,a=i.getReadiness?.(),c=await Lh(e,t.value,i,s);return rh(c,a)}var ki={hasTool(e){return Ls(e)},getDescription(e){return Es[e]??""},getToolName(e){return P[e]??String(e)}};var zc=(e,t=ki)=>t.getDescription(e);function $T(e,t){return t.getToolName(e)}function be(e,t,n){let r=$T(t,e);return{...n,name:r,description:zc(r,e)}}var Je={security:"remote",requiresServerRuntime:!0,requiresProviders:!0};function jT(e=ki){let t=be(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:In,inputSchema:On,executionFn:Wp,...Je}}),n=be(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Lt,inputSchema:kn,executionFn:Hp,...Je}}),r=be(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Un,inputSchema:Qn,executionFn:Am,...Je}}),o=be(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Hn,inputSchema:Bn,executionFn:Lm,...Je}}),i=be(e,"GITHUB_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Fn,inputSchema:vn,executionFn:pm,...Je}}),s=be(e,"GITHUB_ISSUES",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Dn,inputSchema:Mn,executionFn:mm,...Je}}),a=be(e,"GITHUB_COMMITS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Nn,inputSchema:Gn,executionFn:fm,...Je}}),c=be(e,"GITHUB_RELEASES",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:qt,inputSchema:Jt,executionFn:hm,...Je}}),u=be(e,"GITHUB_DISCUSSIONS",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:Zt,inputSchema:en,executionFn:ym,...Je}}),l=be(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:$n,inputSchema:jn,executionFn:zm,security:"remote",requiresServerRuntime:!0}}),d=be(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Xt,inputSchema:An,executionFn:mp,...Je}}),m=be(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:tt,inputSchema:Yn,executionFn:Vf,security:"basic"}}),p=be(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Ot,inputSchema:Xn,executionFn:nh,security:"basic"}}),f=be(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:kt,inputSchema:Vn,executionFn:yf,security:"basic"}}),g=be(e,"LOCAL_FIND_DEAD_CODE",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:It,inputSchema:Kn,executionFn:_f,security:"basic"}}),R=be(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:_t,inputSchema:zn,executionFn:df,security:"basic"}}),h={name:le,description:zc(le,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:qn,inputSchema:Jn,executionFn:$h,security:"basic",requiresServerRuntime:!0}},y=[t,n,r,o,i,s,a,...Ln()?[c]:[],...Vt()?[u]:[],l,d,m,p,f,g,R,h];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_PULL_REQUESTS:i,GITHUB_ISSUES:s,GITHUB_COMMITS:a,GITHUB_RELEASES:c,GITHUB_DISCUSSIONS:u,PACKAGE_SEARCH:l,GITHUB_CLONE_REPO:d,LOCAL_RIPGREP:m,LOCAL_VIEW_STRUCTURE:p,LOCAL_FIND_FILES:f,LOCAL_FIND_DEAD_CODE:g,LOCAL_FETCH_CONTENT:R,LSP_GET_SEMANTIC_CONTENT:h,ALL_TOOLS:y}}var Re=jT(),pW=Re.GITHUB_SEARCH_CODE,mW=Re.GITHUB_FETCH_CONTENT,fW=Re.GITHUB_VIEW_REPO_STRUCTURE,hW=Re.GITHUB_SEARCH_REPOSITORIES,gW=Re.GITHUB_PULL_REQUESTS,yW=Re.GITHUB_ISSUES,RW=Re.GITHUB_COMMITS,SW=Re.GITHUB_RELEASES,bW=Re.GITHUB_DISCUSSIONS,CW=Re.PACKAGE_SEARCH,PW=Re.GITHUB_CLONE_REPO,xW=Re.LOCAL_RIPGREP,wW=Re.LOCAL_VIEW_STRUCTURE,TW=Re.LOCAL_FIND_FILES,EW=Re.LOCAL_FIND_DEAD_CODE,LW=Re.LOCAL_FETCH_CONTENT,AW=Re.LSP_GET_SEMANTIC_CONTENT,jh=Re.ALL_TOOLS;import{ContentSanitizer as zT}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as WT}from"@octocodeai/config";var Wh="OCTOCODE_MCP_FULL_TEXT",VT="[content withheld: sanitization failed \u2014 retry the call; if this persists, report it]";function Wc(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:Qe(t.structuredContent)}}catch{t={...t,structuredContent:{status:"error",code:"SANITIZATION_FAILED",error:"structuredContent withheld: sanitization failed \u2014 retry the call; if this persists, report it"},isError:!0}}return KT(t)?YT(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}=zT.sanitizeContent(n.text);return{...n,text:r}}catch{return{...n,text:VT}}return n})}),t)}function KT(e){return WT()==="mcp"&&process.env[Wh]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function YT(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:XT(e.structuredContent)},...t]}}var zh=3;function XT(e){let t=["structuredContent available"];if(eo(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=JT(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;if(eo(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`),Array.isArray(e.results)&&e.results.length>0){let r=e.results.slice(0,zh).map(qT).filter(Boolean);if(r.length>0){let o=e.results.length-zh;t.push(`[${r.join(" \xB7 ")}${o>0?` \xB7 +${o} more`:""}]`)}}}return`${t.join(" \xB7 ")}. Read structuredContent for full data; if your client cannot read structuredContent, set ${Wh}=true.`}function qT(e){if(!eo(e))return"";let t=[];typeof e.id=="string"&&t.push(e.id),t.push(typeof e.status=="string"?e.status:"ok");let n=e.data;return eo(n)&&typeof n.path=="string"&&n.path&&t.push(n.path.split("/").slice(-2).join("/").slice(0,80)),t.join(" ")}function JT(e){let t=0,n=0;for(let r of e)eo(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function eo(e){return typeof e=="object"&&e!==null}var ZT="TOOL_CALLBACK_EXCEPTION";function Vc(e,t){let n=eE(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
65
|
-
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:
|
|
61
|
+
`);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 yc(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(lc.test(e))return"comment";let o=gw(e,t,r);if(o<0)return"code";let i=yw(e);return i>=0&&o>i?"comment":Nf(e,o)?"string":"code"}function gw(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function yw(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 Nf(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function Rw(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function Sw(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 bw(e,t,n,r,o){if(!e||e.length===0)return 0;let i=hc(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=gc(u,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${Ei(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(d+=ne.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(d+=ne.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(d+=ne.substring,m.push("substring match")));let p=c.kind;if(p)d+=Cw(p,m);else{let f=yc(l,r,t.id,n.caseSensitive);f!=="code"?(d+=ne.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(qr(t.declaration,l)&&(d+=ne.declarationLine,m.push("declaration line")),qr(t.export,l)&&(d+=ne.exportLine,m.push("export/public line")),qr(t.import,l)&&(d+=ne.importLine,m.push("import line")),t.id==="markdown"&&dc.test(l)&&(d+=ne.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&Pw(l,r)&&(d+=ne.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function Cw(e,t){switch(e){case"declaration":return t.push("AST: declaration"),ne.declarationLine;case"export":return t.push("AST: export/public"),ne.exportLine;case"configKey":return t.push("AST: config key"),ne.configKeyLine;case"heading":return t.push("AST: heading"),ne.headingLine;case"import":return t.push("AST: import"),ne.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),ne.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function Pw(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 xw(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(wi,"").includes(u))&&(s+=ne.pathSegmentToken,i.push("query token in path"))}let a=Xr(e);return r.extensions.includes(a)&&t.langType&&(s+=ne.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=ne.sourceDir,i.push("source file")),s}function ww(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),ne.lowSignalPathPenalty):e==="test"?(n.push("test file (penalized)"),ne.testPathPenalty):0}function Tw(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*ne.matchCountScale,r=Math.min(n,ne.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function Rc(e,t){let n=Sw(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=>Ew(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 Ew(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${Ei(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function Lw(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let u=Math.log2((t.candidateCount+1)/(c+1)),l=Math.min(u*ne.rareQueryTokenScale,ne.rareQueryTokenCap);l>i&&(i=l,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function Sc(e,t,n){let r=pc(e.path,t.langType,t.profileOverride),o=Ti(e.path),i=Rw(t.keyword),s=[],a=0;return a+=bw(e.matches,r,t,i,s),a+=xw(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=ne.pathUnderQuery,s.push("under requested subtree")),a+=ww(o,t,s),Yr.test(e.path)&&!t.explicitLowSignal&&(a+=ne.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=Tw(e.matchCount??0,s),a+=Lw(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}var Aw=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"]),kw=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Gf(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=_w(i);s.fetch={tool:"localGetFileContent",query:bc({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:'Read exact source around the first match (set minify:"standard" for a token-lean slice, or drop the line range with minify:"symbols" for a skeleton).',confidence:"exact"}}else s.fetch={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" gives a skeleton for orientation; minify:"none" gives exact bytes).',confidence:r.isFileListMode?"low":"exact"};let a=Iw(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a.symbol,lineHint:a.line??i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"low"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"low"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:bc({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:bc({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function _w(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 Iw(e,t,n){if(t.output==="countLines"||t.output==="countMatches"||t.unique==="list"||t.unique==="count")return;if(n==="structural")return Ow(e?.metavars,e?.metavarRanges);if(t.matchWindow)return;if(t.output==="matchOnly"){let o=Cc(e?.value);return o?{symbol:o}:void 0}let r=Cc(t.searchText);return r?{symbol:r}:void 0}function Ow(e,t){if(e)for(let[n,r]of Object.entries(e))for(let[o,i]of r.entries()){let s=Cc(i);if(s)return{symbol:s,line:t?.[n]?.[o]?.line}}}function Cc(e){if(typeof e!="string")return;let t=e.trim();if(kw.test(t)&&!Aw.has(t))return t}function bc(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Li(e,t,n,r,o){let i=t.sort??"relevance",s=n==="structural"&&i==="relevance"?"path":i,a;try{a=fc(e,s,Fw(t),{debug:!1,sortReverse:t.sortReverse})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,u=a.debug,l=c.length,d=t.output==="files"||t.output==="filesWithout",m=t.output==="countLines"||t.output==="countMatches",p=d||m,f=c.reduce((H,I)=>H+(I.matchCount??0),0),g=p?o?.totalOccurrences??o?.totalStructuralMatches??f:f,R=t,h=Math.min(R.itemsPerPage||wt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),y=R.page||1,S=Math.max(1,Math.ceil(l/h)),C=(y-1)*h,x=Math.min(C+h,l),T=c.slice(C,x),L=l>0&&C>=l;L&&r.push(`page:${y} is out of range (only ${S} page(s), ${l} total file(s)) \u2014 returned 0 files. Use page:1..${S}.`);let k=R.maxMatchesPerFile||wt.DEFAULT_MATCHES_PER_PAGE,w=T.map(H=>{let I=H.matches?.length??0,B=Math.max(1,Math.ceil(I/k)),Z=Math.max(1,R.matchPage||1),v=(Z-1)*k,X=I>0&&v>=I,ae=Math.min(v+k,I),ie=p?void 0:H.matches?.slice(v,ae),ce=ie?.length;X&&r.push(`${H.path}: matchPage:${Z} is out of range under maxMatchesPerFile:${k} (only ${B} page(s), ${I} total match(es) for this file) \u2014 returned 0 rows for this file. Use matchPage:1..${B}, or drop matchPage to re-derive it from the current maxMatchesPerFile.`);let ke=u?.get(H.path);return{path:H.path,...d?{}:t.output==="countLines"?{totalMatchedLines:H.matchCount||1}:t.output==="countMatches"?{totalOccurrences:H.matchCount||1}:{totalMatchRows:I,...ce!==void 0?{returnedMatchRows:ce}:{}},...ie!==void 0&&{matches:ie},...ke?{ranking:{score:ke.score,profile:ke.profile,pathRole:ke.pathRole,reasons:ke.reasons}}:{},pagination:!p&&(I>k||X)?{currentPage:Z,totalPages:B,matchesPerPage:k,totalMatches:I,hasMore:Z<B,...Z<B?{nextMatchPage:Z+1}:{},...X?{outOfRange:!0}:{}}:void 0}}),b=w.filter(H=>H.pagination?.hasMore),A=Gf(w,t,n,{isFileListMode:p,currentPage:y,totalFilePages:S,matchPage:R.matchPage||1,matchesPerPage:k,hasFileWithMoreMatches:b.length>0}),M={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:y,totalPages:S,filesPerPage:h,totalFiles:l,...d?{}:{totalMatches:g},hasMore:y<S,...y<S?{nextPage:y+1}:{},...L?{outOfRange:!0}:{}},...r.length>0?{warnings:r}:{},...Object.keys(A).length>0?{next:A}:{}};return Hf(M,t,{totalMatches:g,totalFiles:l})}function Hf(e,t,n){return e}function Fw(e){let t=e.rankingProfile,n=!!(e.include?.length||mc(e.path));return{queryPath:e.path,keyword:e.searchText,langType:e.langType,caseSensitive:e.caseMode==="sensitive",wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function Bf(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=F.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&vw(r)&&n.push(`pattern '${r}' looks literal \u2014 set regex:"fixed" to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&Dw(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function vw(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function Dw(e){return/\(\?[=!<]/.test(e)}import Tn from"node:path";function Nw(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function Gw(e){return{path:e.path,pattern:e.searchText??"",fixedString:e.regex==="fixed",perlRegex:e.regex==="perl",caseSensitive:e.caseMode==="sensitive",caseInsensitive:e.caseMode==="insensitive",wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline==="on"||e.multiline==="dotall",multilineDotall:e.multiline==="dotall",filesOnly:e.output==="files",filesWithoutMatch:e.output==="filesWithout",countLinesPerFile:e.output==="countLines",countMatchesPerFile:e.output==="countMatches",contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:Nw(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.output==="matchOnly",unique:e.unique==="list"||e.unique==="count",countUnique:e.unique==="count",matchWindow:e.matchWindow,maxCollectedFiles:1e4}}function Hw(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}function Bw(e,t){let n=Tn.isAbsolute(e)?e:Tn.join(t,e),r=Tn.relative(t,n);if(!r||r.startsWith("..")||Tn.isAbsolute(r))return 0;let o=Tn.dirname(r);return o==="."?0:o.split(Tn.sep).filter(Boolean).length}async function Uf(e){let t=[],n=Mw(e);if(!n.isValid)return O(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:P.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=tt.safeParse(e);if(!r.success){let h=r.error.issues.map(y=>y.message);return O(new Error(`Query validation failed: ${h.join(", ")}`),e,{toolName:P.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return O(new Error("Path is required for search"),o,{toolName:P.LOCAL_RIPGREP,extra:{warnings:t}});let s=Le(o,P.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Bf({pattern:a.searchText??"",fixedString:a.regex==="fixed",perlRegex:a.regex==="perl"});if(!c.isValid)return O(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:P.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await F.searchRipgrep(Gw(a))}catch(h){return O(h instanceof Error?h:new Error(String(h)),o,{toolName:P.LOCAL_RIPGREP})}let d=l.files.map(h=>({path:h.path,matchCount:h.matchCount,matches:h.matches.map(y=>{let S={line:y.line,column:y.column,value:y.value};return y.count!==void 0&&(S.count=y.count),y.kind!==void 0&&(S.kind=y.kind),y.scoreHint!==void 0&&(S.scoreHint=y.scoreHint),S})})),m=a.maxDepth,p=m===void 0?d:d.filter(h=>Bw(h.path,a.path)<=m);m!==void 0&&p.length!==d.length&&u.push(`Applied maxDepth:${m} after native text search; filtered ${d.length-p.length} deeper file(s).`);let f=Hw(p),g={totalOccurrences:l.stats.matchCount,matchedLines:l.stats.matchedLines,filesMatched:p.length,filesSearched:l.stats.filesSearched,bytesSearched:l.stats.bytesSearched??void 0,searchTime:l.stats.searchTime,capped:l.stats.capped??void 0,capReason:l.stats.capReason??void 0};if(l.stats.capped&&u.push(`Search hit native collection cap (${l.stats.capReason??"resource limit"}); narrow path/include/keywords for exhaustive results.`),p.length===0){let h=['No matches \u2014 broaden the search: try caseMode:"insensitive", a shorter/partial term, or regex:"smart" instead of "fixed".',...a.include?.length||a.maxDepth!==void 0?["Filters are active (include/maxDepth) \u2014 drop them to search the wider tree."]:[],...a.wholeWord?["wholeWord:true excludes partial hits \u2014 drop it to match substrings."]:[]];return Q({status:"empty",searchEngine:"rg",stats:g,hints:h,warnings:[...t,...u]},f)}a.output!=="files"&&f>wt.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(f/1024)}KB).`);let R=await Li(p,o,"rg",[...t,...u],g);return Q(R,f)}import{readFile as $w,stat as jw}from"node:fs/promises";var Qf={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"]}},$f={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 Uw(e){return e.trim().replace(/^\./,"").toLowerCase()}function jf(e){if(!e?.trim())return;let t=Uw(e),n=Qf[t]??$f[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function Pc(e){let t=jf(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}var Qw=/^\s*(\/\/|\/\*|\*|#)/;function Wf(e,t,n){let r=t&&Object.keys(t).length>0;if(n)return{...e?{metavars:e}:{},...r?{metavarRanges:t??void 0}:{}};let o;if(e){o={};for(let[s,a]of Object.entries(e))a.length<=1&&(o[s]=a.map(zf));Object.keys(o).length===0&&(o=void 0)}let i;if(r&&t){i={};for(let[s,a]of Object.entries(t)){let u=(a.length>1?a.filter(l=>!Qw.test(l.text)):a).map(l=>({...l,text:zf(l.text)}));u.length>0&&(i[s]=u)}Object.keys(i).length===0&&(i=void 0)}return{...o?{metavars:o}:{},...i?{metavarRanges:i}:{}}}function zf(e){return e.length>120?`${e.slice(0,120)}\u2026`:e}var Vf=[],Kf=2e3,zw=1e6,Ww="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 Xf(e){if(!e||!/\)\s*\{/.test(e))return;let t=e.replace(/\)\s*\{/,"): $R {");return t===e?void 0:t}function Vw(e){let t=Xf(e);return t?` Try: \`${t}\`.`:""}function Yf(e){return e.include?.length?e.include:Pc(e.langType)}async function Kw(e){try{return(await jw(e)).isFile()}catch{return!1}}async function Yw(e,t,n){let r=await $w(e,"utf8"),o=await F.structuralSearch(r,e,n??t.pattern,t.rule);return{files:o.length>0?[{path:e,matches:o}]:[],totalMatches:o.length,parsedFiles:1,skippedByPreFilter:0,skippedUnsupported:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function qf(e){let t=Le(e,P.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n=await Kw(t.sanitizedPath),r=!!e.captureText,o=S=>({path:t.sanitizedPath,pattern:S??e.pattern,rule:e.rule,...Yf(e)?{include:Yf(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Vf.length?{excludeDir:Vf}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??Kf,maxFileBytes:zw}),i=S=>n?Yw(t.sanitizedPath,e,S):F.structuralSearchFiles(o(S)),s,a=!1,c;try{if(s=await i(),s.totalMatches===0&&e.pattern&&!e.rule&&!/[;}]\s*$/.test(e.pattern))try{let S=await i(`${e.pattern};`);S.totalMatches>0&&(s=S,a=!0)}catch{}if(s.totalMatches===0&&e.pattern&&!e.rule){let S=Xf(e.pattern);if(S)try{let C=await i(S);C.totalMatches>0&&(s=C,c=S)}catch{}}}catch(S){let C=S instanceof Error?S.message:String(S),x=e.langType||"source";return O(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${C} \u2014 patterns must be valid ${x} 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:P.LOCAL_RIPGREP})}let u=s.files.map(S=>({path:S.path,matchCount:S.matches.length,matches:S.matches.map(C=>({line:C.startLine,endLine:C.endLine,value:C.text.replace(/\s+/g," ").trim().slice(0,300),column:C.startCol,endColumn:C.endCol,...Wf(C.metavars,C.metavarRanges,r)}))})),l=e.maxDepth,d=u,m=0;if(typeof l=="number"&&!n){let S=t.sanitizedPath.replace(/\/+$/,"");d=u.filter(C=>(C.path.startsWith(`${S}/`)?C.path.slice(S.length+1):C.path).split("/").length<=l+1),m=u.length-d.length}let p=d.reduce((S,C)=>S+(C.matchCount??C.matches?.length??0),0),f=e.maxFiles??Kf,R=(s.parsedFiles??0)+(s.skippedUnreadable??0)+(s.skippedLarge??0)>=f,h={totalStructuralMatches:typeof l=="number"?p:s.totalMatches,...R?{capReached:!0}:{}},y=[...s.warnings];if(m>0&&y.push(`maxDepth ${l}: dropped ${m} deeper file(s) \u2014 raise maxDepth or omit it to include them.`),a&&y.push(`Matched after appending ';' \u2014 statement patterns must parse as complete statements; the bare pattern parsed as an expression fragment. Results are for "${e.pattern};".`),c&&y.push(`Matched after adding a return-type metavar \u2014 the bare pattern missed functions that declare a return type. Results are for "${c}".`),s.totalMatches===0&&!n)try{let S=F.structuralSearchFilesDetailed(o()),C=S.query;if(C){let x=[`query parsed as ${C.kind}`];C.literalAnchor&&x.push(`literal anchor "${C.literalAnchor}"`),x.push(`pre-filter: ${C.preFilter}`),C.unsafeReason&&x.push(`unsafe: ${C.unsafeReason}`),y.push(`Engine explanation: ${x.join(", ")}.`);for(let T of[...C.diagnostics??[],...S.diagnostics??[]].slice(0,3))y.push(`Engine ${T.severity} [${T.stage}/${T.code}]: ${T.message}${T.recovery?` \u2014 ${T.recovery}`:""}`)}}catch{}return(d.length===0||h.totalStructuralMatches===0)&&e.pattern&&!e.rule&&m===0&&y.push(Ww+Vw(e.pattern)),await Li(d,e,"structural",y,h)}function Xw(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.output==="content"?n.output="files":t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Ai(e){let t=Xw(e);if(t.mode==="structural")return await qf(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Uf(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:G.OUTPUT_TOO_LARGE}:O(n,t,{toolName:P.LOCAL_RIPGREP})}}async function Jf(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=xe(tt,n);return r.ok===!1?r.error:await Ai(r.data)}}),{toolName:P.LOCAL_RIPGREP},e)}var qw=new Set(["+","*","?"]),Jw=1e3;function Zw(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Zf(e,t){let n=e[t];return n===void 0?!1:qw.has(n)||n==="{"&&nT(e,t)}function eT(e,t,n){let r=n.pop()??!1,o=Zf(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?th(e,t+1):t+1})}function tT(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:th(e,t)})}function eh(e){if(e.length>Jw)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=Zw(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=eT(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Zf(e,r)){let i=tT(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function nT(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 th(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function nh(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(!eh(s).safe)return n=n.filter(u=>(u.name.includes("/")?u.name.split("/").pop():u.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(u=>{let l=u.name.includes("/")?u.name.split("/").pop():u.name;return c.test(l)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return n}function rh(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 oh(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}function ih(e){let t={},n=e.find(o=>o.type==="file"&&o.path);n?.path&&(t.fetch={tool:"localGetFileContent",query:{path:n.path,minify:"standard"},why:'Read the first listed file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"});let r=e.find(o=>o.type==="directory"&&o.path);return r?.path&&(t.viewDeeper={tool:"localViewStructure",query:{path:r.path},why:"Descend into the first listed subdirectory.",confidence:"exact"}),t.fetch||t.viewDeeper?t:void 0}var rT=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function oT(e,t){let n=t??rT,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function sh(e){try{let t=Le(e,P.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.detail==="modified"||e.detail==="full"||e.sortBy==="time";return iT(e,t.sanitizedPath,n)}catch(t){let n=Ee.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function iT(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=aT(e),s=sT(e,i),a=r&&s?1e4:1e4,c=oT(t,e.excludeDir),u;try{u=F.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:cT(e),excludeDir:c,limit:a})}catch(L){return dT(L,e,t)}let l=u.entries.map(L=>uT(L,n,e.detail==="full")),d=nh(l,e),m=e.sortBy??"name";d=d.sort((L,k)=>{let w=0;switch(m){case"size":{let b=L.sizeBytes??(L.size?zr(L.size):0),A=k.sizeBytes??(k.size?zr(k.size):0);w=b-A;break}case"time":n&&L.modified&&k.modified?w=L.modified.localeCompare(k.modified):w=L.name.localeCompare(k.name);break;case"extension":w=(L.extension||"").localeCompare(k.extension||"");break;default:w=L.name.localeCompare(k.name);break}return e.reverse?-w:w}),e.limit&&(d=d.slice(0,e.limit));let p=d.length,{paginatedEntries:f,pagination:g}=Sf(d,e),h=e.detail==="full"||e.detail==="modified"?{path:t,entries:f.map(L=>({...oh(L),path:L.path??`${t.replace(/\/$/,"")}/${L.name}`}))}:{path:t,...rh(f)},y=[...u.warnings,...Ci({skipped:u.skipped,permissionDenied:u.permissionDenied}),...u.wasCapped?[`Results capped at ${a} entries during the walk before sorting \u2014 sortBy:"${m}" only orders that partial set, not the true top-N across the whole tree. Add pattern/extensions/entryType/excludeDir or reduce depth to narrow the scope.`]:[],...g.outOfRange?[`page:${e.page} is out of range (only ${g.totalPages} page(s), ${g.totalEntries} total entries) \u2014 returned page ${g.currentPage} instead.`]:[]],S=p===0,C=Rf(d),T={...ih(f)??{},...g.hasMore?{nextPage:Rn(P.LOCAL_VIEW_STRUCTURE,{...e,page:g.currentPage+1},"Continue to the next page of directory entries.")}:{}};return Q({...S?{status:"empty"}:{},...h,summary:C,...g.hasMore||g.totalPages>1||g.outOfRange?{pagination:g}:{},...Object.keys(T).length>0?{next:T}:{},...y.length>0&&{warnings:y}},u.entries.reduce((L,k)=>L+k.path.length,0))}function sT(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function aT(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function cT(e){return e.entryType}function uT(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:wn(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=lT(e.permissions)),o}function lT(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 dT(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=Ee.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return O(a,t,{toolName:P.LOCAL_VIEW_STRUCTURE})}async function ah(e){let{queries:t}=e;return ee(t||[],async n=>Te({toolName:P.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=xe(Ot,n);return r.ok===!1?r.error:await sh(r.data)}}),{toolName:P.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import{acquirePooledClientDetailed as ZT,isLanguageServerAvailable as eE}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as tE}from"@octocodeai/octocode-engine/lsp/workspaceRoot";var pT=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"]);function mT(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function ch(e,t){if(t===void 0||t==="progressIdle")return e;let n=mT(e);if(!n||!pT.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}import{readFile as fT,stat as hT}from"node:fs/promises";import{SymbolResolver as gT,SymbolResolutionError as yT}from"@octocodeai/octocode-engine/lsp/resolver";import{toUri as RT}from"@octocodeai/octocode-engine/lsp/uri";import{LSP_ERROR_CODES as ki}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function xc(e,t){let n=e.uri,r=Le({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await hT(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:ki.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:ki.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:RT(o),absolutePath:o,content:await fT(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:ki.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function uh(e,t){let n=await xc(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 gT({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=e.lineHint!==void 0?Math.abs(o.foundAtLine-e.lineHint):void 0,u=a>1&&c!==void 0&&c>0?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.uri,range:ST(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u},...c!==void 0&&c>0?{lineDeviation:c}:{}}}}}catch(o){if(o instanceof yT)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:ki.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 ST(e){return{start:e,end:{line:e.line,character:e.character}}}import eo from"node:path";import{readFile as MT}from"node:fs/promises";import{resolveImportAliasDefinitions as NT}from"@octocodeai/octocode-engine/lsp/resolver";var Tt=40,_i=40,wc=10;function Tc(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 Ec(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Tc(e.type,t),reason:t}}}function Ne(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Tc(e,n),reason:n}}}function Ge(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function Jr(e,t,n,r,o){let i=o.length>0,s=o.map(Di),{pageItems:a,pagination:c}=Ge(s,e.page??1,e.itemsPerPage??_i);return{type:e.type,uri:t.uri,resolvedSymbol:Ze(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 Lc(e,t,n,r){let o=n.map(d=>{let m=d.uri===t.uri&&d.range.start.line===t.resolvedSymbol.position.line&&d.range.start.character===t.resolvedSymbol.position.character;return{...d,...m?{isDefinition:!0}:{}}}),i=e.groupByFile?lh(o):void 0,s=i??o.map(Di),{pageItems:a,pagination:c}=Ge(s,e.page??1,e.itemsPerPage??_i),u=o.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0,l=r?.possiblyTruncated===!0?[`Reference warmup opened ${r.warmedFiles}/${r.candidates} candidate file(s) and may be incomplete because the candidate set hit the warmup cap; narrow workspaceRoot/path or confirm with localSearchCode before unused/safe-delete claims.`]:[];return{type:"references",uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...i?{byFile:a}:{locations:a},totalReferences:o.length,totalFiles:new Set(o.map(d=>d.uri)).size,...o.length>0&&o.every(d=>d.isDefinition)?{definitionOnly:!0}:{},...r?{warmup:r}:{},...u?{empty:u}:{}},pagination:c,...l.length>0?{warnings:l}:{}}}async function Ac(e,t,n){let r=dh(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function lh(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 dh(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=>ph(r)).join(`
|
|
62
|
+
`).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 ph(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}import{safeReadLineWindow as bT}from"@octocodeai/octocode-engine/lsp/validation";var CT={maxNodes:100,maxRequests:50},mh={truncatedByDepth:!1,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,cycleCount:0,failedRequestCount:0};function fh(e){return{...CT,...e,visitedNodeCount:0,requestCount:0,truncatedByBudget:!1}}function hh(e){return e.requestCount>=e.maxRequests?(e.truncatedByBudget=!0,!1):(e.requestCount+=1,!0)}function gh(e){return e.visitedNodeCount>=e.maxNodes?(e.truncatedByBudget=!0,!1):(e.visitedNodeCount+=1,!0)}function qe(e,t){return{...e,truncatedByBudget:t.truncatedByBudget,visitedNodeCount:t.visitedNodeCount,requestCount:t.requestCount}}function Zr(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function yh(e,t,n){if(t<=0)return e;let r=n?.[0]?.start.line??e.range.start.line,o=await bT(e.uri,r,t);if(!o)return e;let i=bo(o).length,s=Math.max(0,r-t),a=s+Math.max(0,i-1);return{...e,content:o,displayRange:{startLine:s+1,endLine:a+1}}}async function PT(e,t){return Promise.all(e.map(async n=>({...n,from:await yh(n.from,t,n.fromRanges)})))}async function xT(e,t){return Promise.all(e.map(async n=>({...n,to:await yh(n.to,t)})))}async function kc(e,t,n,r,o,i=fh(void 0)){if(n<=0||!e)return{calls:[],...mh};if(!hh(i))return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getIncomingCalls(t),a=o>0?await PT(s,o):s;if(n===1)return qe({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=Zr(u.from);if(r.has(l)){c.push(qe({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!gh(i)||(r.add(l),c.push(await kc(e,u.from,n-1,r,o,i)),i.truncatedByBudget))break}return qe({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}async function _c(e,t,n,r,o,i=fh(void 0)){if(n<=0||!e)return{calls:[],...mh};if(!hh(i))return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},i);try{let s=await e.getOutgoingCalls(t),a=o>0?await xT(s,o):s;if(n===1)return qe({calls:a,truncatedByDepth:a.length>0,cycleCount:0,failedRequestCount:0},i);let c=[];for(let u of a){let l=Zr(u.to);if(r.has(l)){c.push(qe({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},i));continue}if(!gh(i)||(r.add(l),c.push(await _c(e,u.to,n-1,r,o,i)),i.truncatedByBudget))break}return qe({calls:[...a,...c.flatMap(u=>u.calls)],truncatedByDepth:c.some(u=>u.truncatedByDepth),cycleCount:c.reduce((u,l)=>u+l.cycleCount,0),failedRequestCount:c.reduce((u,l)=>u+l.failedRequestCount,0)},i)}catch{return qe({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},i)}}var wT=new Set(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),TT=new Set(["symbolNotFound","anchorFailed"]);function ET(e){if(e.kind==="empty"&&typeof e.category=="string")return{category:e.category,...typeof e.reason=="string"?{reason:e.reason}:{}};let t=e.empty;if(ut(t)&&typeof t.category=="string")return{category:t.category,...typeof t.reason=="string"?{reason:t.reason}:{}}}function LT(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"rs":return"^\\s*pub\\s";case"py":case"pyi":return"^\\s*(def|class)\\s";case"go":return"^(func|type|var|const)\\s";case"java":case"kt":case"scala":case"cs":return"^\\s*(public|protected|internal)\\s";case"rb":return"^\\s*(def|class|module)\\s";default:return"^\\s*export\\s"}}function AT(e,t){let n=e.symbolName;if(typeof n=="string"&&n.trim())return n.trim();let r=t.resolvedSymbol?.name;if(typeof r=="string"&&r.trim())return r.trim()}function Ic(e,t){if(!Oc(t))return t;let n=t.payload,r=n.locations?.[0],o=r?.displayRange?.startLine;if(r?.uri&&typeof o=="number"){let c=r.uri.startsWith("file://")?decodeURIComponent(r.uri.slice(7)):r.uri;return{...t,next:{readSite:{tool:"localGetFileContent",query:{path:c,startLine:Math.max(1,o-3),endLine:(r.displayRange?.endLine??o)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}let i=ET(n);if(i?.category==="unsupportedOperation"&&t.type==="documentSymbols"&&t.uri){let c=t.uri.startsWith("file://")?decodeURIComponent(t.uri.slice(7)):t.uri;return{...t,next:{textSearch:{tool:"localSearchCode",query:{path:c,searchText:LT(c),regex:"perl"},why:"documentSymbols is unsupported for this file's language server \u2014 fall back to a regex search over top-level declarations for an outline.",confidence:"low"}}}}let s=AT(e,t);if(!i||!s||!wT.has(i.category))return t;let a={textSearch:{tool:"localSearchCode",query:{keywords:s},why:`Semantic ${t.type} returned no result (${i.category}) \u2014 fall back to a text search for "${s}"`,confidence:"low"}};return TT.has(i.category)&&t.uri&&(a.reAnchor={tool:"lspGetSemantics",query:{type:"documentSymbols",uri:t.uri},why:"Re-anchor: list this file's symbols to find the correct lineHint, then retry the semantic query",confidence:"medium"}),{...t,next:a}}var kT=8;function Sh(e){return Q(e,N(e))}function bh(e,t){return e.format!=="compact"||!Oc(t)?t:_T(t)}function Oc(e){return ut(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&ut(e.payload)}function _T(e){return{...e,format:"compact",payload:IT(e.payload)}}function IT(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Rh)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(FT)}:{locations:(e.locations??[]).map(Rh)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Ch(e.root)}:{},direction:e.direction,calls:e.calls.map(vT),...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(OT)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function OT(e){if(!ut(e))return String(e);let t=Ae(e,"line"),n=Ae(e,"character"),r=Ae(e,"endLine"),o=lt(e,"kind"),i=lt(e,"name"),s=Ae(e,"childCount"),a=lt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Rh(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${xh(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function FT(e){if(!ut(e))return String(e);let t=lt(e,"uri"),n=Ae(e,"firstLine"),r=Ae(e,"firstCharacter"),o=Ae(e,"count"),i=Ph(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 vT(e){if(!ut(e))return String(e);let t=lt(e,"direction"),n=Ch(e.item),r=Ph(e,"ranges").map(DT).join(","),o=Ae(e,"rangeCount"),i=Ae(e,"rangeSampleCount"),s=lt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${xh(s,180)}`:""].filter(Boolean).join(" ")}function Ch(e){if(!ut(e))return String(e);let t=lt(e,"name"),n=lt(e,"kind"),r=lt(e,"uri"),o=Ae(e,"line"),i=Ae(e,"endLine"),s=Ae(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function DT(e){return ut(e)?`${Ae(e,"line")}:${Ae(e,"character")}`:String(e)}function ut(e){return typeof e=="object"&&e!==null}function lt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ae(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Ph(e,t){let n=e[t];return Array.isArray(n)?n:[]}function xh(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 wh(e,t){let n=Eh(e.fromRanges);return{direction:"incoming",item:Ii(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Lh(e.from,t)}}function Th(e,t){let n=Eh(e.fromRanges);return{direction:"outgoing",item:Ii(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Lh(e.to,t)}}function Ii(e){return{name:e.name,kind:En(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 Eh(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>=kT))break}return n}function Lh(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function En(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}async function Fc(e,t,n){let o=(await n.prepareCallHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Ne(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await kc(n,o,i,new Set([Zr(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await _c(n,o,i,new Set([Zr(o)]),e.contextLines??0):s,u=y=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(y.to.uri),l=c.calls.filter(u).length,d=c.calls.filter(y=>!u(y)),m=[...a.calls.map(y=>({direction:"incoming",...y})),...d.map(y=>({direction:"outgoing",...y}))],p=m.map(y=>y.direction==="incoming"?wh(y,e.contextLines??0):Th(y,e.contextLines??0)),{pageItems:f,pagination:g}=Ge(p,e.page??1,e.itemsPerPage??wc),R=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",h=!a.truncatedByDepth&&!c.truncatedByDepth&&!a.truncatedByBudget&&!c.truncatedByBudget&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Ze(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Ii(o),direction:R,calls:f,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:h,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,truncatedByBudget:a.truncatedByBudget||c.truncatedByBudget,visitedNodeCount:a.visitedNodeCount+c.visitedNodeCount,requestCount:a.requestCount+c.requestCount,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function vc(e,t,n){let o=(await n.prepareTypeHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return Ne(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}=Ge(s,e.page??1,e.itemsPerPage??Tt);return{type:e.type,uri:t.uri,resolvedSymbol:Ze(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 _h=new Set(["references","callers","callees","callHierarchy","implementation"]),Ah=100,GT=512*1024,kh=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];async function Ih(e,t,n){let r={candidates:0,warmedFiles:0,skippedLarge:0,possiblyTruncated:!1};if(typeof e.openDocument!="function")return r;try{let o=eo.extname(t.absolutePath).slice(1),i=kh.includes(o)?kh:[o],s=await Ai({path:n,searchText:t.resolvedSymbol.name,regex:"fixed",wholeWord:!0,output:"files",maxFiles:Ah,include:i.filter(Boolean).map(c=>`*.${c}`)}),a={candidates:s.files?.length??0,warmedFiles:0,skippedLarge:0,possiblyTruncated:(s.files?.length??0)>=Ah||!!s.stats?.capped};for(let c of s.files??[]){let u=typeof c.path=="string"?c.path:void 0;if(!u)continue;let l=eo.isAbsolute(u)?u:eo.join(n,u);if(eo.resolve(l)!==eo.resolve(t.absolutePath))try{let d=await MT(l,"utf-8");if(d.length>GT){a.skippedLarge+=1;continue}await e.openDocument(l,d),a.warmedFiles+=1}catch{}}return a}catch{return r}}async function Oh(e,t,n,r){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?Jr(e,t,"definition","definitionProvider",await NT({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)})):Ne(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?Jr(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):Ne(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?Jr(e,t,"implementation","implementationProvider",await n.implementation(t.absolutePath,t.resolvedSymbol.position,t.content)):Ne(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?Lc(e,t,await n.findReferences(t.absolutePath,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content),r):Ne(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?Ac(e,t,await n.hover(t.absolutePath,t.resolvedSymbol.position,t.content)):Ne(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?Fc(e,t,n):Ne(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?vc(e,t,n):Ne(e.type,t,"typeHierarchyProvider unsupported",!0)}}import Mc from"node:path";import{fileURLToPath as HT}from"node:url";import{unavailableHintFor as BT}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as UT}from"@octocodeai/octocode-engine/lsp/config";var Dc;function Nc(e){return Dc||(Dc=new Set(F.getSupportedJsTsExtensions().map(t=>`.${t}`))),Dc.has(Mc.extname(e).toLowerCase())}function ze(e,t,n){let r=UT(e),o=BT(r,void 0),i=n?.message?` LSP startup detail (${n.kind??"startupFailed"}): ${n.message}.`:"";throw new Se(G.LSP_SERVER_UNAVAILABLE,`No ${r} language server is available for ${e}, so "${t}" cannot be answered semantically.${i} ${o} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}var QT=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];function Fh(e,t){let n=e.startsWith("file://")?HT(e):e;return Mc.isAbsolute(n)?n:Mc.resolve(t,n)}function Gc(){return[...F.getSupportedJsTsExtensions(),...QT]}function vh(){return Gc().map(e=>`**/*.${e}`)}var $T=[".git","node_modules","dist","out","coverage","target"];async function Dh(e,t){let n=e.symbolName?.trim();if(n)try{return(await F.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:vh(),excludeDir:[...$T],maxSnippetChars:1})).files[0]?.path}catch{return}}async function Hc(e,t){if(e.uri)return Fh(e.uri,t);let n=await Dh(e,t);if(n)return n;try{let o=F.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Gc(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function Bc(e){return e instanceof Error?e.message:String(e)}function Uc(e,t){if(!Nc(e))return null;try{let n=F.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}function jT(e){if(!e||typeof e!="object")return!1;let t=e,n=r=>!!r&&typeof r=="object"&&typeof r.line=="number"&&typeof r.character=="number";return n(t.start)&&n(t.end)}function Mh(e,t){if(!Nc(e))return null;try{let n=F.extractGraphFacts(t,e);if(!n)return null;let r=JSON.parse(n),i=(Array.isArray(r.declarations)?r.declarations:[]).filter(s=>typeof s.name=="string"&&Pi(s.name)&&typeof s.kind=="string"&&jT(s.range)).map(s=>({name:s.name,kind:s.kind,range:s.range}));return i.length>0?i:null}catch{return null}}import{acquirePooledClient as zT,isLanguageServerAvailable as WT}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as VT}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function jc(e){let t=await xc(e,le);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await VT(t.value.absolutePath),r=await WT(t.value.absolutePath,n),o=r?await zT(n,t.value.absolutePath):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=Uc(t.value.uri,t.value.content),u=c?.length?null:Mh(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(u?.length)s=u,a="native-graph-facts";else if(i&&o){let h=await o.documentSymbols(t.value.absolutePath,t.value.content);s=Array.isArray(h)?h:[],a="lsp"}else{let h=sd(t.value.content,t.value.uri);h&&(s=h,a="markdown")}let l=a!==void 0;!l&&!r&&ze(t.value.uri,"documentSymbols");let d=Nh(s),m=Hh(s),{pageItems:p,pagination:f}=Ge(d,e.page??1,e.itemsPerPage??Tt),g=Bh(d,h=>h.kind),R=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:d.length,returnedSymbols:p.length,topLevelSymbols:m,kinds:g},payload:{kind:"documentSymbols",symbols:p,...R?{empty:R}:{}},pagination:f}}function Nh(e){let t=[];for(let n of e)zc(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function zc(e,t,n){if(!e||typeof e!="object")return;let r=e,o=Gh(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:En(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)&&KT.has(En(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)zc(s,t,i)}}var KT=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"]);function Gh(e){if(Qc(e.range))return e.range;let t=e.location;return t&&Qc(t.range)?t.range:void 0}function Qc(e){if(!e||typeof e!="object")return!1;let t=e;return $c(t.start)&&$c(t.end)}function $c(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function Hh(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function Bh(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}import Uh from"node:path";import{readFile as YT}from"node:fs/promises";import{acquirePooledClientDetailed as Qh,isLanguageServerAvailable as $h}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as XT}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as jh}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function Wc(e){let t=e.symbolName??"",n=Uh.resolve(e.workspaceRoot??(e.uri?await jh(e.uri):process.cwd())),r=await Hc(e,n);await $h(r,n)||ze(r,"workspaceSymbol");let i=await Qh(n,r);i.ok===!1&&ze(r,"workspaceSymbol",i);let s=i.client;if(!s.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let a;try{Uh.extname(r)&&await s.openDocument(r),a=await s.workspaceSymbol(t)}catch(d){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${Bc(d)}`}}}let c=await JT(s,zh(a)),{pageItems:u,pagination:l}=Ge(c,e.page??1,e.itemsPerPage??Tt);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:c.length},payload:c.length>0?{kind:"workspaceSymbol",query:t,symbols:u,totalSymbols:c.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}var qT=10;async function JT(e,t){return t.length===0||t.length>qT?t:Promise.all(t.map(async n=>{try{if(!n.uri)return n;let r=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri,o=await YT(r,"utf8");await e.openDocument(r);let i=await XT({anchorUri:r,symbolName:n.name,locations:await e.gotoDefinition(r,{line:n.line-1,character:n.character},o)});if(!Array.isArray(i)||i.length!==1)return n;let s=i[0],a=(s.range?.start?.line??-1)+1;return!s.uri||a<1||s.uri===n.uri&&a===n.line?n:{...n,uri:s.uri,line:a,endLine:(s.range?.end?.line??s.range?.start?.line??a-1)+1,character:s.range?.start?.character??n.character}}catch{return n}}))}function zh(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,u=(s?.end?.line??s?.start?.line??0)+1,l=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:En(o),line:c,character:s?.start?.character??0,endLine:u,childCount:0,...l?{containerName:l}:{},uri:a}]})}async function Vc(e){let t=e.uri??"",n=e.workspaceRoot??(t?await jh(t):process.cwd());await $h(t,n)||ze(t,"diagnostic");let o=await Qh(n,t);o.ok===!1&&ze(t,"diagnostic",o);let i=o.client;if(!i.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let s=await i.getDiagnostics(t),a=Wh(s),c=a.filter(m=>m.severity===1).length,u=a.filter(m=>m.severity===2).length,{pageItems:l,pagination:d}=Ge(a,e.page??1,e.itemsPerPage??Tt);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:a.length,errorCount:c,warningCount:u},payload:a.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:a.length,errorCount:c,warningCount:u}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:d}}function Wh(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>Vh(r))}return[]}function Vh(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}async function Kh(e){return ee(e.queries||[],async t=>Te({toolName:le,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await nE(t);return Sh(Ic(t,bh(t,n)))}}),{toolName:le,minQueryTimeoutMs:3e4},e)}async function nE(e){if(e.type==="documentSymbols")return jc(e);if(e.type==="workspaceSymbol")return Wc(e);if(e.type==="diagnostic")return Vc(e);let t=await uh(e,le);if(t.ok===!1){let u=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return Ec(e,u)}let n=e.workspaceRoot??await tE(t.value.absolutePath);await eE(t.value.absolutePath,n)||ze(t.value.uri,e.type);let o=await ZT(n,t.value.absolutePath);o.ok===!1&&ze(t.value.uri,e.type,o);let i=o.client,s=_h.has(e.type)?await Ih(i,t.value,n):void 0,a=i.getReadiness?.(),c=await Oh(e,t.value,i,s);return ch(c,a)}var Oi={hasTool(e){return ks(e)},getDescription(e){return As[e]??""},getToolName(e){return P[e]??String(e)}};var Kc=(e,t=Oi)=>t.getDescription(e);function rE(e,t){return t.getToolName(e)}function be(e,t,n){let r=rE(t,e);return{...n,name:r,description:Kc(r,e)}}var Je={security:"remote",requiresServerRuntime:!0,requiresProviders:!0};function oE(e=Oi){let t=be(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:In,inputSchema:On,executionFn:qp,...Je}}),n=be(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Lt,inputSchema:_n,executionFn:jp,...Je}}),r=be(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Un,inputSchema:Qn,executionFn:Fm,...Je}}),o=be(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Hn,inputSchema:Bn,executionFn:Om,...Je}}),i=be(e,"GITHUB_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Fn,inputSchema:vn,executionFn:ym,...Je}}),s=be(e,"GITHUB_ISSUES",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Dn,inputSchema:Mn,executionFn:Rm,...Je}}),a=be(e,"GITHUB_COMMITS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Nn,inputSchema:Gn,executionFn:Sm,...Je}}),c=be(e,"GITHUB_RELEASES",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:qt,inputSchema:Jt,executionFn:bm,...Je}}),u=be(e,"GITHUB_DISCUSSIONS",{isDefault:!1,isLocal:!1,type:"history",direct:{schema:Zt,inputSchema:en,executionFn:Pm,...Je}}),l=be(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:$n,inputSchema:jn,executionFn:Xm,security:"remote",requiresServerRuntime:!0}}),d=be(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Xt,inputSchema:An,executionFn:hp,...Je}}),m=be(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:tt,inputSchema:Yn,executionFn:Jf,security:"basic"}}),p=be(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Ot,inputSchema:Xn,executionFn:ah,security:"basic"}}),f=be(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:_t,inputSchema:Vn,executionFn:Pf,security:"basic"}}),g=be(e,"LOCAL_FIND_DEAD_CODE",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:It,inputSchema:Kn,executionFn:vf,security:"basic"}}),R=be(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:kt,inputSchema:zn,executionFn:gf,security:"basic"}}),h={name:le,description:Kc(le,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:qn,inputSchema:Jn,executionFn:Kh,security:"basic",requiresServerRuntime:!0}},y=[t,n,r,o,i,s,a,...Ln()?[c]:[],...Vt()?[u]:[],l,d,m,p,f,g,R,h];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_PULL_REQUESTS:i,GITHUB_ISSUES:s,GITHUB_COMMITS:a,GITHUB_RELEASES:c,GITHUB_DISCUSSIONS:u,PACKAGE_SEARCH:l,GITHUB_CLONE_REPO:d,LOCAL_RIPGREP:m,LOCAL_VIEW_STRUCTURE:p,LOCAL_FIND_FILES:f,LOCAL_FIND_DEAD_CODE:g,LOCAL_FETCH_CONTENT:R,LSP_GET_SEMANTIC_CONTENT:h,ALL_TOOLS:y}}var Re=oE(),_W=Re.GITHUB_SEARCH_CODE,IW=Re.GITHUB_FETCH_CONTENT,OW=Re.GITHUB_VIEW_REPO_STRUCTURE,FW=Re.GITHUB_SEARCH_REPOSITORIES,vW=Re.GITHUB_PULL_REQUESTS,DW=Re.GITHUB_ISSUES,MW=Re.GITHUB_COMMITS,NW=Re.GITHUB_RELEASES,GW=Re.GITHUB_DISCUSSIONS,HW=Re.PACKAGE_SEARCH,BW=Re.GITHUB_CLONE_REPO,UW=Re.LOCAL_RIPGREP,QW=Re.LOCAL_VIEW_STRUCTURE,$W=Re.LOCAL_FIND_FILES,jW=Re.LOCAL_FIND_DEAD_CODE,zW=Re.LOCAL_FETCH_CONTENT,WW=Re.LSP_GET_SEMANTIC_CONTENT,Yh=Re.ALL_TOOLS;import{ContentSanitizer as iE}from"@octocodeai/octocode-engine/security";import{getRuntimeSurface as sE}from"@octocodeai/config";var qh="OCTOCODE_MCP_FULL_TEXT",aE="[content withheld: sanitization failed \u2014 retry the call; if this persists, report it]";function Yc(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:Qe(t.structuredContent)}}catch{t={...t,structuredContent:{status:"error",code:"SANITIZATION_FAILED",error:"structuredContent withheld: sanitization failed \u2014 retry the call; if this persists, report it"},isError:!0}}return cE(t)?uE(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}=iE.sanitizeContent(n.text);return{...n,text:r}}catch{return{...n,text:aE}}return n})}),t)}function cE(e){return sE()==="mcp"&&process.env[qh]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function uE(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:lE(e.structuredContent)},...t]}}var Xh=3;function lE(e){let t=["structuredContent available"];if(to(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=pE(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;if(to(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`),Array.isArray(e.results)&&e.results.length>0){let r=e.results.slice(0,Xh).map(dE).filter(Boolean);if(r.length>0){let o=e.results.length-Xh;t.push(`[${r.join(" \xB7 ")}${o>0?` \xB7 +${o} more`:""}]`)}}}return`${t.join(" \xB7 ")}. Read structuredContent for full data; if your client cannot read structuredContent, set ${qh}=true.`}function dE(e){if(!to(e))return"";let t=[];typeof e.id=="string"&&t.push(e.id),t.push(typeof e.status=="string"?e.status:"ok");let n=e.data;return to(n)&&typeof n.path=="string"&&n.path&&t.push(n.path.split("/").slice(-2).join("/").slice(0,80)),t.join(" ")}function pE(e){let t=0,n=0;for(let r of e)to(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function to(e){return typeof e=="object"&&e!==null}var mE="TOOL_CALLBACK_EXCEPTION";function Xc(e,t){let n=fE(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
|
|
63
|
+
message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:mE,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Yc(r)}catch{return r}}function fE(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:hE(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 hE(e){try{return JSON.stringify(e)}catch{return}}import{withSecurityValidation as gE,withBasicSecurityValidation as yE}from"@octocodeai/octocode-engine/security";function Jh(e,t){let n=gE(e,(r,o)=>t(r,o));return(r,o)=>n(r,o)}function Zh(e,t){let n=yE((r,o)=>e(r,o),t);return(r,o)=>n(r,o)}var Fi=null,vi=null,SE=_l;function bE(e){let t=e;return n=>t(n)}function CE(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:bE(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var PE=Yh.map(CE);function xE(e){return PE.find(t=>t.name===e)}async function eg(e,t){let n=xE(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=wE(n,t);return await TE(n),EE(n),await LE(n,r)}catch(r){return Xc(n.name,r)}}function wE(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function TE(e){e.requiresServerRuntime&&(Fi||(Fi=SE().catch(t=>{throw Fi=null,t})),await Fi),e.requiresProviders&&(vi||(vi=Md().then(()=>{}).catch(t=>{throw vi=null,t})),await vi)}function EE(e){if(!e.isLocal&&!e.isClone)return;let t=RE();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 LE(e,t){try{let n=e.security==="remote"?await AE(e,t):await kE(e,t);return Yc(n)}catch(n){return Xc(e.name,n)}}async function AE(e,t){return Jh(e.name,async(r,o)=>e.execute({...r,authInfo:o.authInfo,sessionId:o.sessionId,signal:o.signal}))(t,{})}async function kE(e,t){return Zh(e.execute,e.name)(t)}import{completeMetadata as _E}from"@octocodeai/octocode-core";var qc=null;function IE(){return qc||(qc=_E),qc}async function OE(){return IE()}export{Ui as DIRECT_TOOL_CATEGORIES,Bu as DIRECT_TOOL_DEFINITIONS,Fe as DirectToolInputError,Qg as buildDirectToolExampleQuery,eg as executeDirectTool,nt as findDirectToolDefinition,mb as formatCallToolResultForOutput,Mg as formatDirectToolMetadataSchemaText,Dg as formatDirectToolSchemaText,Ng as getDirectToolAutoFilledFields,Ft as getDirectToolCategory,Gg as getDirectToolDescription,er as getDirectToolDisplayFields,OE as loadToolContent,Ku as prepareDirectToolInput,Kg as prepareDirectToolInputFromJsonText,Fg as sortDirectToolNames};
|