@octocodeai/octocode-tools-core 18.1.0 → 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/dist/direct.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/direct.js
CHANGED
|
@@ -6,7 +6,7 @@ const require = __createRequire(import.meta.url);
|
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
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.0";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(`
|
|
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
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
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
12
|
`,t);return n===-1?void 0:n+1}function wo(e){let t=e.trimEnd().split(`
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ const __filename = __fileURLToPath(import.meta.url);
|
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
8
|
import{withSecurityValidation as hy,withBasicSecurityValidation as gy}from"@octocodeai/octocode-engine/security";function Vu(e,t){let n=hy(e,(r,o)=>t(r,o));return(r,o)=>n(r,o)}function Ku(e,t){let n=gy((r,o)=>e(r,o),t);return(r,o)=>n(r,o)}var me=30,oe=100,qL=10,JL=100,Yu=200,Ne=20,ct=100,Mo=20,ln=50,Je=1e4,bt=20,No=1e3,Xu=100,pn=5e4,qu=8e3,Go=1e5,Ju=500;var Ts={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},tr={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"}},nr={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})`}},yy={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"}},Ct={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}`}},xt={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"}},Ee={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}`}},Ry={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}`}},rr={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"}},Sy={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}`}},eA={...Ts,...tr,...nr,...yy,...Ct,...xt,...Ee,...Ry,...rr,...Sy};var H={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"},by=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(by||{}),Zu={[H.PATH_VALIDATION_FAILED]:{code:H.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[H.FILE_ACCESS_FAILED]:{code:H.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[H.FILE_READ_FAILED]:{code:H.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[H.FILE_TOO_LARGE]:{code:H.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[H.BINARY_FILE_UNSUPPORTED]:{code:H.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[H.NO_MATCHES]:{code:H.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[H.OUTPUT_TOO_LARGE]:{code:H.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[H.COMMAND_NOT_AVAILABLE]:{code:H.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[H.COMMAND_EXECUTION_FAILED]:{code:H.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[H.COMMAND_TIMEOUT]:{code:H.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[H.TOOL_EXECUTION_FAILED]:{code:H.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[H.LSP_SERVER_UNAVAILABLE]:{code:H.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 xe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Zu[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
|
|
9
9
|
Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function Es(e){return e instanceof xe}function el(e,t=H.TOOL_EXECUTION_FAILED,n){if(Es(e))return e;if(e instanceof Error)return new xe(t,e.message,n,e);let r=String(e);return new xe(t,r,n)}import{redactPath as or}from"@octocodeai/octocode-engine/pathUtils";var Le={pathValidationFailed:(e,t,n)=>new xe(H.PATH_VALIDATION_FAILED,t||`Path validation failed: ${or(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=or(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 xe(H.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new xe(H.FILE_READ_FAILED,`Failed to read file: ${or(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new xe(H.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 xe(H.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${or(e)}. Use localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new xe(H.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new xe(H.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 xe(H.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new xe(H.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as mR}from"octokit";import{throttling as fR}from"@octokit/plugin-throttling";import{createHash as hR}from"crypto";function Ze(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function ut(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 ir(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var sr=new Map,Cy=300*1e3;function xy(e){let t=Ze(e),n=sr.get(t);return!n||Date.now()-n.cachedAt>=Cy?!1:n.credentials?!ut(n.credentials):!0}function ar(e){e?sr.delete(Ze(e)):sr.clear()}function tl(e){let t=Ze(e);if(xy(t))return sr.get(t).credentials}function nl(e,t){let n=Ze(e);sr.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as $o,readFileSync as al,writeFileSync as cl,unlinkSync as sl,statSync as Ay,chmodSync as ky}from"node:fs";import{createCipheriv as _y,createDecipheriv as Iy,randomBytes as ul}from"node:crypto";import{existsSync as Ho,mkdirSync as Bo}from"node:fs";import{join as je}from"node:path";import{getOctocodeHome as Py}from"@octocodeai/config";var Uo=448;function rl(){return Py(process.env)}function zt(){return Ie}var Ie=rl(),we={home:Ie,config:je(Ie,".octocoderc"),credentials:je(Ie,"credentials.json"),key:je(Ie,".key"),session:je(Ie,"session.json"),stats:je(Ie,"stats.json"),tmp:je(Ie,"tmp"),clone:je(Ie,"tmp","clone"),tree:je(Ie,"tmp","tree"),repos:je(Ie,"tmp","clone"),cliConfig:je(Ie,"config.json"),lspConfig:je(Ie,"lsp-servers.json")};function Qo(){Ho(we.home)||Bo(we.home,{recursive:!0,mode:Uo})}function wy(){ol()}function Ls(){Qo(),Ho(we.tmp)||Bo(we.tmp,{recursive:!0,mode:Uo})}function ol(){Ls(),Ho(we.clone)||Bo(we.clone,{recursive:!0,mode:Uo})}function Ty(){Ls(),Ho(we.tree)||Bo(we.tree,{recursive:!0,mode:Uo})}import{z as Se}from"zod";var Ey=Se.object({token:Se.string(),tokenType:Se.literal("oauth"),scopes:Se.array(Se.string()).optional(),refreshToken:Se.string().optional(),expiresAt:Se.string().optional(),refreshTokenExpiresAt:Se.string().optional()}),Ly=Se.object({hostname:Se.string(),username:Se.string(),token:Ey,gitProtocol:Se.enum(["ssh","https"]),createdAt:Se.string(),updatedAt:Se.string()}),il=Se.object({version:Se.number(),credentials:Se.record(Se.string(),Ly)});var As=we.home,lt=we.credentials,et=we.key,ll="aes-256-gcm",Oy=16;function Pt(){Qo()}function pl(){if(Pt(),$o(et))return Ay(et).mode&511&63&&ky(et,384),Buffer.from(al(et,"utf8"),"hex");let e=ul(32);return cl(et,e.toString("hex"),{mode:384}),e}function jo(e){let t=pl(),n=ul(Oy),r=_y(ll,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 zo(e){let t=pl(),[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=Iy(ll,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function pt(){if(Pt(),!$o(lt))return{version:1,credentials:{}};try{let e=al(lt,"utf8"),t=zo(e),n=JSON.parse(t),r=il.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function ks(e){Pt();let t=jo(JSON.stringify(e,null,2));cl(lt,t,{mode:384})}function dl(){try{$o(lt)&&sl(lt),$o(et)&&sl(et)}catch{}}import{refreshToken as Fy}from"@octokit/oauth-methods";import{request as vy}from"@octokit/request";var dn="178c6fc778ccc68e1d6a",wt="github.com";function Dy(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 My(e){return e==="github.com"||e===wt?"https://api.github.com":`https://${e}/api/v3`}async function _s(e,t=wt,n=dn){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(ir(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Fy({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:vy.defaults({baseUrl:My(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?Dy(o.message):"Token refresh failed"}}}async function ml(e,t=wt,n=dn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!ut(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await _s(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 Hy}from"@octocodeai/config";import{execFile as Ny}from"child_process";var Gy=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Wo(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=Gy.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;Ny("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Vo=null;function fl(e){Vo=e}function Is(){Vo=null}function By(){if(!Vo)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Vo}async function Tt(e){let t=e?.hostname??wt,n=e?.clientId??dn,r=e?.getGhCliToken??Wo,o=Hy();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await By().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch(s){process.stderr.write(`[octocode] gh auth token failed: ${s instanceof Error?s.message:String(s)}
|
|
10
|
-
`)}return null}async function Os(e=wt){let t=await Tt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Fs(e=wt,t=dn){let n=await Tt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}async function vs(e){let t=Ze(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=pt();return r.credentials[t]=n,ks(r),ar(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Wt(e="github.com",t){let n=Ze(e);if(!t?.bypassCache){let i=tl(n);if(i!==void 0)return i}let o=pt().credentials[n]||null;return nl(n,o),o}function Ko(e="github.com"){let t=Ze(e);return pt().credentials[t]||null}async function hl(e="github.com"){let t=Ze(e),n=!1,r=pt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?dl():ks(r),n=!0),ar(t),{success:n,deletedFromFile:n}}async function gl(){let e=pt();return Object.keys(e.credentials)}function yl(){let e=pt();return Object.keys(e.credentials)}async function Rl(e="github.com"){return await Wt(e)!==null}function Sl(e="github.com"){return Ko(e)!==null}async function Yo(e,t){let n=await Wt(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await vs(n),!0):!1}function bl(){return lt}async function Cl(e="github.com"){let t=await Wt(e);return!t||!t.token||ut(t)?null:t.token.token}function xl(e="github.com"){let t=Ko(e);return!t||!t.token||ut(t)?null:t.token.token}async function Pl(e,t){return _s({getCredentials:Wt,updateToken:Yo},e,t)}async function Ds(e,t){return ml({getCredentials:Wt,updateToken:Yo},e,t)}fl({getTokenWithRefresh:Ds});import fn from"node:os";import wl from"node:path";var cr=fn.platform()==="win32",Ms=fn.platform()==="darwin",Ns=fn.platform()==="linux",mn=fn.homedir();function Tl(){return cr?process.env.APPDATA||wl.join(mn,"AppData","Roaming"):mn}function El(){return cr?process.env.LOCALAPPDATA||wl.join(mn,"AppData","Local"):mn}function Ll(){return Ms?"macOS":cr?"Windows":Ns?"Linux":fn.platform()}function Al(){return fn.arch()}import{randomUUID as Zy}from"node:crypto";import{existsSync as Gs,readFileSync as Fl,writeFileSync as zy,unlinkSync as Wy,renameSync as Vy}from"node:fs";import{isStatsEnabled as vl}from"@octocodeai/config";import{z as W}from"zod";var Uy=W.object({rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),calls:W.number()}),Qy=W.object({hits:W.record(W.string(),W.number()).default({}),rateLimits:W.number().default(0)}),Xo=W.record(W.string(),W.number()).default({}),$y=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Xo,rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),charSavingsCalls:W.number(),githubCacheHits:W.number(),githubCacheRateLimits:W.number(),packageRegistryFailures:W.number().default(0),packageRegistryFailuresByRegistry:Xo}),qo=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Xo,charsSavedByTool:W.record(W.string(),Uy).default({}),githubCacheHits:Qy.default({hits:{},rateLimits:0}),packageRegistryFailures:Xo,totalUsage:$y.optional()}),kl=W.object({version:W.literal(1),sessionId:W.string(),createdAt:W.string(),lastActiveAt:W.string(),stats:qo.optional()}),_l=W.object({version:W.literal(1),stats:qo});function Il(e){return Object.values(e).reduce((t,n)=>t+n,0)}function jy(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:Il(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Il(o),packageRegistryFailuresByRegistry:o}}function Et(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:jy(t)}}function Lt(){return Et({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Vt=we.session,Kt=we.stats;function Ol(e,t){let n=`${e}.tmp`;zy(n,JSON.stringify(t,null,2),{mode:384}),Vy(n,e)}function Ky(e){let t=JSON.parse(e),n=_l.safeParse(t);if(n.success)return Et(n.data.stats);let r=qo.safeParse(t);return r.success?Et(r.data):null}function Yy(){if(!Gs(Kt))return Lt();try{let e=Fl(Kt,"utf8");return Ky(e)??Lt()}catch{return Lt()}}function Jo(e){Pt(),vl()&&Ol(Kt,{version:e.version,stats:Et(e.stats)});let{stats:t,...n}=e;Ol(Vt,n)}function Dl(){if(!Gs(Vt))return null;try{let e=Fl(Vt,"utf8"),t=JSON.parse(e),n=kl.safeParse(t);return n.success?{...n.data,stats:vl()?Yy():Lt()}:null}catch{return null}}function Ml(){let e=!1;for(let t of[Vt,Kt])if(Gs(t))try{Wy(t),e=!0}catch{return!1}return e}var Xy=6e4,ze=null,At=!1,hn=null,Hs=!1,ur=null,lr=null,pr=null,Zo=!1;function qy(){Hs||(Hs=!0,ur=()=>{dr()},lr=()=>{dr()},pr=()=>{dr()},process.on("exit",ur),process.on("SIGINT",lr),process.on("SIGTERM",pr))}function Bs(){ur&&(process.removeListener("exit",ur),ur=null),lr&&(process.removeListener("SIGINT",lr),lr=null),pr&&(process.removeListener("SIGTERM",pr),pr=null),Hs=!1}function Jy(){hn||(hn=setInterval(()=>{At&&ze&&(Jo(ze),At=!1)},Xy),hn.unref())}function Us(){hn&&(clearInterval(hn),hn=null)}function mr(){if(ze)return ze;let e=Dl();return e&&(ze=e),e}function gn(e){ze=e,At=!0,qy(),Jy()}function fr(){At&&ze&&(Jo(ze),At=!1)}function dr(){if(!Zo&&At&&ze){Zo=!0;try{Jo(ze),At=!1}catch{}finally{Zo=!1}}}function Qs(){ze=null,At=!1,Zo=!1}function Nl(){Qs(),Us(),Bs()}var eR=1;function tR(e){return Et(e)}function nR(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 Gl(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 rR(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 Hl(){let e=new Date().toISOString();return{version:eR,sessionId:Zy(),createdAt:e,lastActiveAt:e,stats:Lt()}}function Bl(){fr()}function Ul(){dr()}function Ql(e){if(e?.forceNew){let r=Hl();return gn(r),fr(),r}let t=mr();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return gn(r),fr(),r}let n=Hl();return gn(n),fr(),n}function $l(){return mr()?.sessionId??null}function Ge(e){let t=mr();if(!t)return{success:!1,session:null};let n=tR(t.stats),r=Et({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Gl(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:nR(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:rR(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Gl(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return gn(o),{success:!0,session:o}}function jl(e=1){return Ge({toolCalls:e})}function zl(e=1){return Ge({errors:e})}function ei(e=1){return Ge({rateLimits:e})}function Wl(e,t=1){return Ge({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function ti(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Ge({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function ni(e,t=1){return Ge({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ri(e=1){return Ge({githubCacheHits:{hits:{},rateLimits:e}})}function Vl(e,t=1){return Ge({packageRegistryFailures:{[e]:t}})}function Kl(){let e=mr();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Lt()};return gn(t),{success:!0,session:t}}function Yl(){return Qs(),Us(),Bs(),Ml()}function Xl(){Nl()}import{z as de}from"zod";var ql=de.looseObject({$schema:de.string().optional(),version:de.number().int().optional(),github:de.record(de.string(),de.unknown()).optional(),local:de.record(de.string(),de.unknown()).optional(),tools:de.record(de.string(),de.unknown()).optional(),network:de.record(de.string(),de.unknown()).optional(),lsp:de.record(de.string(),de.unknown()).optional(),output:de.record(de.string(),de.unknown()).optional()});import{existsSync as oR,readdirSync as iR,lstatSync as sR}from"node:fs";import{join as aR}from"node:path";function hr(e){if(!oR(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=iR(r)}catch{continue}for(let i of o){let s=aR(r,i);try{let a=sR(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function cR(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}import{getConfigSync as Jl,invalidateConfigCache as lR}from"@octocodeai/config";var Yt="18.1.0";import{maskSensitiveData as pR}from"@octocodeai/octocode-engine/mask";var kt=null,yn=null,$s=Tt;function zk(e){e.resolveTokenFull&&($s=e.resolveTokenFull)}function Wk(){$s=Tt}var dR=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function js(){try{let e=await $s({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:dR.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Zl(){if(kt!==null)return;if(yn!==null)return yn;let e=(async()=>{let t=Jl(),n=await js();kt={version:Yt,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}})();yn=e;try{await e}catch(t){throw yn===e&&(kt=null,yn=null),t}}function Vk(){kt=null,yn=null,lR()}function gr(){if(!kt){let e=pR(Ts.NOT_INITIALIZED.message);throw new Error(e)}return kt}async function zs(){return(await js()).token}function Kk(){return gr().enableLocal}function ep(){let e=gr();return e.enableLocal&&e.enableClone}async function Yk(){return kt!==null?kt.tokenSource:(await js()).source}function Ws(){return"github"}function Vs(){let e=Jl().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}function _t(e){(e.provider?Ge({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):ei(1)).session&&e.provider==="github"&&ri(1)}function tp(e){Ge({packageRegistryFailures:{[e]:1}})}function sp(e){return hR("sha256").update(e).digest("hex").substring(0,16)}async function fe(e){let t=e?.token??await zs(),n=t?sp(t):"anon",r=gr().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 gR=mR.plugin(fR),yR=300*1e3,Ks=50,RR=60*1e3;function ap(e){return Date.now()-e.createdAt>yR}var tt=new Map,It=null;function cp(){for(let[e,t]of tt.entries())ap(t)&&tt.delete(e);if(tt.size>Ks){let e=tt.size-Ks,t=0;for(let[n]of tt){if(t>=e)break;tt.delete(n),t++}}}function SR(){It||(It=setInterval(cp,RR),typeof It=="object"&&"unref"in It&&It.unref())}var np=3,rp=60;function op(e,t,n){_t({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var bR=()=>({onRateLimit:(e,t,n,r)=>(op("primary",e,t),r<np&&e<rp),onSecondaryRateLimit:(e,t,n,r)=>(op("secondary",e,t),r<np&&e<rp)});function CR(e){let t=gr(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Yt}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:bR(),log:r,...e&&{auth:e}};return new gR(o)}async function Q(e){SR();let t=e?.token??await zs(),n=t?sp(t):"ANONYMOUS",r=tt.get(n);if(r&&!ap(r))return r.client;tt.size>=Ks&&cp();let o=CR(t??void 0);return tt.set(n,{client:o,createdAt:Date.now()}),o}var xR=200,Rn=new Map;async function Ae(e,t,n){let r=`${e}/${t}`,o=Rn.get(r);if(o)return o;let i=await Q(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return ip(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}),ip(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 ip(e,t){if(Rn.size>=xR){let n=Rn.keys().next().value;n!==void 0&&Rn.delete(n)}Rn.set(e,t)}function s_(){tt.clear(),Rn.clear(),It&&(clearInterval(It),It=null)}import{ContentSanitizer as XR}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as PR}from"node:module";var wR=PR(import.meta.url),up="@octocodeai/octocode-engine",TR=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??wR(up),oi,ER=TR,Ys=class extends Error{constructor(n){super(`Failed to load native dependency ${up}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function J(){if(oi)return oi;try{return oi=ER(),oi}catch(e){throw new Ys(e)}}var O={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{RequestError as pp}from"octokit";var z={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"},ye={[z.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."},[z.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."},[z.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},[z.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)."},[z.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."},[z.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."},[z.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."},[z.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."},[z.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."},[z.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},lp={401:z.AUTH_REQUIRED,403:z.FORBIDDEN_PERMISSIONS,404:z.NOT_FOUND,422:z.INVALID_REQUEST,502:z.SERVER_UNAVAILABLE,503:z.SERVER_UNAVAILABLE,504:z.SERVER_UNAVAILABLE},Xs={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},qs={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ii={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var LR=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function nt(e){if(!(e instanceof pp)||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 LR.some(o=>r.includes(o))})}function V(e){return e instanceof pp?AR(e):e instanceof Error?MR(e):{error:typeof e=="string"?e:ye[z.UNKNOWN].message,type:"unknown"}}function AR(e){let{status:t,message:n,response:r}=e;if(t===403)return _R(n,r);if(t===429)return kR(n,r);let o=lp[t];return o?DR(o,t):Sn(z.UNKNOWN,{error:n||ye[z.UNKNOWN].message,status:t})}function Js(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function kR(e,t){let n=t?.headers,r=Js(n,"retry-after"),o=Js(n,"x-ratelimit-reset"),i=Js(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ii.RESET_BUFFER_SECONDS,0):void 0);return _t({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:e||ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function _R(e,t){let n=t?.headers;if(qs.SECONDARY.test(e))return IR(n);let r=n?.["x-ratelimit-remaining"],o=vR(t);return r!==void 0&&String(r)==="0"||o?OR(n):FR(n)}function IR(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ii.SECONDARY_FALLBACK_SECONDS:t;return _t({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Sn(z.RATE_LIMIT_SECONDARY,{error:ye[z.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ye[z.RATE_LIMIT_SECONDARY].suggestion})}function OR(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)+ii.RESET_BUFFER_SECONDS,0):void 0,i=r?ye[z.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime;return _t({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function FR(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ye[z.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=NR(String(t),String(n))),Sn(z.FORBIDDEN_PERMISSIONS,{error:ye[z.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function vR(e){return e?.data?.errors?.some(n=>n.type===qs.GRAPHQL_TYPE)??!1}function DR(e,t){let n=ye[e];return Sn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function MR(e){return Xs.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ye[z.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ye[z.NETWORK_CONNECTION_FAILED].suggestion}:Xs.TIMEOUT.some(t=>e.message.includes(t))?{error:ye[z.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ye[z.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Sn(e,t){return{type:"http",...t}}function NR(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?ye[z.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ye[z.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function dp(e){return`user:${e}`}var GR=/[@/]/,HR=/^[A-Za-z0-9_-]+$/;function Zs(e){return e.startsWith('"')||HR.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var dt=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(dp(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=GR.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 BR=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ea=class extends dt{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(Zs))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(BR):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}},ta=class extends dt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Zs)),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 na(e){return new ea().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ra(e){return new ta().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var oa=class extends dt{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 ia(e){return new oa().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function sa(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 aa=class extends dt{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 ca(e){return new aa().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function ua(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 UR from"crypto";var QR="v2",$R=new Set([]);function jR(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($R.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function ce(e,t,n){let r=la(jR(t)),o=n?`${n}:${r}`:r,i=UR.createHash("sha256").update(o).digest("hex");return`${QR}-${e}:${i}`}function la(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=>la(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${la(i,t)}`}).join(",")}}`)}import zR from"node-cache";var WR=300*1e3,Te=new zR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ue={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},mp={"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},He=new Map;function VR(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function KR(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function yr(e){let t=VR(e);if(!(!t||!KR(t)))try{ni(t,1)}catch{}}function si(){let e=Date.now();for(let[t,n]of He.entries())e-n.startedAt>WR&&He.delete(t)}function Rr(e){return mp[e]||mp.default}function Sr(e,t,n){try{return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{try{let r=Te.keys();for(let o of r)Te.get(o);return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{return!1}}}async function he(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}si();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Rr(u)}Sr(e,i,a)}return i}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}import YR from"node-cache";var br=new YR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function ai(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}si();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:br.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ue.hits++,yr(e);let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}return Sr(e,i.data,c),i.data}if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}Sr(e,s.value,c),br.set(e,{data:s.value,etag:s.etag})}return s.value}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}function H_(){Te.flushAll(),br.flushAll(),He.clear(),ue.hits=0,ue.misses=0,ue.sets=0,ue.totalKeys=0,ue.lastReset=new Date}function Ot(e){let t=Te.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Te.del(r)>0&&n++}return n>0&&(ue.totalKeys=Te.keys().length),n}function B_(){return Ot("local-")}function U_(){return Ot("lsp-")}function Q_(){let e=0;return e+=Ot("gh-api-"),e+=Ot("bb-api-"),e+=Ot("gh-repo-"),e+=Ot("bb-repo-"),e+=Ot("github-user"),e+=Ot("npm-search"),br.flushAll(),e}function $_(){let e=ue.hits+ue.misses;return{...ue,hitRate:e>0?ue.hits/e*100:0,cacheSize:Te.keys().length}}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as J_,DISCOVERY_IGNORED_FILE_NAMES as Z_,DISCOVERY_IGNORED_FOLDER_NAMES as eI,getDiscoveryExtension as fp,shouldIgnoreDiscoveryDir as Cr,shouldIgnoreDiscoveryFile as bn}from"@octocodeai/octocode-engine/security";var hp=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 gp(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?gp(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,hp,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ne(e){if(!(typeof e!="object"||e===null))return gp(e[hp])}function Cn(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 yp(e){let t=Cn(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 xn(e){let t=Cn(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 Rp(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 Sp=30;async function bp(e,t,n){let r=await fe(t),o=ce("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await he(o,async()=>await qR(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function qR(e,t){try{let n=await Q(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(h=>h&&h.trim()).length===0)return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let r=na(e);if(!r.trim())return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Sp,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 JR(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,p=Math.min(l,1e3),m=Math.min(Math.ceil(p/o),10),d=Math.min(i,Math.max(1,m)),f=d<m,g=Math.min(p,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:d,totalPages:m,perPage:o,totalMatches:p,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>p,hasMore:f,...f?{nextPage:d+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Cn(a.headers),rawResponseChars:N(a.data)}}catch(n){if(nt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Sp,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 V(n)}}async function JR(e,t){let n=ZR(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(d=>!bn(d.path)),c=0,u=0,l=await Promise.allSettled(a.map(async d=>{s.add(d.path);let f=[],g=await Promise.allSettled((d.text_matches||[]).map(async C=>{let P=C.fragment,T=XR.sanitizeContent(P||"",d.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${d.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${d.path}: ${k}`));try{let k=await O.minifyContent(P||"",d.path);P=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:P||"",positions:Rp(C.fragment||"",L,P||"")}})),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=d,S=Array.from(new Set(f));return{path:d.path,matches:R,url:d.html_url,repository:{nameWithOwner:d.repository.full_name,url:d.repository.url,pushedAt:d.repository.pushed_at||void 0},...y.last_modified_at&&{lastModifiedAt:y.last_modified_at},...S.length>0&&{minificationType:S.join(",")}}})),p=l.filter(d=>d.status==="fulfilled").map(d=>d.value);c=l.filter(d=>d.status==="rejected").length;let m={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let d=n.full_name.split("/");return d.length===2&&d[0]&&d[1]?{owner:d[0],repo:d[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 ZR(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{readdirSync as eS,statSync as Cp}from"node:fs";import{join as tS}from"node:path";var xr=50,ci=5*1024*1024,pa=300*1024,xp=5,nS=1e4,Pp=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"]),da={maxDirectoryFiles:xr,maxTotalSize:ci,maxFileSize:pa};function ma(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function wp(e){return Object.values(e).every(t=>t===0)}function fa(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 Tp(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 oS(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var rS=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function oS(e,t){try{let o=new URL(e);if(!rS.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(),nS);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 Ep(e,t){let n=[],r=0;function o(i){let s;try{s=eS(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=tS(i,a);try{let u=Cp(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 Lp(e){try{return Cp(e).size}catch{return 0}}import{writeFileSync as wS,mkdirSync as Dp,existsSync as ya,rmSync as TS}from"node:fs";import{join as Mp,dirname as ES,resolve as Np,sep as Gp}from"node:path";import{existsSync as Lr,readFileSync as aS,writeFileSync as cS,mkdirSync as uS,rmSync as Er,readdirSync as lS,statSync as pS}from"node:fs";import{join as Ft}from"node:path";import{join as ui}from"node:path";import{createHash as Ap}from"node:crypto";function iS(e){return Pr(e)}function Pr(e){return ui(e,"tmp","clone")}function li(e){return ui(e,"tmp","tree")}function sS(e){return e?`__sp_${Ap("sha256").update(e).digest("hex").substring(0,6)}`:""}function kp(e){if(!/[\\/]/.test(e))return e;let t=Ap("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function ha(e,t,n,r,o){let i=`${kp(r)}${sS(o)}`;return ui(Pr(e),t,n,i)}function wr(e,t,n,r){return ui(li(e),t,n,kp(r))}var dS=1440*60*1e3,mS=600*1e3,fS=2*1024*1024*1024,hS=50,Ip=".octocode-clone-meta.json",Pn=null;function gS(e){return typeof e=="object"&&e!==null}function yS(e){if(!gS(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 ga(e){let t=Ft(e,Ip);if(!Lr(t))return null;try{return yS(JSON.parse(aS(t,"utf-8")))}catch{return null}}function Tn(e,t){try{cS(Ft(e,Ip),JSON.stringify(t,null,2),"utf-8")}catch{}}function Op(e){return Date.now()<new Date(e.expiresAt).getTime()}function En(e){let t=ga(e);return t?Op(t)?Lr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function RS(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return dS}function SS(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return fS}function bS(){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 hS}function Ln(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+RS()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function vt(e){let t=Ft(e,"..");try{Lr(t)||uS(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 di(e){try{Lr(e)&&Er(e,{recursive:!0,force:!0})}catch{}}function Tr(e){try{return pS(e).isDirectory()}catch{return!1}}function Xt(e){try{return lS(e)}catch{return[]}}function*Fp(e){for(let t of Xt(e)){let n=Ft(e,t);if(Tr(n))for(let r of Xt(n)){let o=Ft(n,r);if(Tr(o))for(let i of Xt(o)){let s=Ft(o,i);Tr(s)&&(yield s)}}}}function _p(e){for(let t of[...Xt(e)]){let n=Ft(e,t);if(Tr(n)){for(let r of[...Xt(n)]){let o=Ft(n,r);if(Tr(o)&&Xt(o).length===0)try{Er(o,{recursive:!0,force:!0})}catch{}}if(Xt(n).length===0)try{Er(n,{recursive:!0,force:!0})}catch{}}}}function CS(e){let t=0;for(let n of Fp(e))try{let r=ga(n);(!r||!Op(r))&&(Er(n,{recursive:!0,force:!0}),t++)}catch{}return t}function xS(e){let t=[];for(let n of Fp(e)){let r=ga(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??hr(n)})}return t}function PS(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{Er(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function vp(e){if(!Lr(e))return 0;let t=0;try{t+=CS(e)}catch{return t}_p(e);let n=PS(xS(e),SS(),bS());return t+=n,n>0&&_p(e),t}function pi(e){return vp(Pr(e))}function wn(e){return vp(li(e))}function LI(e){Pn||(pi(e),wn(e),Pn=setInterval(()=>{pi(e),wn(e)},mS),Pn.unref())}function AI(){Pn&&(clearInterval(Pn),Pn=null)}async function Ra(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=Np(Mp(a,n));if(!c.startsWith(a+Gp)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(u.hit&&!i&&ya(c)){let b=Ep(c,a),A=ma();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:da,warnings:fa(!0,!1),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await Q(o),p;try{p=(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 d=m,f=ma(),g=[];for(let b of d){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=fp(b.name,{lowercase:!0,leadingDot:!0});if(Pp.has(A)){f.binary+=1;continue}g.push(b)}f.fileLimit=Math.max(0,g.length-xr);let R=g.slice(0,xr),h=o?.token,y=await Tp(R,xp,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>ci){f.totalSizeLimit=y.length-b;break}S+=M.length,C.push({entry:A,content:M})}wn(s),vt(a),ya(c)&&TS(c,{recursive:!0,force:!0}),Dp(c,{recursive:!0,mode:448});let P=[];for(let{entry:b,content:A}of C){let M=Np(Mp(a,b.path));if(!M.startsWith(a+Gp)){f.pathTraversal+=1;continue}let B=ES(M);ya(B)||Dp(B,{recursive:!0,mode:448}),wS(M,A,"utf-8"),P.push({path:b.path,size:A.length,type:"file"})}let T=Ln(e,t,r,"treeFetch",void 0,void 0,p);Tn(a,T);let L=wp(f),k=L,w=f.nonFile>0;return{localPath:c,repoRoot:a,files:P,fileCount:P.length,totalSize:S,complete:L,verified:k,...p?{commitSha:p}:{},...w?{hasSubdirectories:!0}:{},directoryEntryCount:d.length,eligibleFileCount:g.length,savedFileCount:P.length,skipped:f,limits:da,warnings:fa(L,k),cached:!1,expiresAt:T.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}import{writeFileSync as vS,mkdirSync as DS,existsSync as Up}from"node:fs";import{join as MS,dirname as NS,resolve as GS,sep as HS}from"node:path";import{RequestError as Ta}from"octokit";import{completeMetadata as Sa}from"@octocodeai/octocode-core";var x=new Proxy({},{get(e,t){return Sa.toolNames[t]},ownKeys(){return Object.keys(Sa.toolNames)},getOwnPropertyDescriptor(e,t){let n=Sa.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as LS}from"@octocodeai/octocode-core";var ba=new Proxy({},{get(e,t){return LS.tools[t]?.description??""}});import{completeMetadata as AS}from"@octocodeai/octocode-core";function Ca(e){return Object.prototype.hasOwnProperty.call(AS.tools,e)}import{completeMetadata as kS}from"@octocodeai/octocode-core";function xa(){return kS.baseSchema}var _S=new Proxy({},{get(e,t){return xa()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(xa())]))},getOwnPropertyDescriptor(e,t){let n=xa();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});function Pa(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 wa(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(d=>d.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(d=>d.name===s?!1:!!d.name.startsWith(p+".")).forEach(d=>u.push(d.path)),u.length===0&&p.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==p&&g.length>=3&&(p.startsWith(g)||g.startsWith(p))}).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 Ae(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=V(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await wa(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Pa(i,m)]),{...l,...p&&{scopesSuggestion:p}}}async function OS(e,t,n,r,o,i){let s=V(t),a=await wa(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Pa(o,a)]),s}async function Hp(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:Ct.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:Ct.DECODE_FAILED.message,type:"unknown",status:422}}}async function Bp(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"?Hp(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return V(i)}}async function FS(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 Ae(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 p=await Bp(e,t,n,l.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return V(s)}}async function Ar(e,t,n={}){try{let r=await Q(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(d){if(d instanceof Ta&&d.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(d instanceof Ta&&d.status===404)if(a){let f=await IS(r,d,c,o,i,s,a,t);if("result"in f)u=f.result,l=f.actualBranch;else return f}else return await OS(r,d,o,i,s,a);else{if(d instanceof Ta&&d.status===413)return await FS(r,o,i,s,a||l,t);throw d}}let p=u.data,m=xn(u.headers);if(Array.isArray(p))return{error:Ct.PATH_IS_DIRECTORY.message(x.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let d=typeof p.content=="string"?p.content:"",f=p.size??0,g;if(d.length>0)g=await Hp(d,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)g=await Bp(r,o,i,p.sha,s);else return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!l&&!a)try{l=await Ae(o,i,t)}catch{}return{data:{rawContent:g.data,branch:l||void 0,resolvedRef:l||a||"HEAD"},status:200,rawResponseChars:N(p),...m?{etag:m}:{}}}return{error:Ct.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return V(r)}}async function Ea(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=GS(MS(a,n));if(!c.startsWith(a+HS)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(!i&&u.hit&&Up(c))return{localPath:c,repoRoot:a,path:n,size:Lp(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await Ar({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}`)}wn(s),vt(a);let p=NS(c);Up(p)||DS(p,{recursive:!0,mode:448}),vS(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,d=Ln(e,t,m,"treeFetch");return Tn(a,d),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:d.expiresAt,owner:e,repo:t,branch:m}}import{ContentSanitizer as Ia}from"@octocodeai/octocode-engine/contentSanitizer";function kr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function rt(e){return kr(e).length}function mi(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
|
+
`)}return null}async function Os(e=wt){let t=await Tt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Fs(e=wt,t=dn){let n=await Tt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}async function vs(e){let t=Ze(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=pt();return r.credentials[t]=n,ks(r),ar(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Wt(e="github.com",t){let n=Ze(e);if(!t?.bypassCache){let i=tl(n);if(i!==void 0)return i}let o=pt().credentials[n]||null;return nl(n,o),o}function Ko(e="github.com"){let t=Ze(e);return pt().credentials[t]||null}async function hl(e="github.com"){let t=Ze(e),n=!1,r=pt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?dl():ks(r),n=!0),ar(t),{success:n,deletedFromFile:n}}async function gl(){let e=pt();return Object.keys(e.credentials)}function yl(){let e=pt();return Object.keys(e.credentials)}async function Rl(e="github.com"){return await Wt(e)!==null}function Sl(e="github.com"){return Ko(e)!==null}async function Yo(e,t){let n=await Wt(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await vs(n),!0):!1}function bl(){return lt}async function Cl(e="github.com"){let t=await Wt(e);return!t||!t.token||ut(t)?null:t.token.token}function xl(e="github.com"){let t=Ko(e);return!t||!t.token||ut(t)?null:t.token.token}async function Pl(e,t){return _s({getCredentials:Wt,updateToken:Yo},e,t)}async function Ds(e,t){return ml({getCredentials:Wt,updateToken:Yo},e,t)}fl({getTokenWithRefresh:Ds});import fn from"node:os";import wl from"node:path";var cr=fn.platform()==="win32",Ms=fn.platform()==="darwin",Ns=fn.platform()==="linux",mn=fn.homedir();function Tl(){return cr?process.env.APPDATA||wl.join(mn,"AppData","Roaming"):mn}function El(){return cr?process.env.LOCALAPPDATA||wl.join(mn,"AppData","Local"):mn}function Ll(){return Ms?"macOS":cr?"Windows":Ns?"Linux":fn.platform()}function Al(){return fn.arch()}import{randomUUID as Zy}from"node:crypto";import{existsSync as Gs,readFileSync as Fl,writeFileSync as zy,unlinkSync as Wy,renameSync as Vy}from"node:fs";import{isStatsEnabled as vl}from"@octocodeai/config";import{z as W}from"zod";var Uy=W.object({rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),calls:W.number()}),Qy=W.object({hits:W.record(W.string(),W.number()).default({}),rateLimits:W.number().default(0)}),Xo=W.record(W.string(),W.number()).default({}),$y=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Xo,rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),charSavingsCalls:W.number(),githubCacheHits:W.number(),githubCacheRateLimits:W.number(),packageRegistryFailures:W.number().default(0),packageRegistryFailuresByRegistry:Xo}),qo=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Xo,charsSavedByTool:W.record(W.string(),Uy).default({}),githubCacheHits:Qy.default({hits:{},rateLimits:0}),packageRegistryFailures:Xo,totalUsage:$y.optional()}),kl=W.object({version:W.literal(1),sessionId:W.string(),createdAt:W.string(),lastActiveAt:W.string(),stats:qo.optional()}),_l=W.object({version:W.literal(1),stats:qo});function Il(e){return Object.values(e).reduce((t,n)=>t+n,0)}function jy(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:Il(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Il(o),packageRegistryFailuresByRegistry:o}}function Et(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:jy(t)}}function Lt(){return Et({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Vt=we.session,Kt=we.stats;function Ol(e,t){let n=`${e}.tmp`;zy(n,JSON.stringify(t,null,2),{mode:384}),Vy(n,e)}function Ky(e){let t=JSON.parse(e),n=_l.safeParse(t);if(n.success)return Et(n.data.stats);let r=qo.safeParse(t);return r.success?Et(r.data):null}function Yy(){if(!Gs(Kt))return Lt();try{let e=Fl(Kt,"utf8");return Ky(e)??Lt()}catch{return Lt()}}function Jo(e){Pt(),vl()&&Ol(Kt,{version:e.version,stats:Et(e.stats)});let{stats:t,...n}=e;Ol(Vt,n)}function Dl(){if(!Gs(Vt))return null;try{let e=Fl(Vt,"utf8"),t=JSON.parse(e),n=kl.safeParse(t);return n.success?{...n.data,stats:vl()?Yy():Lt()}:null}catch{return null}}function Ml(){let e=!1;for(let t of[Vt,Kt])if(Gs(t))try{Wy(t),e=!0}catch{return!1}return e}var Xy=6e4,ze=null,At=!1,hn=null,Hs=!1,ur=null,lr=null,pr=null,Zo=!1;function qy(){Hs||(Hs=!0,ur=()=>{dr()},lr=()=>{dr()},pr=()=>{dr()},process.on("exit",ur),process.on("SIGINT",lr),process.on("SIGTERM",pr))}function Bs(){ur&&(process.removeListener("exit",ur),ur=null),lr&&(process.removeListener("SIGINT",lr),lr=null),pr&&(process.removeListener("SIGTERM",pr),pr=null),Hs=!1}function Jy(){hn||(hn=setInterval(()=>{At&&ze&&(Jo(ze),At=!1)},Xy),hn.unref())}function Us(){hn&&(clearInterval(hn),hn=null)}function mr(){if(ze)return ze;let e=Dl();return e&&(ze=e),e}function gn(e){ze=e,At=!0,qy(),Jy()}function fr(){At&&ze&&(Jo(ze),At=!1)}function dr(){if(!Zo&&At&&ze){Zo=!0;try{Jo(ze),At=!1}catch{}finally{Zo=!1}}}function Qs(){ze=null,At=!1,Zo=!1}function Nl(){Qs(),Us(),Bs()}var eR=1;function tR(e){return Et(e)}function nR(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 Gl(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 rR(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 Hl(){let e=new Date().toISOString();return{version:eR,sessionId:Zy(),createdAt:e,lastActiveAt:e,stats:Lt()}}function Bl(){fr()}function Ul(){dr()}function Ql(e){if(e?.forceNew){let r=Hl();return gn(r),fr(),r}let t=mr();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return gn(r),fr(),r}let n=Hl();return gn(n),fr(),n}function $l(){return mr()?.sessionId??null}function Ge(e){let t=mr();if(!t)return{success:!1,session:null};let n=tR(t.stats),r=Et({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Gl(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:nR(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:rR(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Gl(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return gn(o),{success:!0,session:o}}function jl(e=1){return Ge({toolCalls:e})}function zl(e=1){return Ge({errors:e})}function ei(e=1){return Ge({rateLimits:e})}function Wl(e,t=1){return Ge({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function ti(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Ge({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function ni(e,t=1){return Ge({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ri(e=1){return Ge({githubCacheHits:{hits:{},rateLimits:e}})}function Vl(e,t=1){return Ge({packageRegistryFailures:{[e]:t}})}function Kl(){let e=mr();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Lt()};return gn(t),{success:!0,session:t}}function Yl(){return Qs(),Us(),Bs(),Ml()}function Xl(){Nl()}import{z as de}from"zod";var ql=de.looseObject({$schema:de.string().optional(),version:de.number().int().optional(),github:de.record(de.string(),de.unknown()).optional(),local:de.record(de.string(),de.unknown()).optional(),tools:de.record(de.string(),de.unknown()).optional(),network:de.record(de.string(),de.unknown()).optional(),lsp:de.record(de.string(),de.unknown()).optional(),output:de.record(de.string(),de.unknown()).optional()});import{existsSync as oR,readdirSync as iR,lstatSync as sR}from"node:fs";import{join as aR}from"node:path";function hr(e){if(!oR(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=iR(r)}catch{continue}for(let i of o){let s=aR(r,i);try{let a=sR(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function cR(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}import{getConfigSync as Jl,invalidateConfigCache as lR}from"@octocodeai/config";var Yt="18.1.2";import{maskSensitiveData as pR}from"@octocodeai/octocode-engine/mask";var kt=null,yn=null,$s=Tt;function zk(e){e.resolveTokenFull&&($s=e.resolveTokenFull)}function Wk(){$s=Tt}var dR=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"]);async function js(){try{let e=await $s({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:dR.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Zl(){if(kt!==null)return;if(yn!==null)return yn;let e=(async()=>{let t=Jl(),n=await js();kt={version:Yt,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}})();yn=e;try{await e}catch(t){throw yn===e&&(kt=null,yn=null),t}}function Vk(){kt=null,yn=null,lR()}function gr(){if(!kt){let e=pR(Ts.NOT_INITIALIZED.message);throw new Error(e)}return kt}async function zs(){return(await js()).token}function Kk(){return gr().enableLocal}function ep(){let e=gr();return e.enableLocal&&e.enableClone}async function Yk(){return kt!==null?kt.tokenSource:(await js()).source}function Ws(){return"github"}function Vs(){let e=Jl().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}function _t(e){(e.provider?Ge({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):ei(1)).session&&e.provider==="github"&&ri(1)}function tp(e){Ge({packageRegistryFailures:{[e]:1}})}function sp(e){return hR("sha256").update(e).digest("hex").substring(0,16)}async function fe(e){let t=e?.token??await zs(),n=t?sp(t):"anon",r=gr().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 gR=mR.plugin(fR),yR=300*1e3,Ks=50,RR=60*1e3;function ap(e){return Date.now()-e.createdAt>yR}var tt=new Map,It=null;function cp(){for(let[e,t]of tt.entries())ap(t)&&tt.delete(e);if(tt.size>Ks){let e=tt.size-Ks,t=0;for(let[n]of tt){if(t>=e)break;tt.delete(n),t++}}}function SR(){It||(It=setInterval(cp,RR),typeof It=="object"&&"unref"in It&&It.unref())}var np=3,rp=60;function op(e,t,n){_t({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var bR=()=>({onRateLimit:(e,t,n,r)=>(op("primary",e,t),r<np&&e<rp),onSecondaryRateLimit:(e,t,n,r)=>(op("secondary",e,t),r<np&&e<rp)});function CR(e){let t=gr(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${Yt}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:bR(),log:r,...e&&{auth:e}};return new gR(o)}async function Q(e){SR();let t=e?.token??await zs(),n=t?sp(t):"ANONYMOUS",r=tt.get(n);if(r&&!ap(r))return r.client;tt.size>=Ks&&cp();let o=CR(t??void 0);return tt.set(n,{client:o,createdAt:Date.now()}),o}var xR=200,Rn=new Map;async function Ae(e,t,n){let r=`${e}/${t}`,o=Rn.get(r);if(o)return o;let i=await Q(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return ip(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}),ip(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 ip(e,t){if(Rn.size>=xR){let n=Rn.keys().next().value;n!==void 0&&Rn.delete(n)}Rn.set(e,t)}function s_(){tt.clear(),Rn.clear(),It&&(clearInterval(It),It=null)}import{ContentSanitizer as XR}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as PR}from"node:module";var wR=PR(import.meta.url),up="@octocodeai/octocode-engine",TR=()=>globalThis.__OCTOCODE_ENGINE_BINDING__??wR(up),oi,ER=TR,Ys=class extends Error{constructor(n){super(`Failed to load native dependency ${up}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function J(){if(oi)return oi;try{return oi=ER(),oi}catch(e){throw new Ys(e)}}var O={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{RequestError as pp}from"octokit";var z={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"},ye={[z.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."},[z.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."},[z.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},[z.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)."},[z.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."},[z.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."},[z.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."},[z.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."},[z.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."},[z.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},lp={401:z.AUTH_REQUIRED,403:z.FORBIDDEN_PERMISSIONS,404:z.NOT_FOUND,422:z.INVALID_REQUEST,502:z.SERVER_UNAVAILABLE,503:z.SERVER_UNAVAILABLE,504:z.SERVER_UNAVAILABLE},Xs={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},qs={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},ii={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};var LR=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function nt(e){if(!(e instanceof pp)||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 LR.some(o=>r.includes(o))})}function V(e){return e instanceof pp?AR(e):e instanceof Error?MR(e):{error:typeof e=="string"?e:ye[z.UNKNOWN].message,type:"unknown"}}function AR(e){let{status:t,message:n,response:r}=e;if(t===403)return _R(n,r);if(t===429)return kR(n,r);let o=lp[t];return o?DR(o,t):Sn(z.UNKNOWN,{error:n||ye[z.UNKNOWN].message,status:t})}function Js(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function kR(e,t){let n=t?.headers,r=Js(n,"retry-after"),o=Js(n,"x-ratelimit-reset"),i=Js(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+ii.RESET_BUFFER_SECONDS,0):void 0);return _t({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:e||ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function _R(e,t){let n=t?.headers;if(qs.SECONDARY.test(e))return IR(n);let r=n?.["x-ratelimit-remaining"],o=vR(t);return r!==void 0&&String(r)==="0"||o?OR(n):FR(n)}function IR(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?ii.SECONDARY_FALLBACK_SECONDS:t;return _t({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Sn(z.RATE_LIMIT_SECONDARY,{error:ye[z.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ye[z.RATE_LIMIT_SECONDARY].suggestion})}function OR(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)+ii.RESET_BUFFER_SECONDS,0):void 0,i=r?ye[z.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ye[z.RATE_LIMIT_PRIMARY].messageWithoutTime;return _t({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Sn(z.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ye[z.RATE_LIMIT_PRIMARY].suggestion})}function FR(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ye[z.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=NR(String(t),String(n))),Sn(z.FORBIDDEN_PERMISSIONS,{error:ye[z.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function vR(e){return e?.data?.errors?.some(n=>n.type===qs.GRAPHQL_TYPE)??!1}function DR(e,t){let n=ye[e];return Sn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function MR(e){return Xs.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ye[z.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ye[z.NETWORK_CONNECTION_FAILED].suggestion}:Xs.TIMEOUT.some(t=>e.message.includes(t))?{error:ye[z.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ye[z.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Sn(e,t){return{type:"http",...t}}function NR(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?ye[z.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ye[z.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function dp(e){return`user:${e}`}var GR=/[@/]/,HR=/^[A-Za-z0-9_-]+$/;function Zs(e){return e.startsWith('"')||HR.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var dt=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(dp(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=GR.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 BR=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,ea=class extends dt{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(Zs))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(BR):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}},ta=class extends dt{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(Zs)),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 na(e){return new ea().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ra(e){return new ta().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}var oa=class extends dt{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 ia(e){return new oa().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function sa(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 aa=class extends dt{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 ca(e){return new aa().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addDateFilters(e).addEngagementFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function ua(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 UR from"crypto";var QR="v2",$R=new Set([]);function jR(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($R.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function ce(e,t,n){let r=la(jR(t)),o=n?`${n}:${r}`:r,i=UR.createHash("sha256").update(o).digest("hex");return`${QR}-${e}:${i}`}function la(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=>la(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${la(i,t)}`}).join(",")}}`)}import zR from"node-cache";var WR=300*1e3,Te=new zR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),ue={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},mp={"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},He=new Map;function VR(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function KR(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function yr(e){let t=VR(e);if(!(!t||!KR(t)))try{ni(t,1)}catch{}}function si(){let e=Date.now();for(let[t,n]of He.entries())e-n.startedAt>WR&&He.delete(t)}function Rr(e){return mp[e]||mp.default}function Sr(e,t,n){try{return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{try{let r=Te.keys();for(let o of r)Te.get(o);return Te.set(e,t,n),ue.sets++,ue.totalKeys=Te.keys().length,!0}catch{return!1}}}async function he(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}si();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Rr(u)}Sr(e,i,a)}return i}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}import YR from"node-cache";var br=new YR({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1});async function ai(e,t,n={}){if(n.skipCache)return(await t({})).value;if(!n.forceRefresh)try{let i=Te.get(e);if(i!==void 0)return ue.hits++,yr(e),i}catch{}si();let r=He.get(e);if(r)return r.promise;let o=(async()=>{try{let i=n.forceRefresh?void 0:br.get(e),s=await t({ifNoneMatch:!n.forceRefresh&&i?.etag?i.etag:void 0});if(s.notModified&&i){ue.hits++,yr(e);let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}return Sr(e,i.data,c),i.data}if(n.forceRefresh||ue.misses++,(n.shouldCache??(()=>!0))(s.value)){let c=n.ttl;if(!c){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";c=Rr(l)}Sr(e,s.value,c),br.set(e,{data:s.value,etag:s.etag})}return s.value}finally{He.delete(e)}})();return He.set(e,{promise:o,startedAt:Date.now()}),o}function H_(){Te.flushAll(),br.flushAll(),He.clear(),ue.hits=0,ue.misses=0,ue.sets=0,ue.totalKeys=0,ue.lastReset=new Date}function Ot(e){let t=Te.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Te.del(r)>0&&n++}return n>0&&(ue.totalKeys=Te.keys().length),n}function B_(){return Ot("local-")}function U_(){return Ot("lsp-")}function Q_(){let e=0;return e+=Ot("gh-api-"),e+=Ot("bb-api-"),e+=Ot("gh-repo-"),e+=Ot("bb-repo-"),e+=Ot("github-user"),e+=Ot("npm-search"),br.flushAll(),e}function $_(){let e=ue.hits+ue.misses;return{...ue,hitRate:e>0?ue.hits/e*100:0,cacheSize:Te.keys().length}}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as J_,DISCOVERY_IGNORED_FILE_NAMES as Z_,DISCOVERY_IGNORED_FOLDER_NAMES as eI,getDiscoveryExtension as fp,shouldIgnoreDiscoveryDir as Cr,shouldIgnoreDiscoveryFile as bn}from"@octocodeai/octocode-engine/security";var hp=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 gp(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?gp(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,hp,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ne(e){if(!(typeof e!="object"||e===null))return gp(e[hp])}function Cn(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 yp(e){let t=Cn(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 xn(e){let t=Cn(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 Rp(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 Sp=30;async function bp(e,t,n){let r=await fe(t),o=ce("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,auth:r},n);return await he(o,async()=>await qR(e,t),{shouldCache:s=>"data"in s&&!s.error})}async function qR(e,t){try{let n=await Q(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(h=>h&&h.trim()).length===0)return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let r=na(e);if(!r.trim())return{error:Ee.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Sp,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 JR(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,p=Math.min(l,1e3),m=Math.min(Math.ceil(p/o),10),d=Math.min(i,Math.max(1,m)),f=d<m,g=Math.min(p,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:d,totalPages:m,perPage:o,totalMatches:p,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>p,hasMore:f,...f?{nextPage:d+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Cn(a.headers),rawResponseChars:N(a.data)}}catch(n){if(nt(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Sp,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 V(n)}}async function JR(e,t){let n=ZR(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(d=>!bn(d.path)),c=0,u=0,l=await Promise.allSettled(a.map(async d=>{s.add(d.path);let f=[],g=await Promise.allSettled((d.text_matches||[]).map(async C=>{let P=C.fragment,T=XR.sanitizeContent(P||"",d.path);P=T.content,T.hasSecrets&&r.add(`Secrets detected in ${d.path}: ${T.secretsDetected.join(", ")}`),T.warnings.length>0&&T.warnings.forEach(k=>r.add(`${d.path}: ${k}`));try{let k=await O.minifyContent(P||"",d.path);P=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:P||"",positions:Rp(C.fragment||"",L,P||"")}})),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=d,S=Array.from(new Set(f));return{path:d.path,matches:R,url:d.html_url,repository:{nameWithOwner:d.repository.full_name,url:d.repository.url,pushedAt:d.repository.pushed_at||void 0},...y.last_modified_at&&{lastModifiedAt:y.last_modified_at},...S.length>0&&{minificationType:S.join(",")}}})),p=l.filter(d=>d.status==="fulfilled").map(d=>d.value);c=l.filter(d=>d.status==="rejected").length;let m={items:p,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let d=n.full_name.split("/");return d.length===2&&d[0]&&d[1]?{owner:d[0],repo:d[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 ZR(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{readdirSync as eS,statSync as Cp}from"node:fs";import{join as tS}from"node:path";var xr=50,ci=5*1024*1024,pa=300*1024,xp=5,nS=1e4,Pp=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"]),da={maxDirectoryFiles:xr,maxTotalSize:ci,maxFileSize:pa};function ma(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function wp(e){return Object.values(e).every(t=>t===0)}function fa(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 Tp(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 oS(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var rS=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function oS(e,t){try{let o=new URL(e);if(!rS.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(),nS);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 Ep(e,t){let n=[],r=0;function o(i){let s;try{s=eS(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=tS(i,a);try{let u=Cp(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 Lp(e){try{return Cp(e).size}catch{return 0}}import{writeFileSync as wS,mkdirSync as Dp,existsSync as ya,rmSync as TS}from"node:fs";import{join as Mp,dirname as ES,resolve as Np,sep as Gp}from"node:path";import{existsSync as Lr,readFileSync as aS,writeFileSync as cS,mkdirSync as uS,rmSync as Er,readdirSync as lS,statSync as pS}from"node:fs";import{join as Ft}from"node:path";import{join as ui}from"node:path";import{createHash as Ap}from"node:crypto";function iS(e){return Pr(e)}function Pr(e){return ui(e,"tmp","clone")}function li(e){return ui(e,"tmp","tree")}function sS(e){return e?`__sp_${Ap("sha256").update(e).digest("hex").substring(0,6)}`:""}function kp(e){if(!/[\\/]/.test(e))return e;let t=Ap("sha256").update(e).digest("hex").substring(0,8);return`${e.replace(/[\\/]/g,"_")}__b_${t}`}function ha(e,t,n,r,o){let i=`${kp(r)}${sS(o)}`;return ui(Pr(e),t,n,i)}function wr(e,t,n,r){return ui(li(e),t,n,kp(r))}var dS=1440*60*1e3,mS=600*1e3,fS=2*1024*1024*1024,hS=50,Ip=".octocode-clone-meta.json",Pn=null;function gS(e){return typeof e=="object"&&e!==null}function yS(e){if(!gS(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 ga(e){let t=Ft(e,Ip);if(!Lr(t))return null;try{return yS(JSON.parse(aS(t,"utf-8")))}catch{return null}}function Tn(e,t){try{cS(Ft(e,Ip),JSON.stringify(t,null,2),"utf-8")}catch{}}function Op(e){return Date.now()<new Date(e.expiresAt).getTime()}function En(e){let t=ga(e);return t?Op(t)?Lr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function RS(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return dS}function SS(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return fS}function bS(){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 hS}function Ln(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+RS()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function vt(e){let t=Ft(e,"..");try{Lr(t)||uS(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 di(e){try{Lr(e)&&Er(e,{recursive:!0,force:!0})}catch{}}function Tr(e){try{return pS(e).isDirectory()}catch{return!1}}function Xt(e){try{return lS(e)}catch{return[]}}function*Fp(e){for(let t of Xt(e)){let n=Ft(e,t);if(Tr(n))for(let r of Xt(n)){let o=Ft(n,r);if(Tr(o))for(let i of Xt(o)){let s=Ft(o,i);Tr(s)&&(yield s)}}}}function _p(e){for(let t of[...Xt(e)]){let n=Ft(e,t);if(Tr(n)){for(let r of[...Xt(n)]){let o=Ft(n,r);if(Tr(o)&&Xt(o).length===0)try{Er(o,{recursive:!0,force:!0})}catch{}}if(Xt(n).length===0)try{Er(n,{recursive:!0,force:!0})}catch{}}}}function CS(e){let t=0;for(let n of Fp(e))try{let r=ga(n);(!r||!Op(r))&&(Er(n,{recursive:!0,force:!0}),t++)}catch{}return t}function xS(e){let t=[];for(let n of Fp(e)){let r=ga(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??hr(n)})}return t}function PS(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{Er(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function vp(e){if(!Lr(e))return 0;let t=0;try{t+=CS(e)}catch{return t}_p(e);let n=PS(xS(e),SS(),bS());return t+=n,n>0&&_p(e),t}function pi(e){return vp(Pr(e))}function wn(e){return vp(li(e))}function LI(e){Pn||(pi(e),wn(e),Pn=setInterval(()=>{pi(e),wn(e)},mS),Pn.unref())}function AI(){Pn&&(clearInterval(Pn),Pn=null)}async function Ra(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=Np(Mp(a,n));if(!c.startsWith(a+Gp)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(u.hit&&!i&&ya(c)){let b=Ep(c,a),A=ma();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:da,warnings:fa(!0,!1),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await Q(o),p;try{p=(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 d=m,f=ma(),g=[];for(let b of d){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=fp(b.name,{lowercase:!0,leadingDot:!0});if(Pp.has(A)){f.binary+=1;continue}g.push(b)}f.fileLimit=Math.max(0,g.length-xr);let R=g.slice(0,xr),h=o?.token,y=await Tp(R,xp,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>ci){f.totalSizeLimit=y.length-b;break}S+=M.length,C.push({entry:A,content:M})}wn(s),vt(a),ya(c)&&TS(c,{recursive:!0,force:!0}),Dp(c,{recursive:!0,mode:448});let P=[];for(let{entry:b,content:A}of C){let M=Np(Mp(a,b.path));if(!M.startsWith(a+Gp)){f.pathTraversal+=1;continue}let B=ES(M);ya(B)||Dp(B,{recursive:!0,mode:448}),wS(M,A,"utf-8"),P.push({path:b.path,size:A.length,type:"file"})}let T=Ln(e,t,r,"treeFetch",void 0,void 0,p);Tn(a,T);let L=wp(f),k=L,w=f.nonFile>0;return{localPath:c,repoRoot:a,files:P,fileCount:P.length,totalSize:S,complete:L,verified:k,...p?{commitSha:p}:{},...w?{hasSubdirectories:!0}:{},directoryEntryCount:d.length,eligibleFileCount:g.length,savedFileCount:P.length,skipped:f,limits:da,warnings:fa(L,k),cached:!1,expiresAt:T.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}import{writeFileSync as vS,mkdirSync as DS,existsSync as Up}from"node:fs";import{join as MS,dirname as NS,resolve as GS,sep as HS}from"node:path";import{RequestError as Ta}from"octokit";import{completeMetadata as Sa}from"@octocodeai/octocode-core";var x=new Proxy({},{get(e,t){return Sa.toolNames[t]},ownKeys(){return Object.keys(Sa.toolNames)},getOwnPropertyDescriptor(e,t){let n=Sa.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as LS}from"@octocodeai/octocode-core";var ba=new Proxy({},{get(e,t){return LS.tools[t]?.description??""}});import{completeMetadata as AS}from"@octocodeai/octocode-core";function Ca(e){return Object.prototype.hasOwnProperty.call(AS.tools,e)}import{completeMetadata as kS}from"@octocodeai/octocode-core";function xa(){return kS.baseSchema}var _S=new Proxy({},{get(e,t){return xa()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(xa())]))},getOwnPropertyDescriptor(e,t){let n=xa();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});function Pa(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 wa(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(d=>d.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let p=s.replace(/\.[^/.]+$/,"");return c.filter(d=>d.name===s?!1:!!d.name.startsWith(p+".")).forEach(d=>u.push(d.path)),u.length===0&&p.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==p&&g.length>=3&&(p.startsWith(g)||g.startsWith(p))}).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 Ae(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=V(t),p=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await wa(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Pa(i,m)]),{...l,...p&&{scopesSuggestion:p}}}async function OS(e,t,n,r,o,i){let s=V(t),a=await wa(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Pa(o,a)]),s}async function Hp(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:Ct.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:Ct.DECODE_FAILED.message,type:"unknown",status:422}}}async function Bp(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"?Hp(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return V(i)}}async function FS(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 Ae(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 p=await Bp(e,t,n,l.sha,r);return"error"in p?p:{data:{rawContent:p.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return V(s)}}async function Ar(e,t,n={}){try{let r=await Q(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(d){if(d instanceof Ta&&d.status===304)return{data:{rawContent:"",resolvedRef:a||"HEAD"},status:304,etag:n.ifNoneMatch,notModified:!0};if(d instanceof Ta&&d.status===404)if(a){let f=await IS(r,d,c,o,i,s,a,t);if("result"in f)u=f.result,l=f.actualBranch;else return f}else return await OS(r,d,o,i,s,a);else{if(d instanceof Ta&&d.status===413)return await FS(r,o,i,s,a||l,t);throw d}}let p=u.data,m=xn(u.headers);if(Array.isArray(p))return{error:Ct.PATH_IS_DIRECTORY.message(x.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in p&&p.type==="file"){let d=typeof p.content=="string"?p.content:"",f=p.size??0,g;if(d.length>0)g=await Hp(d,s);else if(f>0&&"sha"in p&&typeof p.sha=="string"&&p.sha)g=await Bp(r,o,i,p.sha,s);else return{error:Ct.FILE_EMPTY.message,type:"unknown",status:404};if("error"in g)return g;if(!l&&!a)try{l=await Ae(o,i,t)}catch{}return{data:{rawContent:g.data,branch:l||void 0,resolvedRef:l||a||"HEAD"},status:200,rawResponseChars:N(p),...m?{etag:m}:{}}}return{error:Ct.UNSUPPORTED_TYPE.message(p.type),type:"unknown",status:415}}catch(r){return V(r)}}async function Ea(e,t,n,r,o,i=!1){let s=zt(),a=wr(s,e,t,r),c=GS(MS(a,n));if(!c.startsWith(a+HS)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=En(a);if(!i&&u.hit&&Up(c))return{localPath:c,repoRoot:a,path:n,size:Lp(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await Ar({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}`)}wn(s),vt(a);let p=NS(c);Up(p)||DS(p,{recursive:!0,mode:448}),vS(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,d=Ln(e,t,m,"treeFetch");return Tn(a,d),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:d.expiresAt,owner:e,repo:t,branch:m}}import{ContentSanitizer as Ia}from"@octocodeai/octocode-engine/contentSanitizer";function kr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function rt(e){return kr(e).length}function mi(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(`
|
|
11
11
|
`),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=O.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 BS=/\.(?:md|markdown|mdx)$/i;function US(e){return BS.test(e.split(/[?#]/,1)[0]??e)}function Qp(e,t){return US(t)?$S(QS(e)):null}function fi(e,t){let n=Qp(e,t);if(n===null||n.length===0)return null;let r=[];return jp(n,r),r.join(`
|
|
12
12
|
`)}function $p(e,t){let n=Qp(e,t);return n===null?null:n.map(zp)}function QS(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 $S(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 jp(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}`),jp(n.children,t)}}function zp(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(zp)}}import{getConfigSync as jS,DEFAULT_OUTPUT_CONFIG as zS}from"@octocodeai/config";function Dt(){try{return jS().output.pagination.defaultCharLength}catch{return zS.pagination.defaultCharLength}}var Wp=1e5;function LO(e){let t=Math.min(Math.max(Dt(),1),Wp),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,Wp)}function WS(e,t,n){return O.byteSliceContent(e,t,n)}function hi(e,t){return O.byteToCharOffset(e,t)}function Vp(e,t){return O.charToByteOffset(e,t)}function Kp(e){return O.charToByteOffset(e,e.length)}function _O(e,t,n){let r=WS(e,t,t+n);return{charOffset:hi(e,t),charLength:r.length,text:r}}function La(e,t,n,r){return O.sliceContent(e,t,n,r)}function gi(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Kp(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,p,m,d,f,g;if(o==="bytes"){let R=Math.min(t,s),h=Math.min(R+n,s);p=hi(e,R),m=hi(e,h),m<i&&Vp(e,m)<h&&(m+=1);let y=La(e,p,m-p);c=y.text,p=y.charOffset,m=y.charOffset+y.charLength,u=y.byteOffset,l=y.byteOffset+y.byteLength,d=l<s;let S=r.actualOffset??R;f=Math.floor(S/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let R=La(e,t,n);c=R.text,p=R.charOffset,m=R.charOffset+R.charLength,u=R.byteOffset,l=R.byteOffset+R.byteLength,d=m<i;let h=r.actualOffset??p;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:d?l:void 0,charOffset:p,charLength:c.length,totalChars:i,nextCharOffset:d?m:void 0,hasMore:d,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:g}}function FO(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function Aa(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}function vO(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
|
|
13
13
|
`){let u=e.lastIndexOf(`
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@octocodeai/octocode-tools-core",
|
|
3
3
|
"description": "Core tool implementations for Octocode: GitHub, local filesystem, LSP, and package search tools.",
|
|
4
|
-
"version": "18.1.
|
|
4
|
+
"version": "18.1.2",
|
|
5
5
|
"author": "Guy Bary <bgauryy@octocodeai.com>",
|
|
6
6
|
"bugs": "https://github.com/bgauryy/octocode/issues",
|
|
7
7
|
"dependencies": {
|
|
8
8
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
9
9
|
"@octocodeai/config": "18.0.1",
|
|
10
10
|
"@octocodeai/octocode-core": "18.2.0",
|
|
11
|
-
"@octocodeai/octocode-engine": "18.1.
|
|
11
|
+
"@octocodeai/octocode-engine": "18.1.2",
|
|
12
12
|
"@octokit/oauth-methods": "^6.0.2",
|
|
13
13
|
"@octokit/plugin-throttling": "^11.0.3",
|
|
14
14
|
"@octokit/request": "^10.0.10",
|